body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have a web page with a set of icons that are grey by default:</p>
<p><img src="https://i.stack.imgur.com/WrlEu.png" alt="enter image description here" /></p>
<p>If a user clicks one, it toggles green (<code>.toggleClass('green')</code>):</p>
<p><img src="https://i.stack.imgur.com/0pxOp.png" alt="enter image description here" /></p>
<p>If a user clicks a green one, it toggles back to grey (<code>.removeClass('green')</code>).</p>
<p>Only one icon can be green at any given time, so if you have a green icon and you click a grey icon, the icon that was originally green will change to grey while the one you clicked would change to green.</p>
<hr />
<p>Each of these icons corresponds to a section on the page.</p>
<ul>
<li><p>If all the icons are grey, all the sections on the page are visible.</p>
</li>
<li><p>If one icon is green, only that icon's section is visible, the sections represented by the grey icons are hidden.</p>
</li>
</ul>
<hr />
<p>Here is the code that controls that behavior:</p>
<pre><code>$(document).on 'click', '.toggler', ->
icons = [$('#toggle-videos'),$('#toggle-images'),$('#toggle-words')]
sections = [$('#videos'),$('#images'),$('#words')]
if $(this).hasClass('green')
$(this).toggleClass('green')
i = 0
while i < sections.length
sections[i].show()
i++
else
$(this).addClass('green')
i = 0
while i < icons.length
if icons[i][0] != $(this)[0]
icons[i].removeClass('green')
sections[i].hide()
else
j = 0
while j < sections.length
if $(this).attr('id').indexOf(sections[j].attr('id')) != -1
sections[j].show()
j++
i++
</code></pre>
<p>I feel it is very hard to understand what this code does simply by reading it. I feel I am missing a simpler way to accomplish the following:</p>
<ul>
<li>Associate an icon with a specific section on the page</li>
<li>Keep the green state of an icon associated with the visibility of a specific section on the page</li>
</ul>
<p>My primary concerns with the code:</p>
<ul>
<li>I have several nested if statements with nested while statements</li>
<li>I am checking the relationship between a section and an icon by checking if the <code>icon.id</code> has part of the string (<code>this</code> is the icon element and <code>j</code> is a counter):
<code>if $(this).attr('id').indexOf(sections[j].attr('id')) != -1</code></li>
</ul>
<p><strong>Is this acceptable for javascript or is there a better way?</strong></p>
| [] | [
{
"body": "<p>I usually don't review CoffeeScript, because I find it too hard too read. Your code is not too hard to read, so I will give it a shot.</p>\n\n<p>I think in essence, you are trying too hard to show all but the one section, I would simply had all sections, and then show the one section you need. I would also cache <code>$(this)</code> for speed reasons and use more <code>[].forEach</code> for readability. Finally, <code>this.id</code> is more readable and faster than <code>$(this).attr('id')</code></p>\n\n<p>This untested counter proposal should illustrate what I mean:</p>\n\n<pre><code>$(document).on 'click', '.toggler', ->\n //Look up by `id`\n icons = ['toggle-videos','toggle-images','toggle-words']\n //Show via '#` + id\n sections = ['#videos','#images','#words']\n $this = $(this);\n if $this.hasClass('green')\n $this.removeClass('green')\n sections.forEach( (section) => section.show() )\n else\n $this.addClass('green')\n sections.forEach( (section) => section.hide() )\n sections[ icons.indexOf( this.id ) ].show(); \n</code></pre>\n\n<p>Personally, and that is a bit more hackish, I would abuse the fact that the section id is postfixed to the toggle id and do this:</p>\n\n<pre><code>$(document).on 'click', '.toggler', ->\n $this = $(this);\n if $this.hasClass('green')\n $this.removeClass('green')\n sections.forEach( (section) => section.show() )\n else\n $this.addClass('green')\n sections.forEach( (section) => section.hide() )\n sections[ this.id.split(\"-\")[1] ].show();\n</code></pre>\n\n<p>I might be tempted to put a <code>toggleClass</code> in there as well, but somehow the <code>if</code> and then the <code>removeClass</code> or <code>addClass</code> make this code easier to parse for me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:16:12.653",
"Id": "80755",
"Score": "0",
"body": "I did not know I could cache $(this) (I only 'do javascript' when I HAVE to). You made some good points about performance, hadn't even considered it up to this point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:51:26.687",
"Id": "80786",
"Score": "0",
"body": "It's interesting you find CoffeeScript harder to read; I have the exact opposite experience. These days I only write plain JS for CodeReview answers :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:19:16.297",
"Id": "80796",
"Score": "0",
"body": "I think I'm getting old and (c)rusty ;]"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:56:55.787",
"Id": "46265",
"ParentId": "46262",
"Score": "1"
}
},
{
"body": "<p>I would propose to use data attributes. E.g. icons have data-section-id attribute.</p>\n\n<pre><code>if $(this).hasClass('green') // all should become greynow\n{\n $('div.section').show(); // show all sections\n $(this).removeClass('green');\n}\nelse // we turn one sectio on\n{\n $('div.section').hide(); // show all sections\n $('#'+ $(this).data('sectionId')).show(); // show a corresponding section\n $('li.icon').removeClass('green'); // turn all icons off\n $(this).addClass('green'); // turn current one on\n}\n</code></pre>\n\n<p>But of course, that requires some changes in HTML structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:14:43.907",
"Id": "80753",
"Score": "0",
"body": "I have been using data attributes elsewhere in the same app to come up with a similar solution - glad to see it came up here. Not a bad idea."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:10:19.083",
"Id": "46266",
"ParentId": "46262",
"Score": "2"
}
},
{
"body": "<p>jQuery generally operates on <em>collections</em> of elements, so you rarely need to old-fashioned loops and incrementing indexes. In addition, CoffeeScript has many syntactic niceties for dealing with collections, which means that you hardly ever have to do old-fashioned looping.</p>\n\n<p>I'd suggest keeping the link-to-section relationship in the HTML, like so:</p>\n\n<pre><code><a class=\"toggle\" href=\"#videos\">...</a>\n<a class=\"toggle\" href=\"#words\">...</a>\n<a class=\"toggle\" href=\"#images\">...</a>\n</code></pre>\n\n<p>(using <code>href</code> has the added benefit that it'll still work, even with no JavaScript support)</p>\n\n<p>Then, use that in your code to hide/show what's needed, e.g.</p>\n\n<pre><code>$ ->\n toggles = $ \".toggle\"\n sections = $ \".section\" # or whatever selector works\n\n toggles.on \"click\", (event) ->\n event.preventDefault()\n\n target = $ this\n section = $ target.attr(\"href\") # get the associated section\n\n if target.hasClass(\"selected\")\n target.removeClass(\"selected\")\n sections.show() # show all sections\n else\n toggles.removeClass(\"selected\") # remove selection from other links\n target.addClass(\"selected\") # select the clicked link\n sections.not(section).hide() # hide other sections\n section.show() # show only the relevant section\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/h8MvL/1/\" rel=\"nofollow\">Here's a demo</a></p>\n\n<p>I've changed the selection class to <code>selected</code> rather than <code>green</code>, because \"green\" isn't a very descriptive name - or, in a sense, it's <em>much too</em> descriptive. Either way, the name's tied to the <em>look</em> rather than the <em>purpose/function</em> of the class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:19:01.937",
"Id": "80756",
"Score": "0",
"body": "Good point about the 'green' to 'selected' - I should have made that change before I even posted this here. Someone else mentioned using data attributes, it seems you use the actual href attribute to fulfill a similar role. I like this because it would give feedback on mouse-hover about what is going to happen."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:24:22.130",
"Id": "80757",
"Score": "1",
"body": "@Ecnalyr Using data attributes is a perfectly valid solution too. I only use the `href` attribute here, because what we need to store - an element selector - has exactly the same syntax as a regular anchor link. Otherwise, I'd use a data attribute too. But, as mentioned, the links will make the page scroll to the correct section even if you remove all the javascript/coffeescript. I.e. it degrades gracefully"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:30:59.210",
"Id": "80759",
"Score": "0",
"body": "Also nice trick with sections.not(section). Probably doesn't make much sense in this case. But is more correct if show/hide will be replaced with fadeIn/Out e.g."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:38:28.387",
"Id": "80761",
"Score": "0",
"body": "@StepanStepanov That depends how you the look & feel you want for the page; the original code just uses show/hide. But yes, you can just replace it with fadeIn/Out, if you want."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:12:36.073",
"Id": "46267",
"ParentId": "46262",
"Score": "2"
}
},
{
"body": "<p>To start with, you shouldn't use \"green\" as a class name. The name should be something generic, like \"selected\" or \"current\". Your CSS will cause the current selection to be rendered as a green icon, but you shouldn't hard-code that assumption into the name of the CSS class itself.</p>\n\n<p>What you have described is essentially a radio button (with the additional feature that <a href=\"https://stackoverflow.com/a/8318129/1157100\">clicking on the currently selected item will deselect everything</a>). Therefore, if you start with radio buttons, <a href=\"https://stackoverflow.com/a/3896259/1157100\">styled with images using CSS</a>, most of your work will be done already!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:32:03.833",
"Id": "80760",
"Score": "0",
"body": "I would like the radio button idea to work - and it would ordinarily. But I've failed to style with iconfonts in the past (probably my fault, not the fault of css itself), so I always stray away from this idea. I may have to revisit it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:22:36.273",
"Id": "46269",
"ParentId": "46262",
"Score": "1"
}
},
{
"body": "<p>If you like fun jQuery chains, the following should work for you.</p>\n\n<pre><code>$(document).on 'click', '.toggler', ->\n targetSection = $(this)\n .parent()\n .find('green')\n .removeClass('green')\n .end()\n .end()\n .addClass('green')\n .data( 'target' )\n $('.section').not(targetSection).hide()\n $(targetSection).show()\n</code></pre>\n\n<p>One thing is that you would have to modify your icons to have <code>data-</code> attributes like so:</p>\n\n<pre><code><a id=\"video-toggle\" data-target='#videos'>...</a>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:13:13.617",
"Id": "46316",
"ParentId": "46262",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46267",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:18:09.747",
"Id": "46262",
"Score": "7",
"Tags": [
"coffeescript"
],
"Title": "Avoiding nested conditionals and comparing strings"
} | 46262 |
<p><a href="http://learnyouahaskell.com/" rel="nofollow">Learn You a Haskell</a> gives this <a href="http://learnyouahaskell.com/starting-out#im-a-list-comprehension" rel="nofollow">exercise</a>:</p>
<blockquote>
<p>Here's a problem that combines tuples and list comprehensions: which
right triangle that has integers for all sides and all sides equal to
or smaller than 10 has a perimeter of 24? First, let's try generating
all triangles with sides equal to or smaller than 10:</p>
</blockquote>
<p>Here's my solution in Scala. Note that I'm ignoring the right triangle part.</p>
<pre><code>val a = List.range(1,11)
val b = List.range(1,11)
val c = List.range(1,11)
def sumsEqualsTo24(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] =
if(x + y + z == 24) Some( (x,y,z) ) else None
def pythagTriple(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] = {
if( Math.pow(x, 2) + Math.pow(y, 2) == Math.pow(z, 2) )
Some( (x,y,z) )
else None
}
</code></pre>
<p><strong>Using flatMap</strong></p>
<pre><code>val xs: List[(Int, Int, Int)] = a.flatMap(x =>
b.flatMap(y =>
c.flatMap(z => sumsEqualsTo24(x, y, z) ) ) )
val ys: List[(Int, Int, Int)] = xs.flatMap{a => pythagTriple(a._1, a._2, a._3)}
</code></pre>
<p><strong>Using for-comprehension</strong></p>
<pre><code>for {
a <- List.range(1, 11)
b <- List.range(1, 11)
c <- List.range(1, 11)
xs <- sumsEqualsTo24(a,b,c)
_ <- pythagTriplebar(xs._1, xs._2, xs._3)
} yield (a,b,c)
</code></pre>
<p>Could you please critique my code?</p>
| [] | [
{
"body": "<p>There is no need for <code>List</code>s <code>a</code>,<code>b</code>, and <code>c</code>, only one of them is needed.</p>\n\n<p>So the flatmap could just use <code>a</code> three times: </p>\n\n<pre><code>a.flatMap(x => \n a.flatMap(y => \n a.flatMap(z => sumsEqualsTo24(x, y, z))))\n</code></pre>\n\n<p>For comprehensions can use extractors as you would in pattern matching or declaring a val.\nYou may find this more readable:</p>\n\n<pre><code> ...\n c <- List.range(1, 11) \n (x,y,z) <- sumsEqualsTo24(a,b,c)\n _ <- pythagTriplebar(x,y,z)\n} yield (a,b,c)\n</code></pre>\n\n<p>Likewise you can have</p>\n\n<pre><code>val ys = xs.flatMap{case (x,y,z) => pythagTriple(x,y,z)}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T13:07:23.620",
"Id": "48572",
"ParentId": "46270",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:36:52.177",
"Id": "46270",
"Score": "2",
"Tags": [
"scala"
],
"Title": "Find Pythagorean Triple with Perimeter == 24"
} | 46270 |
<p>I have written a numbers to text challenge for some people in my organisation to practice their Python skills. I am an economist working with pandas, but I am trying to teach them some stuff about general programming as well. I am not a trained computer scientist or anything, so what I know is just what I have picked up along the way.</p>
<p>I have written a solution to the numbers to text problem and would like feedback on the following:</p>
<ol>
<li>Any general comments about the functions. I find the tuple to text function to be a bit scary to look at.</li>
<li>Any suggestions as to how to write helpful comments. Squeezing them in next to lines of code themselves seems to confuse the reading, but creating new lines makes the function look
massive and it can be hard to read - suggestions welcome. </li>
<li>Any other possible systems that are simple to implement.</li>
</ol>
<p>Incidentally, solutions deliberately do not make use of user defined classes. A full description of the problem and the method I used to solve it is provided:</p>
<pre><code>#####********************************************************************************#####
##### DESCRIPTION #####
#####********************************************************************************#####
""" The task is to write a number to text program that can convert any number between
minus 2 billion and plus 2 billion. It sounds deceptively simple...
Examples:
10 -> ten
121 -> one hundred and twenty one
1032 -> one thousand and thirty two
11143 -> eleven thousand one hundred and forty three
1200011 -> one million two hundred thousand and eleven
Note: if you ever want to turn a nested list into a single list containing all the
elements of the nested lists, use itertools.chain()
e.g.
In [1]: l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [2]: l2 = list(itertools.chain(*l))
In [3]: l2
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The solution provided here is based upon the following:
+ If the length of a string representation of a number id divisible by three, then
if that number is split into tuples of three consecutive numerical characters, then
by looking at the character in the tuple and its index position in the tuple, it
is possible to map the character to an English word. For example:
number: '983123214'
tuples: ('9', '8', '3') ('1', '2', '0')
Notice that the characters in the 0th and 2nd index positions in each tuple
will always map to the English words for those particular numbers (except '0'
which maps to no English word as the word 'zero' is not used when annunciating
a number:
'9' : 'nine'
'3' : 'three'
'1' : 'one'
'0' : ''
However, the character in the 1st index position in each tuple will always map to
the and english word that represents the number in a unit of tens, except '0'
which is not used in speech in the same way:
'8' : 'eighty'
'2' : 'twenty'
'0' : ''
Of course the character in the 0th index position in each tuple always represents the
number in a unit of hundreds:
'9' : 'nine' + 'hundred'
'1' : 'one' + 'hundred'
The exception to this rule is when the character in the 1st index position is '0'. In
this case, there are no hundred units:
'0' : ''
A further exception of importance is when the character in the 1st index position is
'1'. Unfortunately the numbers between 10 to 19, do not behave in the same way as
numbers between 20 to 21, 30 to 31 etc this is because to obtain the english word
for the tuple:
tuple: ('1', '2', '3')
we can follow the basic rules relating to index positions as above to get:
'1' : 'one' + 'hundred'
'2' : 'twenty'
'3' : 'three'
The sum of the above will yield:
sum: 'one hundred twenty three'
But this will not work with the following tuple:
tuple : ('4', '1', '2')
because applying the above rules relating to index positions we would get:
'4' : 'four' + 'hundred'
'1' : 'ten'
'2' : 'two
sum : 'four hundred ten two'
when in fact we want 'four hundred eleven'.
Therefore when a '1' character is found in the 1st index position a new method is
needed to determine how to translate that character into English word. The simplest
method it seems to me is to use the character in the 2nd index position to determine
the English word when '1' is observed in the 1st index position. When the following
characters are observed in index position 2, and the character at index position 1
is '1', then:
'0' : 'ten'
'1' : 'eleven'
'2' : 'twelve'
The beauty of this method is that whenever a string of numerical characters can be
divided into tuples of three elements each, the above rules apply in every case. Of
course, we also need to specify the unit level of the tuple itself to get the full
story:
number: 312030967
tuples: ('3', '1', '2') ('0', '3', '0') ('9', '6', '7')
units: 'million', 'thousand', ''
The last tuple does not have a unit as the 'hundred' is already implied by the three
elements in the tuple. The relevant unit can just be added at the end of evaluating
each character in each tuple. Combining the above facts we see that in reference to
the above system:
'3' : 'three' + 'hundred'
'1' : ''
'2' : 'twelve'
unit : 'million'
'0' : ''
'3' : 'thirty'
'0' : ''
unit : 'thousand'
'9' : 'nine' + 'hundred'
'0' : ''
'7' : 'seven
Naturally the above only works if the number entered has a length that gives no
remainder when divided by 3. Therefore the first thing the program will do is
to make sure that whatever number the user enters its length will be divisible by 3
without remainder. In order to achieve this the number entered is padded with '0'
characters until the length of the resulting string is 12. Why 12? Well the program
specifies that the program must work for numbers between -2bn and 2bn. A string
representation of the number 2bn is 10 characters long. Therefore to make the string
divisible by 3 without remainder, 2 '0' characters are padded to the beginning. The
number of '0' pads will obviously depend on the number entered by the user. When a
negative number is entered the '-' symbol is stripped out before the zero padding.
The result is then split into a system of tuples each with three elements, and the
are evaluated with reference to the above described system.
In order to make the evaluation a dictionary is created. The keys of the dictionary
are the characters, '1' to '9'. Other than the values of key '1', the values are
themselves dictionary. These sub-dictionaries have keys that are tuples that contain
integer values that are designed to mirror the index values of the tuples of
characters that are being evaluated. For example:
dict extract : {'2' : {(0, 2) : 'two', (1,) : 'twenty'}}
number : '222'
tuple : ('2', '2', '2')
When evaluating the tuple, the program will first identify which character is found
at index 0. This is '2'. Then it will access the dict with key '2'. This will give
access to the sub dictionary. Now if the index position (still 0) is found in the
tuple key (0, 2) of the sub-dictionary, then the value associated with that key is
returned : 'two'. And so on.
In the case of the character '1', there is a further nested sub-dictionary which will
use the character found in the 2nd index point of the tuple being evaluated when the
character '1' in in index position 1, in order to get the proper English
representation two character numbers beginning with '1'.
There is a system of adding the word 'and' at various points, but this is not
discussed in detail here.
"""
</code></pre>
<hr>
<pre><code>#####********************************************************************************#####
##### Functions and Dictionaries #####
#####********************************************************************************#####
import itertools
nums_dict = { '1' : {(0, 2) : 'one', (1,) : {'0' : 'ten',
'1' : 'eleven',
'2' : 'twelve',
'3' : 'thirteen',
'4' : 'fourteen',
'5' : 'fifteen',
'6' : 'sixteen',
'7' : 'seventeen',
'8' : 'eighteen',
'9' : 'ninteen',}},
'2' : {(0, 2) : 'two', (1,) : 'twenty'},
'3' : {(0, 2) : 'three', (1,) : 'thirty'},
'4' : {(0, 2) : 'four', (1,) : 'fourty'},
'5' : {(0, 2) : 'five', (1,) : 'fifty'},
'6' : {(0, 2) : 'six', (1,) : 'sixty'},
'7' : {(0, 2) : 'seven', (1,) : 'seventy'},
'8' : {(0, 2) : 'eight', (1,) : 'eighty'},
'9' : {(0, 2) : 'nine', (1,) : 'ninty'}
}
def get_number(message1, message2):
"""
message1 : string
message2 : string
return : string
Returns user input string if capable of being cast to integer, and between minus
2 billon and positive 2 billion, else self.
"""
user_input = raw_input(message1)
try:
if int(user_input) < -2000000000 or int(user_input) > 2000000000:
print message2
return get_number(message1, message2)
except ValueError:
print 'That was not valid input'
return get_number(message1, message2)
return user_input
def zero_padding(user_input):
"""
user_input : string
return : string
Returns user input stripped of a minus sign (if present) and padded to the extent
necessary with zeros to ensure that the returned string is 12 characters in length.
"""
if user_input[0] == '-':
user_input = user_input[1:]
modified_input = ('0'*(12 - len(user_input))) + user_input
return modified_input
def convert_to_tuple_list(modified_input):
"""
modified_input : string
return : tuple
Returns tuple with four elements, each a tuple with three elements.
Assumes modified_input has length 12.
"""
tuple_list = tuple((tuple(modified_input[x:x+3]) for x in xrange(0, 10, 3)))
return tuple_list
def tuple_to_text(single_tuple, unit_string, nums_dict = nums_dict):
"""
single_tuple : tuple
unit_string : string
nums_dict : dict
return : list
Returns list of alpha strings that represent text of numerical string characters found
in single_tuple. The final element of the list is the unit_sting.
"""
word_list = [[],[]]
if ''.join(single_tuple) == '000': # if all characters are '0' return empty list
return list(itertools.chain(*word_list))
if single_tuple[0] != '0': # if the fist element of the tuple is not '0'
word_list[0].extend([nums_dict[single_tuple[0]][(0, 2)], 'hundred'])
if single_tuple[1] != '0': # if the second element of the tuple is not '0'
if single_tuple[1] == '1': # Special case where second character is '1'
word_list[1].extend(['and', nums_dict['1'][(1,)][single_tuple[2]], unit_string])
else:
try: #if third element is zero then this will generate an error below as zero
#is not in the nums_dict.
word_list[1].extend(['and', nums_dict[single_tuple[1]][(1,)],
nums_dict[single_tuple[2]][(0, 2)], unit_string])
except KeyError:
word_list[1].extend(['and', nums_dict[single_tuple[1]][(1,)], unit_string])
else:
if single_tuple[2] != '0': # if first element of tuple is zero but the second is not
word_list[1].extend(['and', nums_dict[single_tuple[2]][(0, 2)], unit_string])
else:
word_list[1].append(unit_string)
if len(word_list[0]) == 0: # if no 'hundreds' then remove 'and'
word_list[1].remove('and')
return list(itertools.chain(*word_list))
def create_text_representation(tuple_list):
"""
tuple_list : tuple
return : string
Returns string of words found in each list created by calling the tuple_to_text
function.
"""
list1 = tuple_to_text(tuple_list[0], 'billion')
list2 = tuple_to_text(tuple_list[1], 'million')
list3 = tuple_to_text(tuple_list[2], 'thousand')
list4 = tuple_to_text(tuple_list[3], '')
#If any of the lists 1/2/3 are not empty, but list4 contains no hundred value,
#insert an 'and' into list4 at index position 1 if tuple_list[3] does not contain
#elements all of which are equal to '0'
if any([len(list1) != 0, len(list2) != 0, len(list3) != 0])\
and 'hundred' not in list4 and ''.join(tuple_list[3]) != "000":
list4.insert(0, 'and')
complete_list = itertools.chain(*[list1, list2, list3, list4])
complete_list = [elem for elem in complete_list if not type(elem) is list]
return " ".join(complete_list)
def message(user_input, text_representation):
"""
user_input : string of numerical characters (possible including the minus sign)
text_representation : string of alphas
return : formatted string
Returns string formatted to include 'minus' where necessary, the original number
provided, and the textual representation of that number.
"""
message = \
"""
The number {0} written as text is :
{1}{2}
"""
if user_input[0] == '-':
return message.format(user_input, 'minus ', text_representation)
return message.format(user_input, '', text_representation)
#####********************************************************************************#####
##### Run Method #####
#####********************************************************************************#####
user_input = get_number("Please enter a number between -2 billion and 2 billion: ",
"That number is out of range")
modified_input = zero_padding(user_input)
tuple_list = convert_to_tuple_list(modified_input)
text_representation = create_text_representation(tuple_list)
print message(user_input, text_representation)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:56:26.877",
"Id": "80769",
"Score": "0",
"body": "The amount of documentation in your code is impressive. I have no time to have a look right now but a pretty similar question was asked recently, maybe you'll find something relevant for you on http://codereview.stackexchange.com/questions/43744/improving-a-number-to-word-converter-to-better-match-pythonic-standards/43763#43763 ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:02:31.300",
"Id": "80770",
"Score": "0",
"body": "Thanks, yes its a simple problem, but for training purposes I try to explain the solutions as best as possible. Actually, it helps me to then write the code better..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:09:53.947",
"Id": "80774",
"Score": "0",
"body": "@Josay's referring to my thread, which I saw you've commented on as well. The way to do this best is to split into lists almost every word you're going to be using and create specific functions for less than a thousand and for more than a thousand, as well as a function for splitting by thousands as well. :) The documentation on this really is impressive, and I hope you get it working for you. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:17:41.217",
"Id": "80777",
"Score": "0",
"body": "It seems to work perfectly, I was just wondering if this was a good way to tackle the problem or not really, before I teach my staff how to solve problems in python. The issue is I am not an expert at all, so I am always worried I am giving them bad info. We use programming in a very ad hoc way i.e. to achieve data management tasks on the fly, so none of us have every really become real programmers. I'm going to check out your solution for sure..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:22:40.563",
"Id": "80780",
"Score": "0",
"body": "Concerning the amount of documentation, wouldn't it be better to have a minimal but sufficient documentation in the code and to put the details in a Sphinx documentation or something like that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:25:05.817",
"Id": "80781",
"Score": "0",
"body": "Almost certainly yes, but as these are training materials, it makes my life easier just to put everything in one place :-)"
}
] | [
{
"body": "<p>I will review a single function the <code>get_number()</code>.</p>\n\n<ol>\n<li><p>From what I have seen in your code there is completely no benefit of passing messages as variables <code>message1</code> and <code>message2</code>. It is easer to read code which looks like this:</p>\n\n<pre><code>user_input = raw_input(\"Please enter a number between -2 billion and 2 billion: \")\n</code></pre>\n\n<p>If you still decide to pass it as variables you should give a descriptive name to your message variable</p>\n\n<pre><code>user_input = raw_input(msg_ask_to_enter_value)\n</code></pre></li>\n<li><p>Recursion will reach limits and will throw an exception if I keep entering wrong values. It's not a serious issue, as I would need to repeat for 1000 times but still its better not to leave this bug especially when it is so easy to get around it. Instead of recursion use a loop:</p>\n\n<pre><code>def get_number():\n boundary_low = -2000000000\n boundary_high = 2000000000\n\n while True\n input = raw_input('Please inter a number in range of %s to %s: ' % (\n boundary_low, boundary_high))\n try:\n value = int(input)\n except:\n print 'That was not a number'\n else:\n if boundary_low <= value <= boundary_high:\n return value\n else:\n print 'Number out of boundaries'\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:29:42.517",
"Id": "80782",
"Score": "0",
"body": "The point about the messages is well taken. I suppose if I were varying the range of accepted inputs, if could make sense to have different messages, but actually I could just use string formatting as you have done. Also, if I did want to vary the possible range of numbers I would have to update the zero padding function to accept an argument to tell it how many zeros to pad etc. That might actually be nice, just to show how to make the functions as flexible as possible i.e. not need to edit when changing the paramters of the problem. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:22:57.223",
"Id": "46277",
"ParentId": "46273",
"Score": "2"
}
},
{
"body": "<p>I was bored, so I decided to write my own solution. Might be helpful- so I'll post it.</p>\n\n<p>It's fairly similar to your solution. I start by defining some strings:</p>\n\n<pre><code>singles = [\"\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\"]\ntens = [\"\",\"\",\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"]\nteens = [\"ten\",\"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"]\nsuffix = [\"\",\"thousand\",\"million\",\"billion\",\"trillion\",\"quadrillion\",\"zillion\"]\n</code></pre>\n\n<p>My idea here is that if I use a <code>\"\"</code> entry, I'll remove it before I construct the sentence.</p>\n\n<pre><code>def name_number(number):\n # The simplest case\n if number == 0:\n return \"zero\"\n\n # container for the evaluated digits\n name_list = []\n\n # add negative?\n if number < 0:\n name_list.append(\"negative\")\n number = -number\n\n # Pad such that it can be broken into threes\n number = str(number)\n while not len(number) % 3 == 0:\n number = '0' + number\n\n # break number into chunks\n sections = [ number[ii:ii+3] for ii in range(0, len(number), 3)]\n\n # name the chunks, and add a suffix\n for ii in range(len(sections)):\n # if the section is zero, it can be skipped\n if not int(sections[ii]) == 0:\n # if it is the last chunk, you have to add \"and\"\n name_list.extend(name_chunk(sections[ii], ii+1 == len(sections) ))\n # limited by the ammount of suffix's defined\n name_list.append(suffix[len(sections)-(ii+1)])\n\n # remove undefined numbers\n while \"\" in name_list:\n name_list.remove(\"\")\n\n # return that stuff\n return \" \".join(name_list)\n</code></pre>\n\n<p>Because I remove the empty entries, I can be lazy while evaluating chunks</p>\n\n<pre><code>def name_chunk(chunk, add_and = False):\n # container for the evaluated digits\n name_list = []\n # have to check for 0 on this digit, seeing as \"\" hundred will make no sense\n if not int(chunk[0]) == 0:\n name_list.append(singles[int(chunk[0])])\n name_list.append(\"hundred\")\n # check if in teens before moving on\n if int(chunk[1]) == 1:\n if add_and:\n name_list.append(\"and\")\n name_list.append(teens[int(chunk[2])])\n else:\n # have to check for 0 here due to same reason as before\n if add_and and not int(chunk[1:]) == 0:\n name_list.append(\"and\")\n name_list.append(tens[int(chunk[1])])\n name_list.append(singles[int(chunk[2])])\n return name_list\n</code></pre>\n\n<p>giving me the result:</p>\n\n<pre><code>>>> name_number(341234123412341200)\n'three hundred fourty one quatrillion two hundred thirty four trillion one hundred twenty three billion four hundred twelve million three hundred fourty one thousand two hundred'\n>>> name_number(341234123412341201)\n'three hundred fourty one quatrillion two hundred thirty four trillion one hundred twenty three billion four hundred twelve million three hundred fourty one thousand two hundred and one'\n>>> \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:18:15.900",
"Id": "80947",
"Score": "0",
"body": "Zero!!!!! I forgot about zero! Damnit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:45:46.713",
"Id": "80954",
"Score": "0",
"body": "I particulalry like the idea of iterating until the len(string)%3 == 3. This means, fewer unnecessary tuples of '0's when the number is short, and means you don't have to specify how many '0's should be added, therefore making the function more flexible as to input... Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:44:21.673",
"Id": "81083",
"Score": "0",
"body": "@woody padding works well for immutable objects like strings. just remember if you're padding something like a list, to remove the padding after"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:44:38.177",
"Id": "46325",
"ParentId": "46273",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:42:27.717",
"Id": "46273",
"Score": "5",
"Tags": [
"python",
"strings",
"python-2.x",
"numbers-to-words"
],
"Title": "Numbers to Text Program - Python Training"
} | 46273 |
<p>I want to create a small web widget, you can see it at this <a href="http://jsfiddle.net/easilyBaffled/ta8YR/1/" rel="nofollow noreferrer">jsfiddle</a>. Right now it is organized by placing lists within lists and content within those lists. All of this is supposed to sit, as a bar, fixed to the bottom of your window, over the current website. I want to know, is my list set up too cumbersome, and at the same time there a better(more efficient) way to use CSS to create this same layout?</p>
<p>Here's what it looks like:
<img src="https://i.stack.imgur.com/OCJI2.png" alt="enter image description here"></p>
<p><strong>HTML:</strong></p>
<pre><code><ul class="app_container_T t_ul">
<li>
<ul class="menu_T t_ul">
<li>
<button class="large_menu_button_T">+</button>
<button class="large_menu_button_T">T</button>
<button class="small_menu_button_T options">o</button>
</li>
</ul>
</li>
<li>
<ul class="container_element_T t_ul resizableui-widget-content" id="1">
<li class="content_header_T">
<button class="t_intect_button close_button_T">-</button>
<form name="search_form" class="search_form_T">
<input type="text" name="search_input" class="search_bar_T"></input>
<button class="search_button_T" name="search_button" onclick="add_timeline_element"></button>
</form>
</li>
<li class="content_container_T">
<button value="Timeline" id="1" class="content_selection_button_T">Timeline</button>
<button value="Relevent" id="1" class="content_selection_button_T">Relevent</button>
<button value="Mentions" id="1" class="content_selection_button_T">Mentions</button>
</li>
</ul>
</li>
<li class="container_T">
<button class="t_intect_button close_button_T">-</button>
<textarea class="text_area_T" warp="hard" placeholder="place holder"></textarea>
<button value="Add Photo" class="composition_button_T photo_button_T"></button>
<button value="Add Location" class="composition_button_T location_button_T"></button>
<textarea class="word_count_T"></textarea>
<button value="Undo: Off" class="composition_button_T Undo_button_T"></button>
<button value="Submit" class="composition_button_T send_button_T"></button>
</li>
</ul>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code> /*------------------------------------------------------------------------------------*/
/*----Bar---*/
/*------------------------------------------------------------------------------------*/
.app_container_T {
position:fixed;
bottom: 0px;
left:0px;
z-index: 998;
padding: 0px;
height: 150px;
box-sizing: border-box;
}
.app_container_T > li {
/*create a class for them to share itll be faster, like t_ul*/
display: inline-block;
height: 100%;
}
.t_ul {
list-style: none;
}
.app_container_T * {
box-sizing: border-box;
border-radius:5px;
vertical-align: text-bottom;
}
/*------------------------------------------------------------------------------------*/
/*----Menu---*/
/*------------------------------------------------------------------------------------*/
.menu_buffer {
width: 60px;
}
.menu_T {
background-color:lightblue;
padding: 0px;
width:60px;
height: 100%;
}
.large_menu_button_T {
background: #0016f0;
color: #ffffff;
height: 50px;
width: 50px;
margin: 3px;
font-size: 20px;
border-radius:10px;
}
.small_menu_button_T {
background: #002aa9;
color: #ffffff;
height: 20px;
width: 20px;
margin: 1px;
font-size: 12px;
}
.options {
margin-left: 26px;
}
/*-------------------------------------------------------------------------------------*/
/*Selection Element*/
/*------------------------------------------------------------------------------------*/
.container_element_T {
background-color:red;
padding: 5px;
height: 100%;
width: 325px;
}
.content_header_T {
position: relative;
width: 100%;
height: 35px;
}
.content_header_T > * {
position: relative;
}
.close_button_T {
width: 20px;
height: 20px;
display: inline-block;
padding: 0;
margin: 0;
vertical-align: top
}
.search_form_T {
width: 90%;
height: 35px;
display: inline-block;
}
.content_title_T {
width: 90%;
height: 100%;
display: inline-block;
}
.content_container_T {
overflow: scroll;
width: 100%;
height: 100%;
}
.content_selection_button_T {
font-size: 100%;
width:100%;
height: 25%;
}
.content_list_T {
width: 100%;
height: 100%;
padding: 2px;
background: #0c5bd4;
overflow: auto;
}
.t_content {
width: 100%;
height: 50%;
background: #40aeee;
border: 1px solid #fffeda;
}
.t_content_container_image {
display: block;
margin: 0;
float: left;
height: 100%;
width: auto;
}
.t_content_container_text {
margin: 0;
overflow: hidden;
padding-left: 2px;
height: 100%;
width: initial;
}
/*-------------------------------------------------------------------------------------*/
/*Timeline Element*/
/*------------------------------------------------------------------------------------*/
.search_bar_T {
background-color:white;
box-shadow: rgb(204, 204, 204) 0px 0px 0px 1px inset;
border: 1px solid rgb(178, 210, 203);
border-radius: 8px;
font-size: 12px;
height: 100%;
width: 87%;
}
.search_button_T {
cursor: pointer;
border: 1px;
background-color: #d4d4d4;
font-family:'EntypoRegular';
color: #5f615c;
font-size: 30px;
height: 30px;
width: 30px;
}
/*-------------------------------------------------------------------------------------*/
/*Alt Element*/
/*------------------------------------------------------------------------------------*/
.container_T {
background-color:red;
padding: 5px;
height: 150px;
width: 325px;
}
.text_area_T {
height: 80%;
width: 90%;
}
.composition_button_T {
margin: 0px 2px;
height: 20%;
width: 10%;
}
.word_count_T {
height: 20%;
width: 10%;
background: transparent;
color: #b1b7b6;
margin: 0px 15%;
}
</code></pre>
| [] | [
{
"body": "<p><a href=\"http://html5doctor.com/\" rel=\"nofollow\">Here's how HTML5Doctor describes <code><ul></code> and <code><li></code></a>:</p>\n\n<blockquote>\n <h2>ul</h2>\n \n <p>The ul element represents a list of items, where the order of the\n items is not important — that is, where changing the order would not\n materially change the meaning of the list.</p>\n \n <h2>li</h2>\n \n <p>The li element represents a list item. If its parent element is an ol,\n ul, or menu element, then the element is an item of the parent\n element's list, as defined for those elements. Otherwise, the list\n item has no defined list-related relationship to any other li element.</p>\n</blockquote>\n\n<p>Here's how I describe it:</p>\n\n<blockquote>\n <p><strong>If it ain't a list, don't use a list</strong></p>\n</blockquote>\n\n<p>If the layout has no semantic meaning, and the elements are just used for layouting, you should consider <code><div></code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T00:25:02.690",
"Id": "80933",
"Score": "0",
"body": "div is a fairly general tag, and would require a bit of css magic to make it work with jquery's resize. Is there any more specific element instead of div?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:20:00.527",
"Id": "81025",
"Score": "0",
"body": "@EasilyBaffled Elements fall under 2 categories. There are *block elements* like `<div>` and `<p>`, and *inline elements* like `<a>` and `<span>`. Aside from functional differences, the names merely provide semantic meaning and nothing more. Sectioning and grouping elements generally fall under block elements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:30:18.267",
"Id": "46284",
"ParentId": "46275",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:04:07.447",
"Id": "46275",
"Score": "4",
"Tags": [
"html",
"css",
"layout"
],
"Title": "Am I over using <ul> for layout?"
} | 46275 |
<p>I have to deal with a really ugly looking response I get back from a particular device. The string represents a table. Each section of the string represents the form:</p>
<pre><code>["id", "date_time", "path", "type","duration","count", "rate"]
</code></pre>
<p>Which as an example looks like:</p>
<pre><code>"1,2014-4-3 10:1:10,somerandompath,some/screwy!stringwithstufflike[0,0,0,0]inIt,0,0;"
</code></pre>
<p>all table entries as you can see are terminated by <code>;</code> and have their elements separated by <code>,</code></p>
<p>But some entries like in <code>some/screwy!stringwithstufflike[0,0,0,0]inIt</code> have commas within their data,.. and times/dates <code>10:1:10</code> aren't padded with <code>0</code>'s to be consistent</p>
<p>This is what I have so far, but it doesn't feel very optimized...</p>
<pre><code>def GetEventTable(self):
# After I split by ',' commas can be inside of [..],
# so I combine entries until their number of starting/end braces match
def split_entry(entry):
splitentry = entry.split(',')
for ii in range(len(splitentry))[::-1]:
start_bracket = splitentry[ii].count('[')
end_bracket = splitentry[ii].count(']')
if not start_bracket == end_bracket:
splitentry[ii-1:ii+1] = [splitentry[ii-1] + ',' + splitentry[ii]]
return splitentry
event_lable = ["id", "date_time", "path", "type","duration","count", "rate"]
## This section just talks to the remote device and gets the unformatted string ###
print "Sending: GET EVENT TABLE"
stat, raw_data = SendRecieve(self, "GET EVENT TABLE")
if IsError(stat):
raise Exception("Error type '{}': {}".format(stat, raw_data))
print raw_data
##################################################################################
events = raw_data.split(';')[:-1]
event_table = [{key:value for key,value in zip(event_lable,split_entry(entry) )} for entry in events ]
return event_table
</code></pre>
<p>How can I improve the efficiency and also the readability?</p>
<p>It returns a list of dictionaries with keys <code>["id", "date_time", "path", "type","duration","count", "rate"]</code></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:07:53.360",
"Id": "80791",
"Score": "0",
"body": "Can you add information about how this function is supposed to be used? At the moment, this is just the definition of a function taking no parameter and calling a `SendRecieve` function that probably does not exist on a standard installation (the typo is a pretty good hint)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:12:01.333",
"Id": "80793",
"Score": "0",
"body": "@Josay I already explained that I'm getting the data in a string where \"entries as you can see are terminated by ; and have their elements separated by ,\".. I did however forget to add self :p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:09:36.447",
"Id": "80929",
"Score": "0",
"body": "Well then you'll have to excuse me for being a pain but it's quite hard to review anything out of its context (a method out of its class). I'll try to give it a try if no one else has later on."
}
] | [
{
"body": "<p><strong>Disclaimer</strong> </p>\n\n<p>Because a lot of context is missing, here's the code I will review :</p>\n\n<pre><code>def split_entry(entry):\n splitentry = entry.split(',')\n for ii in range(len(splitentry))[::-1]:\n start_bracket = splitentry[ii].count('[')\n end_bracket = splitentry[ii].count(']')\n if not start_bracket == end_bracket:\n splitentry[ii-1:ii+1] = [splitentry[ii-1] + ',' + splitentry[ii]]\n return splitentry\n\nevent_lable = [\"id\", \"date_time\", \"path\", \"type\",\"duration\",\"count\", \"rate\"]\nraw_data = \"1,2014-4-3 10:1:10,somerandompath,some/screwy!stringwithstufflike[0,0,0,0]inIt,0,0;\"\nevents = raw_data.split(';')[:-1]\nevent_table = [{key:value for key,value in zip(event_lable,split_entry(entry) )} for entry in events ]\nprint event_table\n</code></pre>\n\n<hr>\n\n<p><code>ii</code> is a pretty bad name. <code>i</code> is twice shorter and so many times easier to understand.</p>\n\n<hr>\n\n<p>Instead of creating a new list by reversing the return of range, you could just use all the potential of range (or xrange): </p>\n\n<hr>\n\n<p>Instead of using <code>not A == B</code>, you could write a more natural <code>A != B</code></p>\n\n<hr>\n\n<p>Looping over an array using <code>range(len(a))</code> is an anti-pattern in python. To loop on an array while keeping track of the index, the usual solution is to use <code>enumerate()</code>. In your case, because you are updating the array anyway, it is quite tricky to loop on it.</p>\n\n<hr>\n\n<p>Final point : I had trouble understanding your list slicing stuff but as I was messing a bit with it, I obtained a result different from yours ('rate' appears in the final result so it might actually be a good thing) :</p>\n\n<pre><code>def split_entry(entry):\n splitentry = entry.split(',')\n for i in xrange(len(splitentry)-1,0,-1):\n chunk = splitentry[i]\n if chunk.count('[') != chunk.count(']'):\n splitentry[i-1] += ',' + chunk\n splitentry[i] = '0'\n return splitentry\n\nevent_lable = [\"id\", \"date_time\", \"path\", \"type\",\"duration\",\"count\", \"rate\"]\nraw_data = \"1,2014-4-3 10:1:10,somerandompath,some/screwy!stringwithstufflike[0,0,0,0]inIt,0,0;\"\nevents = raw_data.split(';')[:-1]\nevent_table = [{key:value for key,value in zip(event_lable,split_entry(entry) )} for entry in events]\nprint event_table\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:15:33.423",
"Id": "81176",
"Score": "0",
"body": "hmmm.. now that I think of it, I wouldn't need to clear the old value in `splitentry[i] = '0'` seeing as the zip function will only return up to max `len(event_lable)` anyway!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:59:37.793",
"Id": "46472",
"ParentId": "46279",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:43:49.147",
"Id": "46279",
"Score": "0",
"Tags": [
"python",
"strings",
"python-2.x",
"formatting"
],
"Title": "Dealing with a dirty table"
} | 46279 |
<p>I want to include about 10 jQuery plugins in a project but do so in a better way than just pasting them into a JS file.</p>
<p>I want to capture various device data and other data passed from the server-side (in a HTML meta tag) and I want some of this to decide which jQuery scripts to run - or none in the case of some devices.</p>
<p>I also want to be able to extend jQuery plugins, globally control events, globally control setTimeout() and basically write the code in a much better way to maintain.</p>
<p>I have been learning from various tutorials and would like to gauge my understanding.</p>
<p>I have written the code below form various tutorials and advice and it should be a better way to extend and implement jQuery and feedback would be great. I haven't actually ran the code, I'm just trying to understand how the best way to design this would be.</p>
<p>Am I on the right track for how to structure this?</p>
<pre><code>/* all the original jQuery plugins */
(function ($) {
$.slider = function () {
//etc
};
}(jQuery));
/* jQuery wrappers - one for each jQuery script */
function JquerySlider($) {
var extensionMethods = {
showId: (function () {
return this.element[0].id;
}())
};
$.extend(true, $.slider.prototype, extensionMethods);
}
/* execute all the jQuery scripts */
function InitJquery($) {
this.slider = new JquerySlider($);
}
/* get various device data */
function Device() {
// get meta data from HTML
// holds a value 1-3 for the quality of the device (detected server-side)
this.quality = Number(document.getElementById('device-quality').content);
// get viewport width
this.viewportWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}
/* standard JS */
function InitStandard(jQuery) {
//get device information
this.device = new Device();
// initialise jQuery, if device is capable
if (this.device.quality === 1) {
this.jqueryPlugins = new InitJquery(jQuery);
}
}
/* cross-browser add event function */
if (window.addEventListener) {
var addEvent = function (ob, type, fn) {
if (typeof ob != 'undefined') {
ob.addEventListener(type, fn, false);
}
};
} else if (document.attachEvent) {
var addEvent = function (ob, type, fn) {
if (typeof ob != 'undefined') {
var eProp = type + fn;
ob['e' + eProp] = fn;
ob[eProp] = function () {
ob['e' + eProp](window.event);
};
ob.attachEvent('on' + type, ob[eProp]);
}
};
}
/* initialise standard JS on load and pass in the jQuery object */
(function init(jQuery) {
var js = new InitStandard(jQuery);
}(jQuery));
addEvent(window, 'load', init);
</code></pre>
| [] | [
{
"body": "<p>On the whole, I think you need to work on <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">keeping it simple</a>.</p>\n\n<ul>\n<li><p>I would not write my own cross-browser event handling function if I use jQuery, I would leverage <a href=\"http://api.jquery.com/category/events/\" rel=\"nofollow\">what jQuery provides</a>.</p></li>\n<li><p>This:</p>\n\n<pre><code>/* standard JS */\nfunction InitStandard(jQuery) {\n //get device information\n this.device = new Device();\n\n // initialise jQuery, if device is capable\n if (this.device.quality === 1) {\n this.jqueryPlugins = new InitJquery(jQuery);\n }\n}\n\n/* initialise standard JS on load and pass in the jQuery object */\n(function init(jQuery) {\n var js = new InitStandard(jQuery);\n}(jQuery));\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>(function InitStandard(jQuery) {\n //get device information\n this.device = new Device();\n\n // initialise jQuery, if device is capable\n if (this.device.quality === 1) {\n this.jqueryPlugins = new InitJquery(jQuery);\n }\n}(jQuery));\n</code></pre>\n\n<p>Because you are not using <code>var js</code> anywhere.<br>\nAlso, <code>1</code> should be assigned to a properly named constant like <code>ADVANCED_DEVICE</code></p></li>\n<li><code>addEvent(window, 'load', init);</code> could be <code>$( init )</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:36:49.413",
"Id": "46285",
"ParentId": "46281",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:03:57.433",
"Id": "46281",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"object-oriented",
"cross-browser"
],
"Title": "Re-writing rough JS code with loads of jQuery plugins"
} | 46281 |
<p><code>Schedule</code> is a simple class that could be used in program to manage when a task should be repeated (a todo list, for example). Its constructor requires a start date and an optional end date, then type of repetition (daily, weekly or monthly) has to be set. If weekly is chosen, then the days of weeks when repetition occurs has to be set too. This is a simple exercise I made to practice test driven development. All test passes, so I guess it works as expected. Any suggestion about how to improve tests will be very appreciated (but any other are welcome too).</p>
<p>This is the class:</p>
<pre><code>public class Schedule {
public enum REPETITION {
NONE, DAILY, WEEKLY, MONTHLY
}
public enum DAY_OF_WEEK {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Date dateStart;
Date dateStop;
REPETITION repetitionType = REPETITION.NONE;
EnumSet<DAY_OF_WEEK> daysOfWeek = EnumSet.noneOf(DAY_OF_WEEK.class);
public Schedule(Date dateStart, Date dateStop){
if (dateStop != null){
if (dateStart.after(dateStop))
throw new IllegalArgumentException("Date start after date stop.");
this.dateStop = new Date(dateStop.getTime());
}
this.dateStart = new Date(dateStart.getTime());
}
/**
*
* @param dateToCheck
* @return true if repetition is expected int the day to check
*/
public boolean checkDateValid(Date dateToCheck){
if (dateToCheck == null)
return false;
try {
checkDateBetweenLimits(dateToCheck);
if (repetitionType != null){
switch (repetitionType){
case WEEKLY: checkWeekRepetition(dateToCheck); break;
case MONTHLY: checkMonthRepetition(dateToCheck); break;
default:
}
}
}
catch (IllegalArgumentException ex){
return false;
}
return true;
}
public void checkDateBetweenLimits(Date dateToCheck) throws IllegalArgumentException{
if (dateToCheck.before(dateStart))
throw new IllegalArgumentException("Date before limit");
if (dateStop != null && dateToCheck.after(dateStop))
throw new IllegalArgumentException("Date after limit");
}
public void checkMonthRepetition(Date dateToCheck) throws IllegalArgumentException{
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateToCheck);
int dayOfWeekToValidate = calendar.get(Calendar.DAY_OF_MONTH);
calendar = Calendar.getInstance();
calendar.setTime(dateStart);
int dayOfWeek = calendar.get(Calendar.DAY_OF_MONTH);
if (dayOfWeek != dayOfWeekToValidate){
throw new IllegalArgumentException("Not same day of month.");
}
}
private void checkWeekRepetition(Date dateToCheck) throws IllegalArgumentException{
DAY_OF_WEEK day = evaluateDayOfWeek(dateToCheck);
if (!daysOfWeek.contains(day))
throw new IllegalArgumentException("No repetition in this day of week.");
}
private DAY_OF_WEEK evaluateDayOfWeek(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
switch (dayOfWeek){
case Calendar.MONDAY: return DAY_OF_WEEK.MONDAY;
case Calendar.TUESDAY: return DAY_OF_WEEK.TUESDAY;
case Calendar.WEDNESDAY: return DAY_OF_WEEK.WEDNESDAY;
case Calendar.THURSDAY: return DAY_OF_WEEK.THURSDAY;
case Calendar.FRIDAY: return DAY_OF_WEEK.FRIDAY;
case Calendar.SATURDAY: return DAY_OF_WEEK.SATURDAY;
case Calendar.SUNDAY: return DAY_OF_WEEK.SUNDAY;
default: throw new IllegalArgumentException("Unexpected value.");
}
}
public Date getDateStop() {
return dateStop;
}
public Date getDateStart() {
return dateStart;
}
public void setRepetitionType(REPETITION repetitionType) {
this.repetitionType = repetitionType;
}
public void addDayOfWeek(DAY_OF_WEEK day) {
daysOfWeek.add(day);
}
public void removeDayOfWeek(DAY_OF_WEEK day){
daysOfWeek.remove(day);
}
}
</code></pre>
<p>This is the test class (Junit4):</p>
<pre><code>public class ScheduleTest {
Date mon = new Date(2014, 0, 5);
Date tue = new Date(2014, 0, 6);
Date wed = new Date(2014, 0, 7);
Date thu = new Date(2014, 0, 8);
Date fri = new Date(2014, 0, 9);
Date sat = new Date(2014, 0, 10);
Date sun = new Date(2014, 0, 11);
Date firstOf2014 = new Date(2014, 0, 1);
Date lastOf2014 = new Date(2014, 11, 31);
Date today = GregorianCalendar.getInstance().getTime();
Date tomorrow = new Date(today.getTime() + (1000L * 3600 * 24));
Date nextMonth = new Date(today.getTime() + (1000L * 3600 * 24 * 31));
Date prevMonth = new Date(today.getTime() - (1000L * 3600 * 24 * 31));
Schedule scheduleTodayTomorrow = new Schedule(today, tomorrow);
@Test
public void testDateStartBeforeDateStop(){
try{
scheduleTodayTomorrow = new Schedule(tomorrow, today);
Assert.fail("Should throw IllegalArgumentException when dateStart after dateStop.");
}
catch (IllegalArgumentException ex){
//OK
}
}
@Test
public void testDateStopCanBeNull(){
Schedule schedule = new Schedule(today, null);
}
@Test
public void testDefensiveCopy(){
long todayTime = today.getTime();
today.setTime(1000);
Assert.assertEquals(todayTime, scheduleTodayTomorrow.getDateStart().getTime());
long tomorrowTime = tomorrow.getTime();
tomorrow.setTime(1000);
Assert.assertEquals(tomorrowTime, scheduleTodayTomorrow.getDateStop().getTime());
}
@Test
public void testDateValidity(){
Assert.assertTrue(scheduleTodayTomorrow.checkDateValid(today));
Assert.assertTrue(scheduleTodayTomorrow.checkDateValid(tomorrow));
Assert.assertFalse(scheduleTodayTomorrow.checkDateValid(prevMonth));
Assert.assertFalse(scheduleTodayTomorrow.checkDateValid(nextMonth));
Date inDate = new Date(today.getTime() + 1000L);
Assert.assertTrue(scheduleTodayTomorrow.checkDateValid(inDate));
}
@Test
public void testDailyRepetition(){
Schedule schedule = new Schedule(today, nextMonth);
schedule.setRepetitionType(Schedule.REPETITION.DAILY);
Assert.assertTrue(schedule.checkDateValid(today));
Assert.assertTrue(schedule.checkDateValid(tomorrow));
Assert.assertTrue(schedule.checkDateValid(nextMonth));
}
@Test
public void testMonthRepetition(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.MONTHLY);
// As the scheduleTodayTomorrow starts on 1/1, then every first day of months should be valid
for (int i=1; i<=11; i++){
Date date = new Date(2014, i, 1);
Assert.assertTrue("Valid date with month " + i + " treated as invalid.", schedule.checkDateValid(date));
}
// Every other days of every month are invalid
for (int i=1; i<=11; i++){
Date date = new Date(2014, i, 2);
Assert.assertFalse("Invalid date with month " + i + " treated as valid.", schedule.checkDateValid(date));
}
}
@Test
public void testWeekRepetitionNoValidDateAsDefault(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddMonday(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.MONDAY);
Assert.assertTrue(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddTuesday(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.TUESDAY);
Assert.assertTrue(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddWednesday(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.WEDNESDAY);
Assert.assertTrue(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddThursday(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.THURSDAY);
Assert.assertTrue(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddFriday(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.FRIDAY);
Assert.assertTrue(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddSaturday(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.SATURDAY);
Assert.assertTrue(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddSunday(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.SUNDAY);
Assert.assertTrue(schedule.checkDateValid(sun));
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(sat));
}
@Test
public void testWeekRepetitionAddMultipleDays(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.MONDAY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.WEDNESDAY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.FRIDAY);
Assert.assertTrue(schedule.checkDateValid(mon));
Assert.assertTrue(schedule.checkDateValid(wed));
Assert.assertTrue(schedule.checkDateValid(fri));
Assert.assertFalse(schedule.checkDateValid(tue));
Assert.assertFalse(schedule.checkDateValid(thu));
Assert.assertFalse(schedule.checkDateValid(sat));
Assert.assertFalse(schedule.checkDateValid(sun));
}
@Test
public void testWeekRepetitionAddAndRemoveDays(){
Schedule schedule = new Schedule(firstOf2014, lastOf2014);
schedule.setRepetitionType(Schedule.REPETITION.WEEKLY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.MONDAY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.WEDNESDAY);
schedule.addDayOfWeek(Schedule.DAY_OF_WEEK.FRIDAY);
Assert.assertTrue(schedule.checkDateValid(mon));
Assert.assertTrue(schedule.checkDateValid(wed));
Assert.assertTrue(schedule.checkDateValid(fri));
schedule.removeDayOfWeek(Schedule.DAY_OF_WEEK.MONDAY);
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertTrue(schedule.checkDateValid(wed));
Assert.assertTrue(schedule.checkDateValid(fri));
schedule.removeDayOfWeek(Schedule.DAY_OF_WEEK.WEDNESDAY);
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertTrue(schedule.checkDateValid(fri));
schedule.removeDayOfWeek(Schedule.DAY_OF_WEEK.FRIDAY);
Assert.assertFalse(schedule.checkDateValid(mon));
Assert.assertFalse(schedule.checkDateValid(wed));
Assert.assertFalse(schedule.checkDateValid(fri));
}
}
</code></pre>
| [] | [
{
"body": "<p>I would strongly reccomend that you use the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\"><code>java.time</code></a> package instead of the <code>java.util</code> classes, if that is at all possible.</p>\n\n<hr>\n\n<p>One thing you could improve involves the improperly-named <code>DAY_OF_WEEK</code> and <code>REPETITION</code> enums. An <code>enum</code> is a type of class, and should be named using the convention for naming classes, not that for <code>static final</code> constants. Call them <code>DayOfWeek</code> and <code>Repetition</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:22:46.910",
"Id": "80805",
"Score": "1",
"body": "It should be emphasized that `java.time` package is for Java 8. But yes, it's a good suggestion to use it. Java 8 is awesome :) +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:29:41.570",
"Id": "80807",
"Score": "0",
"body": "I decided to use java 7 and avoid Joda library. Thank for names, still have to remember all the java naming convention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:02:06.273",
"Id": "80942",
"Score": "0",
"body": "@holap JodaTime or `java.time` will save your sanity."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:37:38.327",
"Id": "46286",
"ParentId": "46282",
"Score": "10"
}
},
{
"body": "<p><strong>What's in a name?</strong><br>\nClass names should be nouns, and although <code>Schedule</code> could be a noun, it looks like you chose the verb name. I think maybe 'Task' will be a better name for it?<br>\nYour main method is called <code>checkDateValid()</code>, what does it mean? All dates passed to the method are <em>valid</em>... valid for what? Give the method a name which gives the context of the <em>instance</em> which tests it.<br>\nThe documentation above the method says</p>\n\n<blockquote>\n<pre><code> * @return true if repetition is expected int the day to check\n</code></pre>\n</blockquote>\n\n<p>And what happens if repetition is <em>not</em> expected? This is actually not defined in your description as well... By looking in your code it means that if there is no repetition, <em>anytime</em> between start date and end date (or forever) is considered valid... Maybe a better name for the method be <code>isRelevantFor()</code>?</p>\n\n<p><strong>When enums don't matter</strong><br>\nYou have declared two enums - <code>REPETITION</code> and <code>DAY_OF_WEEK</code>. One observation - naming conventions for enums is CamelCase, so the names should be <code>Repetition</code> and <code>DayOfWeek</code>.<br>\nBut, look at what you do with <code>DAY_OF_WEEK</code> - you translate it (not in a very DRY way) to <code>Calendar.DAY_OF_WEEK</code>, you should consider to drop it all together and use the Calendar constants from the start...</p>\n\n<p><strong>What exceptions are for?</strong><br>\n<code>checkMonthRepetition</code> and <code>checkWeekRepetition</code> throw <code>IllegalArgumentException</code>. Why? Again, all dates are <em>legal</em>.<br>\nExceptions should be used in case where something prevented the method from completing its promise to its caller. For example - <code>parseInt()</code> would throw an exception when the input string is not made of integers - it simply can't parse it to a valid integer. The same way that a <code>readFile()</code> will throw an exception when the file was not found where expected.<br>\nHere they are used for completely expected values - the input date is either a match to the indicated repetition dates, or it isn't.<br>\nExceptions break the flow of the method, and need to be handled. They are also very inefficient at runtime.<br>\nThese methods should simply return <code>boolean</code>, just like their caller.</p>\n\n<p><strong>Simplify you API according to use-cases</strong><br>\nTo set a weekly repetition, you expect the user to call two methods - <code>setRepetitionType()</code> and then remember to call <code>addDayOfWeek</code>. This is far from optimal to your prospective user, and very hard to enforce statically. The reason you chose this way is because that is the way your class is arranged internally.<br>\nIf you think about the API from the <em>outside</em>, maybe a better set of APIs would be <code>setMonthlyRepetition()</code>, and <code>setWeeklyRepetition(DAY_OF_WEEK... days)</code>. This way, the user will set the relevant days <em>in the same call</em> where he sets the repetition type. It would also make it easier to expand your API in the future to <code>setMonthlyRepetition(int... daysOfTheMonth)</code>...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:36:44.733",
"Id": "80810",
"Score": "1",
"body": "Thank you for suggestion about name. Actually I'm not very sutisfy with the names I choosed (english is not my mother language, have to improve this). Don't like constant at all. They where needed when enum didn't exist. Now I prefer use enum for the check that compiler could do. I choosed exception juat to stop the flow of method. Otherwise I should check the return value of every function and return if it's false. Don't like it, this way I can avoid it. Amazing suggestion about the api."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:45:07.657",
"Id": "80812",
"Score": "0",
"body": "About checkMonthRepetition and checkWeekRepetition, now I can see your point (thanks to Simon). Yes that's should be better. I made it because I thought there could be other conditions to test after that. I actually should cange it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:57:17.930",
"Id": "80815",
"Score": "0",
"body": "Changed the name of checkDateValid to checkRepetitionRequiredAtDate and removed the exception, but would improve the style of that function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:37:00.640",
"Id": "81029",
"Score": "0",
"body": "Nice post overall, but I don't find your snippet on exceptions very helpful: _\"Exceptions should be used in case of, well, exceptions. Here they are used for completely expected values.\"_ Using a term as its own definition doesn't add anything. And besides, how could you raise an exception for invalid values, which are (obviously) expected since they are known up front and you are testing for them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:03:00.460",
"Id": "81057",
"Score": "0",
"body": "@AndréCaron - thanks for your input - I've reworded the section according to it"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:49:34.760",
"Id": "46289",
"ParentId": "46282",
"Score": "11"
}
},
{
"body": "<ul>\n<li><p><code>private final</code> Your fields <code>dateStart</code>, <code>dateStop</code> and the others should be marked as <strong>private final</strong>. Other classes don't need direct access to them (and normally shouldn't have direct access even if they needed it), and as they never change once the class has been initialized it's good practice to mark them as <strong>final</strong>.</p></li>\n<li><p>I'm not a big fan of the lack of line breaks in your <code>switch</code> statements. Also, by returning <code>boolean</code> as has been suggested in other answers, you can simplify it to: (Note the improved formatting)</p>\n\n<pre><code>switch (repetitionType) {\n case WEEKLY: \n return checkWeekRepetition(dateToCheck);\n case MONTHLY: \n return checkMonthRepetition(dateToCheck);\n}\n</code></pre>\n\n<p>I also removed the <code>if (repetitionType != null)</code> check as that's not needed, if it would be null the default case would apply, and as your default case was just empty there's no need in having it at all.</p></li>\n<li><p><code>catch (IllegalArgumentException ex) {</code></p>\n\n<p>You catch the IllegalArgumentException to use it as flow-control by returning <code>false</code> if it occurs. Don't do that. Don't use Exceptions for flow-control in the first place, and I also have to point out that some exceptions are not meant to be caught. That includes <code>IllegalArgumentException</code> See another answer of mine <a href=\"https://codereview.stackexchange.com/questions/45637/exception-handling-with-instanceof-rather-than-catch/45639#45639\">here</a> regarding such exceptions.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:56:19.760",
"Id": "80814",
"Score": "0",
"body": "Thank you. You made the argument of Uri more clear. Made some changes, but don't like a lot control flow of checkRepetitionRequiredAtDate (I renamed the function)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:37:34.280",
"Id": "46294",
"ParentId": "46282",
"Score": "10"
}
},
{
"body": "<p>As far as I see nobody reviewed the tests, so here are a few notes about that:</p>\n\n<ol>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>@Test\npublic void testDateStartBeforeDateStop(){\n try{\n scheduleTodayTomorrow = new Schedule(tomorrow, today);\n Assert.fail(\"Should throw IllegalArgumentException when dateStart after dateStop.\");\n }\n catch (IllegalArgumentException ex){\n //OK\n }\n}\n</code></pre>\n</blockquote>\n\n<p>could be changed to</p>\n\n<pre><code>@Test(expected = IllegalArgumentException.class)\npublic void testDateStartBeforeDateStop() {\n new Schedule(tomorrow, today);\n}\n</code></pre>\n\n<p>It's the same. If you want to test the message of the exception you need the <code>try-catch</code> but if it doesn't matter this one is simpler.</p></li>\n<li><p>This constructor is deprecated:</p>\n\n<blockquote>\n<pre><code>Date mon = new Date(2014, 0, 5);\n</code></pre>\n</blockquote>\n\n<p>I'd create a helper method with a similar signature which calls <code>Calendar.set</code> as it is suggested by the javadoc of <code>Date</code>.</p></li>\n<li><p>The <code>Date</code> fields could be <code>private</code>.</p>\n\n<p>(<a href=\"https://stackoverflow.com/q/5484845/843804\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><p>The <code>schedule</code> variable is unused here:</p>\n\n<blockquote>\n<pre><code>@Test\npublic void testDateStopCanBeNull(){\n Schedule schedule = new Schedule(today, null);\n}\n</code></pre>\n</blockquote>\n\n<p>The following is the same:</p>\n\n<pre><code>@Test\npublic void testDateStopCanBeNull() {\n new Schedule(today, null);\n}\n</code></pre></li>\n<li><p>If you check the code with a code coverage tool (I'm using Eclipse with EclEmma) you can find a few missed branches which the tests don't cover.</p></li>\n<li><p>I'd use static import for assert methods to remove some clutter. So, this</p>\n\n<blockquote>\n<pre><code>Assert.assertTrue(schedule.checkDateValid(mon));\n</code></pre>\n</blockquote>\n\n<p>could be this:</p>\n\n<pre><code>assertTrue(schedule.checkDateValid(mon));\n</code></pre></li>\n<li><p>Instead of constants like these:</p>\n\n<blockquote>\n<pre><code>Date mon = new Date(2014, 0, 5);\nDate tue = new Date(2014, 0, 6);\n</code></pre>\n</blockquote>\n\n<p>I would use creation methods (<code>createMondayDate</code>, etc.) to avoid accidental modification of the internal time of the <code>Date</code> object.</p></li>\n<li><p>The following field is used by only two test methods:</p>\n\n<blockquote>\n<pre><code>Schedule scheduleTodayTomorrow = new Schedule(today, tomorrow);\n</code></pre>\n</blockquote>\n\n<p>I would instantiate it inside those methods to increase <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow noreferrer\">defect localization</a>. If the constructor throws an exception for those parameters all test will fail which makes debugging a little bit harder.</p></li>\n<li><p>This test tests two things:</p>\n\n<blockquote>\n<pre><code>@Test\npublic void testDefensiveCopy(){\n long todayTime = today.getTime();\n today.setTime(1000);\n Assert.assertEquals(todayTime, scheduleTodayTomorrow.getDateStart().getTime());\n\n long tomorrowTime = tomorrow.getTime();\n tomorrow.setTime(1000);\n Assert.assertEquals(tomorrowTime, scheduleTodayTomorrow.getDateStop().getTime());\n}\n</code></pre>\n</blockquote>\n\n<p>It could be split up to two separate methods: <code>testStartDateDefensiveCopy</code>, <code>testStopDateDefensiveCopy</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:06:29.413",
"Id": "80943",
"Score": "0",
"body": "This seems the best answer to add \"Don't prefix your test method names with `test` when you use the `@Test` annotation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T05:12:48.167",
"Id": "80977",
"Score": "1",
"body": "Thank you. Very usefull tips. Intellij community didn't complain about branches, I will try with Eclipse."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T00:28:08.700",
"Id": "46339",
"ParentId": "46282",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:06:50.193",
"Id": "46282",
"Score": "10",
"Tags": [
"java",
"unit-testing",
"datetime",
"scheduled-tasks"
],
"Title": "Schedule class (exercise for test driven development)"
} | 46282 |
<p>I have started using BEM syntax for my HTML and CSS. I got the idea from Harry Roberts' blog post <a href="http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/" rel="nofollow">"MindBEMding – getting your head 'round BEM syntax"</a>.</p>
<p>Please note I am not looking to use this for HTML email, it is just an example. Am I going too low in my element structures?</p>
<pre class="lang-html prettyprint-override"><code><div class="wrapper">
<!-- EMAIL ONE -->
<div class="email_template">
<div class="email_template__head--one">
<div class="email_template__logo">
<img src="logo.png" alt="">
</div>
</div>
<div class="email_template__main">
<h1>Lorem ipsum dolor.</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam, sunt hic perspiciatis consectetur assumenda provident asperiores mollitia excepturi voluptatibus sequi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil, suscipit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A, ea, maiores corporis quasi quos et obcaecati! At, adipisci, eligendi, dolor sapiente magni accusamus ducimus quos aperiam exercitationem dignissimos quibusdam cum blanditiis rerum iste perferendis perspiciatis ratione ullam necessitatibus reprehenderit ex nam cumque atque voluptas? Ab reprehenderit labore repellendus sapiente atque.</p>
</div>
<div class="email_template__foot">
<div class="email_template__foot__social">
<p>Stay In Touch With Us:</p>
<div class="email_template__foot__social__logo">
<div class="email_template__foot__social__item">
<a href="#"><img src="facebook.png" alt=""></a>
</div>
<div class="email_template__foot__social__item">
<a href="#"><img src="twitter.png" alt=""></a>
</div>
</div>
</div>
<div class="email_template__foot__content">
<p>&copy;2014 ShowHouse Software</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veritatis, eligendi vero quos vitae perspiciatis ea?</p>
<div class="email_template__foot__content__links--one">
<div class="email_template__foot__content__links__item">
<a href="#">View Online</a>
</div>
<div class="email_template__foot__content__links__item"> | </div>
<div class="email_template__foot__content__links__item">
<a href="#">Unsubscribe</a>
</div>
</div>
</div>
</div>
</div>
<!-- EMAIL ONE -->
</div>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:15:45.770",
"Id": "80803",
"Score": "0",
"body": "Where is the CSS? is this Live code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:30:55.240",
"Id": "80808",
"Score": "1",
"body": "could you please clarify the meaning of \"element structure\", there's currently a discussion in [chat] about wether this question should be tagged with [tag:css]. I believe you talk about the BEM-element structure, while others believe, you are talking about the HTML-element structure..."
}
] | [
{
"body": "<p>Something minor that irritates me and may or may not irritate others, is your lack of newlines inside your <code>p</code> tags. Within these tags you can multi line and it won't be translated to your browser output.</p>\n\n<pre><code><p>\n Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n Laboriosam, sunt hic perspiciatis consectetur assumenda \n provident asperiores mollitia excepturi voluptatibus sequi.\n</p>\n</code></pre>\n\n<p>When I started writing HTML this is how I would structure most of my code, it looked pretty to me and I could easily see everything clearly.</p>\n\n<p>As long as you are styling you can make the block of text inside the <code>p</code> tag do whatever you want. you can make it wrap or not wrap or whatever. </p>\n\n<p>When you want an explicit new line then you use a <code><br /></code> tag.</p>\n\n<p>You can even insert an <code>img</code> tag inside of a <code>p</code> block as well.</p>\n\n<hr>\n\n<p>this code:</p>\n\n<pre><code> <div class=\"email_template__logo\">\n <img src=\"logo.png\" alt=\"\">\n </div>\n</code></pre>\n\n<p>could be better written using a class attribute inside of the <code>img</code> tag like this</p>\n\n<pre><code> <img src=\"logo.png\" alt=\"\" class=\"email_template__logo\" />\n</code></pre>\n\n<p>Where a <code>div</code> and a <code>img</code> tag differ you will be able to find a better way with the <code>img</code> tag because it is meant to be styled for images. </p>\n\n<hr>\n\n<p>Something else that I noticed is that you have what looks like an item list in your footer code, but you aren't using Lists (<code><ul></code> {unordered} or <code><ol></code> {ordered}) with List Items (<code><li></code> for both ordered and unordered). </p>\n\n<p>so this:</p>\n\n<pre><code> <div class=\"email_template__foot__content\">\n <p>&copy;2014 ShowHouse Software</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veritatis, eligendi vero quos vitae perspiciatis ea?</p>\n <div class=\"email_template__foot__content__links--one\">\n\n <div class=\"email_template__foot__content__links__item\">\n <a href=\"#\">View Online</a>\n </div>\n <div class=\"email_template__foot__content__links__item\"> | </div>\n <div class=\"email_template__foot__content__links__item\">\n <a href=\"#\">Unsubscribe</a>\n </div>\n\n </div>\n </div>\n</code></pre>\n\n<p>should look something more like this</p>\n\n<pre><code><div class=\"email_template__foot__content\">\n <p>&copy;2014 ShowHouse Software</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veritatis, eligendi vero quos vitae perspiciatis ea?</p>\n\n <ul class=\"email_template__foot__content__links--one\">\n <li class=\"email_template__foot__content__links__item\">\n <a href=\"#\">View Online</a>\n </li>\n <li class=\"email_template__foot__content__links__item\"> | </li>\n <li class=\"email_template__foot__content__links__item\">\n <a href=\"#\">Unsubscribe</a>\n </li>\n </ul>\n</div>\n</code></pre>\n\n<p>with this line of code being removed and replaced with styling to separate the list items</p>\n\n<pre><code><li class=\"email_template__foot__content__links__item\"> | </li>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:41:35.080",
"Id": "46296",
"ParentId": "46287",
"Score": "6"
}
},
{
"body": "<p>You could improve your BEM structure by not being so strict.</p>\n\n<p>A class name like <code>email_template__foot__content__links__item</code> is a pain to read and, in my opinion, makes BEM redundant. You don't have to go too deep. Just three levels deep should be fine, but deeper than that is too hard to read. I suggest organising your BEM like the following:</p>\n\n<pre><code><div class=\"email-template\">\n <div class=\"et-head\">\n <img class=\"et-head__logo\" src=\"\">\n </div>\n <div class=\"et-main\">\n ...\n </div>\n <div class=\"et-foot\">\n <div class=\"et-foot__social\">\n <div class=\"et-foot__social--logo\">\n ...\n </div>\n </div>\n </div>\n</div>\n</code></pre>\n\n<p>and so on. It's not against BEM to come up with a complete new class name for the footer or any other element and name the children after it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:48:08.730",
"Id": "80884",
"Score": "0",
"body": "I still don't understand the need for all those DIVs...??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:48:57.523",
"Id": "80885",
"Score": "0",
"body": "I suppose because it's a HTML email ;) HTML5 elements wont work in most email clients, so `div`s or in worst case `table`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:24:34.847",
"Id": "80901",
"Score": "0",
"body": "what about plain HTML, like `img`, `p`, `ul`, `li`, and yes `table` for the data layout. none of those are HTML5 tags, and to top things off we are talking about CSS, why would it be able to use CSS and not HTML5?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:25:27.867",
"Id": "80902",
"Score": "0",
"body": "point is, there are too many `div`'s in OP's code and in your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:34:42.163",
"Id": "80903",
"Score": "0",
"body": "Yeah I agree with the `div`'s. I was thinking of `<header>, <footer>, <section<` elements while talking about the HTML5 part. (anyway, he allready said at the beginning that he won't use the code for a html email)\nBut in generell the initial question wasn't \"do I use too many `div`'s\". He just wanted to know if his BEM structure is correct and if he can improve it. I just followed his given example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:18:31.153",
"Id": "80910",
"Score": "0",
"body": "it's HTML before it is BEM, if it is bad for HTML structure it is probably bad for BEM structure. all those `div`'s clutter the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T12:07:53.043",
"Id": "81006",
"Score": "0",
"body": "I was just using that as an example. So far in BEM the deepest I have seen was from the blog post."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:34:15.653",
"Id": "46318",
"ParentId": "46287",
"Score": "6"
}
},
{
"body": "<p>One of the most fundamentally useful things about BEM is the flattening of modules to make them independent of structure.</p>\n\n<p>It's always a problem in css to make the selectors follow the HTML structure, which is why flattening down the selectors from a css perspective is a good thing. It makes it easier to re-use on other HTML and easier to change the HTML without affecting the css.</p>\n\n<p>Take this class here: <code>email_template__foot__content__links__item</code> - although the styles will likely only apply to the list item, the entire structure that gets there is baked into the class name. This is less pernicious than the corresponding <code>.email footer .content ul li</code> that would tightly tie the selector to the HTML, but it's still unnecessary.</p>\n\n<p>My rule of thumb is that I never use the <code>__</code> more than once in class names. If you do that, you probably have another module that should be broken out to be re-usable.</p>\n\n<p>Again, looking at the footer example, you would find that this is much more modular and easier to re-use, as well as having class names that will mean something if they're moved into another context, such as if you want to use a list in the email body. You also clean the class names up massively.</p>\n\n<pre><code>.footer\n.footer__content\n\n.list\n.list__item\n</code></pre>\n\n<p>You can then do the following to style the list in some way you might want to seen as it's in the footer:</p>\n\n<pre><code>.footer .list\n// or\n.footer__list // applied to the same element as `.list` \n</code></pre>\n\n<p>Note above that the BEM class for the footer list doesn't use an intermediary <code>__content</code> clip. You shouldn't have the class <code>.footer__content__list</code></p>\n\n<p>A final small thing: <code>.email_footer</code> should probably be <code>.email-footer</code> - in BEM the underscore is only used for de-marking block from element, not as a word spacer - use the hyphen for this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-10T14:16:28.833",
"Id": "125315",
"ParentId": "46287",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46318",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:37:46.207",
"Id": "46287",
"Score": "7",
"Tags": [
"html",
"css",
"email",
"bem"
],
"Title": "BEM email structure"
} | 46287 |
<p>I'm hoping to get some feedback on how to improve and optimise a program I wrote which takes three values as input (via the terminal) and uses them in the <a href="http://www.purplemath.com/modules/quadform.htm">quadratic formula</a>.</p>
<p>I'm aware this is mostly micro-optimisation, but any advice whatsoever would be much appreciated.</p>
<pre><code>public class Quadratic_Equations {
static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Please enter a, b and c or enter -1 at any time to exit");
double a = tryParse(sc.nextLine());
a = checkIfValidNumber(a);
if (a == -1)
break;
double b = tryParse(sc.nextLine());
b = checkIfValidNumber(b);
if (b == -1)
break;
double c = tryParse(sc.nextLine());
c = checkIfValidNumber(c);
if (c == -1)
break;
System.out.println(useQuadraticFormula(a, b, c));
System.out.println();
}
sc.close();
}
private static double checkIfValidNumber(double number) {
while (number == -1.0) {
System.out.println("You didn't enter a valid number for a. Please try again.");
number = tryParse(sc.nextLine());
}
return number;
}
public static Double tryParse(String text) {
try {
return new Double(text);
} catch (NumberFormatException e) {
return -1.0;
}
}
public static String useQuadraticFormula(double a, double b, double c) {
double result1;
double result2;
if (Math.pow(b, 2) - (4 * a * c) <= 0)
return "These numbers do not compute - they produce an illegal result.";
result1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
result2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return String.valueOf(result1) + ", " + String.valueOf(result2);
}
}
</code></pre>
<p>Among the things I really dislike are:</p>
<ol>
<li>The static <code>scanner</code> object.</li>
<li>The three different checks for -1 being entered.</li>
<li>The quadratic formula method, which seems like it could be shortened.</li>
</ol>
<p>I'm still working on this myself, but as I said any advice (including on naming conventions, code style etc.) would be appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T06:51:18.427",
"Id": "81123",
"Score": "0",
"body": "There is also a [follow-up question](http://codereview.stackexchange.com/q/46322/9357)."
}
] | [
{
"body": "<p>A few things jump me here:</p>\n\n<h3>1. Class Names</h3>\n\n<p>Your class name is queer. The Java standard is to use <code>PascalCasing</code> for class names. You use <code>Pascal_Snake_Case</code>. That's kinda funny ;) Also you named your class after what it contains somewhere deep down, and not what it's responsible for. I'd instead probably name it Program. As it's nothing else, than that. I'd expect a class named <code>Quadratic_Equations</code> to be an enum containing different Equations.</p>\n\n<h3>2. checkIfValidNumber</h3>\n\n<p>I like the name. It's good, it could describe what it does. I don't like the print-statement and that you have a loop in there. This is one of these \"side-effects\". Your function name makes me expect something different. \nI expect a function applying some constraint to a number and returning true or false depending on the validity of that number to the constraint. </p>\n\n<p>You also hide your whole process behind that. Also: why should a user not enter <code>-1.0</code> for your quadratic equation? It makes no sense to use a number within the valid range to check for validity. instead use boolean return type in your tryParse and make use of the out-parameter. </p>\n\n<h3>3. Reading user input.</h3>\n\n<blockquote>\n<pre><code>double a = tryParse(sc.nextLine());\n a = checkValidNumber(a);\n</code></pre>\n</blockquote>\n\n<p>This makes no sense. You should also move the first <code>tryParse(sc.nextLine());</code> into a method.</p>\n\n<p>Instead I would expect:</p>\n\n<pre><code>double a = promptUserUntilValidInput(\"Please enter a:\");\n</code></pre>\n\n<p>You can move the whole reading to this method.</p>\n\n<pre><code>private double promptUserUntilValidInput(String prompt){\n boolean valid = false;\n double value = 0.0;\n while(!valid){\n System.out.println(prompt);\n //this is the c# attempt...\n valid = tryParse(sc.nextLine(), out value);\n\n //You would need to do something like this in java\n Double result = tryParse(sc.nextLine());\n valid = result != null;\n value = (double)result;\n }\n return value;\n}\n</code></pre>\n\n<p>tryParse would then (in C#) return true, when parsing the number was successful. You'd just need to assign to an out parameter before returning in the method:</p>\n\n<pre><code>private boolean tryParse(String text, out double val){\n try{\n val = new Double(text);\n return true;\n }\n catch (NumberFormatException e){\n return false;\n }\n}\n</code></pre>\n\n<p>This way you also eliminate all checks for <code>-1.0</code>. </p>\n\n<p>But as this is java we need to make it a little more complicated. I'm here heavily relying on <a href=\"https://codereview.stackexchange.com/a/46307/37660\">@Uri Agassi's answer</a> </p>\n\n<pre><code>private Double tryParse(String text){\n try{\n Double value = new Double(text);\n return value;\n }\n catch (NumberFormatException e){\n if(text.matches(\"/^quit$/gi\"))\n Application.Exit;\n else\n return null;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:59:14.657",
"Id": "80833",
"Score": "2",
"body": "this is java - no `out` parameter..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:04:45.557",
"Id": "80837",
"Score": "1",
"body": "lol, you can pass a container, but think how ugly it will look to use it... In my answer I suggested boxing, and returning null - http://dotnetbutchering.blogspot.co.il/2012/07/c-like-tryparse-integer-for-java.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:23:51.407",
"Id": "80872",
"Score": "0",
"body": "I would throw an exception and catch it. It's rather an exceptional case when the user enters an invalid input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:24:42.487",
"Id": "80874",
"Score": "0",
"body": "`Pascal_Snake_Case`, LOL :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:29:08.087",
"Id": "80878",
"Score": "0",
"body": "I like this, but how could I keep the \"Insert -1 to quit program\" part in this example (ie how do I get the logic of that decision all the way back to the main method)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T05:16:03.963",
"Id": "80978",
"Score": "1",
"body": "You should fix the last part, or at least remark that it doesn't work in java: http://codereview.stackexchange.com/questions/46293/quadratic-expression-calculator/46307?noredirect=1#comment80899_46307"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:58:00.847",
"Id": "46298",
"ParentId": "46293",
"Score": "13"
}
},
{
"body": "<h3>Regarding the <code>Scanner</code> object:</h3>\n<p>You're right. I also don't like that. For two reasons.</p>\n<ol>\n<li><p>It's not <code>private final</code>. It's good to restrict things as much as possible (making things private). And as the object reference never changes, it's good practice to mark it as <code>final</code>.</p>\n<pre><code> private static final Scanner sc = new Scanner (System.in);\n</code></pre>\n</li>\n<li><p>It can be a local variable :) It doesn't even need to be <code>private static final</code>. Create it in the <code>main</code> method and then <strong>pass it as a parameter</strong> to any method that needs it.</p>\n</li>\n</ol>\n<hr />\n<h3>Shortening <code>useQuadraticFormula</code></h3>\n<p>How many times are you using <code>Math.pow(b, 2) - (4 * a * c)</code>? <strong>THREE!</strong> It's about time to put it in a variable, don't you think?</p>\n<p>You can also do the initialization and declaration of <code>resul1</code> and <code>result2</code> respectively on the same line.</p>\n<pre><code>public static String useQuadraticFormula(double a, double b, double c) {\n double temp = Math.pow(b, 2) - (4 * a * c);\n if (temp <= 0)\n return "These numbers do not compute - they produce an illegal result.";\n double result1 = (-b + Math.sqrt(temp)) / (2 * a);\n double result2 = (-b - Math.sqrt(temp)) / (2 * a);\n return String.valueOf(result1) + ", " + String.valueOf(result2);\n}\n</code></pre>\n<hr />\n<h3>Object oriented</h3>\n<p>Overall, a good continued development of this would be to make things more object oriented. Create your own class, <code>QuadraticFormula</code> that contains the values of a, b, c. Use a method named <code>computeResult</code> which could return either an integer array (<code>int[]</code>) of length two for the two results, or another custom class, <code>QuadraticResult</code> that could hold the two results, and possibly some of the temporary variables used in-between.</p>\n<h3>Exceptions</h3>\n<pre><code>return "These numbers do not compute - they produce an illegal result.";\n</code></pre>\n<p>If it is illegal, then</p>\n<pre><code>throw new IllegalArgumentException("These numbers produce an illegal result.");\n</code></pre>\n<p><strong>Do not return a "custom constant for 'things went wrong'"</strong> This is really one of those cases when using an exception makes sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:35:03.183",
"Id": "80881",
"Score": "0",
"body": "Thank you for these suggestions. The reason why I _didn't_ throw an exception like in your last line is because it stops the program running, whereas the return statement prints the string, then begins the program over again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:50:14.467",
"Id": "80887",
"Score": "0",
"body": "@Andrew Then you can `catch (IllegalArgumentException e)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:55:00.873",
"Id": "80888",
"Score": "0",
"body": "Sorry - how can I do that? I'm assuming I need a try and catch block, but what would the try statement be?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:16:53.327",
"Id": "46299",
"ParentId": "46293",
"Score": "10"
}
},
{
"body": "<p>When implementing even such a simple code I'd suggest thinking of how you'd like to test it in the automated way (i.e. using standard Java testing framework - JUnit). It will guide you to a better design and in consequence improve your code. </p>\n\n<p>While there is plenty of improvements which can still be done to the attached code as a whole, I will focus on the <code>useQuadraticFormula</code> method as it hasn't been yet extensively commented upon: </p>\n\n<ul>\n<li><p>Firstly the purpose of this method is unclear, as it returns a formatted string. It would be much better to have a method <code>calculateQuadraticFormula</code> which would return the collection of double values (ideally not array, but a dynamic size collection - <code>java.util.Set</code> would be good as it eliminates the duplicates, which can happen if <code>b * b == 4 * a * c</code>). This would allow to test the result of the method (to check whether you received 0, 1 or 2 results and whether the specific values are correct). Then you can format the results to user-friendly string in another function (which also can be tested).</p></li>\n<li><p>As already advised, it makes sense to define the interim value:</p>\n\n<pre><code>double someMeaningfulName = Math.sqrt(Math.pow(b, 2) - (4 * a * c))\n</code></pre>\n\n<p>You can also use <code>import static Math.*</code> which will allow you to write the formula with less noise:</p>\n\n<pre><code>double someMeaningfulName = sqrt(pow(b, 2) - (4 * a * c))\n</code></pre></li>\n<li><p>Finally, using <code>pow(b, 2)</code> is a bit over the top. Instead, <code>b * b</code> is as good, more readable and slightly faster.</p></li>\n</ul>\n\n<p>Please find below the example making use of my comments: </p>\n\n<pre><code>import java.util.Set;\nimport java.util.HashSet;\n\npublic static Set<Double> calculateQuadraticFormula(double a, double b, double c) {\n Set<Double> results = new HashSet<Double>();\n double temp = (b * b) - (4 * a * c);\n if( temp == 0 ) {\n results.add(-b / 2 * a);\n } else if( temp > 0) {\n results.add( (-b + Math.sqrt(temp) ) / (2 * a) );\n results.add( (-b - Math.sqrt(temp) ) / (2 * a) );\n }\n return results;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:49:10.430",
"Id": "80886",
"Score": "0",
"body": "Could you provide any examples of _how_ such a Set method would work for calculating the Quadratic Formula?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:21:14.130",
"Id": "80900",
"Score": "0",
"body": "I've edited my comment to attach the example. Please also note, that it makes sense to split the if >= 0 into 2 separate cases, firstly for performance reasons (avoid duplicate computation), but mostly due to rounding issues with floating point number representation. Therefore in some odd cases you might end up with 2 results (i.e. 9.0000000001 and 8.9999999998) when 1 is expected. You can avoid it by rounding the double results to the number of decimal places making sense for the user."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:19:03.103",
"Id": "46301",
"ParentId": "46293",
"Score": "10"
}
},
{
"body": "<p>In addition to the other comments, I suggest you check for <code>a == 0.0</code> (comparing doubles against zero is about the only safe comparison you can do). If <code>a == 0.0</code> there is a rather simpler way to solve the equation, and the normal quadratic solution will give a division by zero. You probably need to special case <code>(a == 0.0) && (b == 0.0)</code> too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:59:22.677",
"Id": "46306",
"ParentId": "46293",
"Score": "4"
}
},
{
"body": "<p><strong>Who should use scanner?</strong><br>\nAs was already suggested - <code>sc</code> should be a local variable. I don't agree with the suggestion to pass it around as an argument, since I don't think the other methods have any business prompting the user. <code>checkIfValidNumber()</code> should do exactly that - check that the number is valid!</p>\n\n<p><strong>What's the meaning of -1?</strong><br>\nFrom reading your code, I can see a little problem:</p>\n\n<pre><code>if (a == -1) // or b or c\n break;\n</code></pre>\n\n<p>This <code>if</code> will never be true - as <code>-1</code> is considered an indicator that it is invalid, and <code>checkIfValidNumber</code> will then prompt the user for a new number...<br>\nIt is unfortunate that java does not have <code>TryParse</code> like in <code>C#</code>... You can, however use boxing to indicate an <a href=\"http://dotnetbutchering.blogspot.co.il/2012/07/c-like-tryparse-integer-for-java.html\">invalid number as <code>null</code></a>. This way - all valid numbers are fine, including <code>-1</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:41:44.143",
"Id": "80882",
"Score": "0",
"body": "If I use scanner as local variable, I've two questions. 1: If I close it at end of method, is this okay (as it will basically instantiate and close scanner three times, for three different inputs). 2: If inside the tryParse I detect if the user enters -1 (to exit program) and do a System.exit, does it matter that the Scanner hasn't been closed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:00:22.183",
"Id": "80890",
"Score": "0",
"body": "1. In my suggestion, I meant for the scanner to be a local variable of `main()`, not any other method, so you close it in `main()` - once. 2. You _should not_ make any decision regarding `-1` inside `tryParse` - simply return the number. It is the decision of the part which manages the application flow (`main()`) to check for the `-1`, and decide whether to exit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:02:21.487",
"Id": "80891",
"Score": "0",
"body": "See my updated code. I can change the scanner to be in the main, but I'll have to pass it as an argument then to the prompt user method. Additionally, if I check for \"-1\" (or \"exit\" as I now call it) inside the main method, I have to check three times (After each entry) as opposed to once in tryPArse method. Isn't there a better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:10:23.020",
"Id": "80895",
"Score": "0",
"body": "`tryParse` should do what it says - and nothing more. You can check for `\"exit\"` _before_ you pass it to `tryParse`. Btw, your `tryParse` will not work, since arguments in java are passed by pointer, not by reference - `value` in `promptUserUntilValidInput` will always return `0.0` (the initial value)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:15:58.410",
"Id": "80899",
"Score": "0",
"body": "Just realised that. I was following the suggestion from the top rated answer, but I don't think it works."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:01:44.870",
"Id": "46307",
"ParentId": "46293",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>When you need a <code>double</code> don't create a <code>Double</code> object.</p>\n\n<pre><code>double a = tryParse(sc.nextLine()); //<-- tryParse returns Double, causes autounboxing\n</code></pre>\n\n<p>Use <code>double Double.parseDouble(String s)</code> instead.</p>\n\n<pre><code>public static double tryParse(String text) {\n try {\n return Double.parseDouble(text);\n } catch (NumberFormatException e) {\n return -1.0;\n }\n}\n</code></pre></li>\n<li><p>Simplify String concatenation.</p>\n\n<p>When left argument of + is a <code>String</code> you don't need <code>String.valueOf</code>, at least you want apply some format.</p>\n\n<p>In <code>useQuadraticFormula</code> you could write</p>\n\n<pre><code>return String.valueOf(result1) + \", \" + result2;\n</code></pre>\n\n<p>You could event write</p>\n\n<pre><code>return \"\" + result1 + \", \" + result2;\n</code></pre>\n\n<p>When lot of <code>String</code> concatenation are involved, use <code>String.format</code> or <code>StringBuilder</code> (or <code>StringBuffer</code> if thread safety is required).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:14:57.170",
"Id": "46321",
"ParentId": "46293",
"Score": "6"
}
},
{
"body": "<p>checkIfValidNumber() sounds like it is returning a boolean value if the number is valid. Maybe parseValidNumber() throws IllegalNumberException is better.</p>\n\n<p>I would create the Scanner in main() and pass it on to every function that needs it, although it does not seem neccessary here.</p>\n\n<p>Using a Constructor instead of doing all in main() would be good too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T09:37:19.983",
"Id": "80986",
"Score": "0",
"body": "`checkNotNull` from Guava's [`Preconditions`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Preconditions.html#checkNotNull%28T%29) also returns the input value instead of returning boolean. It makes the following possible: `this.x = checkNotNull(x, \"x cannot be null\");` (Anyway, welcome on the site and +1 :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:08:04.570",
"Id": "46347",
"ParentId": "46293",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:32:28.010",
"Id": "46293",
"Score": "13",
"Tags": [
"java",
"beginner",
"mathematics"
],
"Title": "Quadratic expression calculator"
} | 46293 |
<p>I'm upgrading my project from YouTube's V2 API to their V3 API. I'm also taking the time to upgrade to Jasmine 2.0 since I already need to look at my test cases.</p>
<p>Here's a couple of test cases and the corresponding code. Am I doing 'it' correctly? Maybe I should have a spy?</p>
<pre><code>define([
'common/model/youTubeV3API'
], function (YouTubeV3API) {
'use strict';
describe('YouTubeV3API', function () {
describe('when asked to find a playable song by title', function () {
beforeEach(function (done) {
this.result = null;
YouTubeV3API.findPlayableByTitle({
title: 'Gramatik',
success: function (response) {
this.result = response;
done();
}.bind(this)
});
});
it('should return a playable result', function() {
expect(this.result).not.toBeNull();
});
});
describe('when asked to search for songs', function () {
beforeEach(function (done) {
this.result = null;
YouTubeV3API.search({
text: 'Gramatik',
success: function (response) {
this.result = response;
done();
}.bind(this)
});
});
it('should return 50 songs', function () {
expect(this.result.length).toEqual(50);
});
});
}
}
define([
'common/model/utility',
'common/googleAPI'
], function (Utility, GoogleAPI) {
'use strict';
var YouTubeV3API = Backbone.Model.extend({
defaults: {
loaded: false
},
initialize: function () {
GoogleAPI.client.load('youtube', 'v3', function () {
this.set('loaded', true);
}.bind(this));
},
// Performs a search and then grabs the first item most related to the search title by calculating
// the levenshtein distance between all the possibilities and returning the result with the lowest distance.
// Expects options: { title: string, success: function, error: function }
findPlayableByTitle: function (options) {
return this.search({
text: title,
success: function (songInformationList) {
songInformationList.sort(function (a, b) {
return Utility.getLevenshteinDistance(a.title, title) - Utility.getLevenshteinDistance(b.title, title);
});
var songInformation = songInformationList.length > 0 ? songInformationList[0] : null;
options.success(songInformation);
},
error: options.error,
complete: options.complete
});
},
// Performs a search of YouTube with the provided text and returns a list of playable songs (<= max-results)
// Expects options: { maxResults: integer, text: string, fields: string, success: function, error: function }
search: function (options) {
// If the API has not loaded yet - defer calling this event until ready.
if (!this.get('loaded')) {
this.once('change:loaded', function () {
this.search(options);
});
return;
}
var searchListRequest = GoogleAPI.client.youtube.search.list({
part: 'id',
// Probably set this to its default of video/playlist/channel at some point.
type: 'video',
maxResults: options.maxResults || 50,
q: options.text,
// I don't think it's a good idea to filter out results based on safeSearch for music.
safeSearch: 'none'
});
searchListRequest.execute(function (response) {
if (response.error) {
if (options.error) {
options.error({
error: response.error
});
}
if (options.complete) {
options.complete();
}
} else {
var songIds = _.map(response.items, function (item) {
return item.id.videoId;
});
this._getSongInformationList(songIds, function (songInformationList) {
options.success(songInformationList);
if (options.complete) {
options.complete();
}
});
}
}.bind(this));
},
// Converts a list of YouTube song ids into actual video information by querying YouTube with the list of ids.
_getSongInformationList: function(songIds, callback) {
// Now I need to take these songIds and get their information.
var songsListRequest = GoogleAPI.client.youtube.videos.list({
part: 'contentDetails,snippet',
maxResults: 50,
id: songIds.join(',')
});
songsListRequest.execute(function (response) {
var songInformationList = _.map(response.items, function (item) {
return {
id: item.id,
duration: Utility.iso8061DurationToSeconds(item.contentDetails.duration),
title: item.snippet.title,
author: item.snippet.channelTitle
};
});
callback(songInformationList);
});
}
});
return new YouTubeV3API();
});
</code></pre>
<p>My main concerns are:</p>
<ul>
<li>I'm really interested in knowing I am calling YouTube's API properly, but I think it's best practice to stub out the calls to YouTube and mock responses. Is that true?</li>
<li>I'm not using a Spy to check success value, but, again, seems a bit awkward to actually use it in my scenario... Would love an example.</li>
<li>Jasmine 2.0 syntax reads nicer, but seems a bit less generous with asynchronous calls. Have I structured things properly by placing code in a beforeEach, but only have one "it" call? I don't think I want to hammer YouTube's API many times for each "it" following a "beforeEach" ... so it seems odd to have it there. This problem would go away with stubbing my calls to YouTube though..</li>
</ul>
| [] | [
{
"body": "<p>This looks okay to me, the only thing I will comment on is this:</p>\n\n<pre><code> if (response.error) {\n if (options.error) {\n options.error({\n error: response.error\n });\n }\n\n if (options.complete) {\n options.complete();\n }\n }\n</code></pre>\n\n<p>If you default <code>.complete()</code> and <code>.error()</code> like this:</p>\n\n<pre><code> var doNothing = function(){};\n options.complete = options.complete || doNothing();\n options.error = options.error || doNothing();\n</code></pre>\n\n<p>then that first block would be simply</p>\n\n<pre><code> if (response.error) {\n options.error({ error: response.error });\n options.complete();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:42:20.870",
"Id": "47164",
"ParentId": "46297",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:56:31.640",
"Id": "46297",
"Score": "4",
"Tags": [
"javascript",
"unit-testing",
"youtube",
"jasmine"
],
"Title": "Testing async YouTube API calls using Jasmine 2.0"
} | 46297 |
<p>I have an XML document that contains "ads" and includes information about the department name, image name, link to URL, and alt text. I have a PHP function that accepts two arguments, department name and the number of "ads" to display. It reads through the entire XML document, and stores the information in arrays if the department name matches what is passed to the argument or matches "all". What I have works, but it seems rather long and cumbersome. Is there a way to shorten it and improve performance?</p>
<p><strong>PHP</strong></p>
<pre><code>function rightAds($deptName, $displayNumber) {
//load xml
/* --- Original loading, left in for completeness
$completeurl = "http://example.com/example.xml";
$xml = simplexml_load_file($completeurl);
--- */
//Loading without an HTTP call, as per Corbin's point
$xml = simplexml_load_file(dirname(__FILE__)."/smallAdsByDepartment.xml");
$smallAds = $xml->smallAds;
//number of ads that can be used for department
$numberForDepartment = 0;
//loop through xml document, save the ads that are "all" or the department name
foreach($smallAds as $ad) {
//get department name
$departmentName = $ad->departmentName;
//if it is a valid department, add info to corresponding arrays
if((strpos($departmentName, $deptName) !== false) || (strpos($departmentName, "all") !== false)) {
//PT exception. If department name includes noPT, and provided name is pt, don't include the image
if(($deptName == "pt" && strpos($departmentName, "noPT") !== false) || (strpos(dirname($_SERVER['PHP_SELF']), "pt") !== false && basename($_SERVER['REQUEST_URI']) == "admissions.php" && strpos($departmentName, "noPT") !== false )) {
continue;
}
//CLS exception.
if(($deptName == "cls" && strpos($departmentName, "noCLS") !== false)) {
continue;
}
$name[$numberForDepartment] = $ad->name;
$alt[$numberForDepartment] = $ad->alt;
$linkTo[$numberForDepartment] = $ad->linkTo;
$numberForDepartment++;
}
}
//if $displayNumber is 1, or an invalid negative number, display random ad.
if($displayNumber <= 1) {
$randKeys = mt_rand(0, $numberForDepartment);
echo "<div class='adRight'><a href='$linkTo[$randKeys]'><img src='../../includes/images/adImages/$name[$randKeys]' alt='$alt[$randKeys]'></a></div>";
}
else {
//get a list of randomly selected keys from the array
$randKeys = range(0, (count($name) - 1));
shuffle($randKeys);
$numberOfAds = 0;
//loop through and display image/link for each
foreach($randKeys as $adNumber) {
echo "<div class='adRight'><a href='" . $linkTo[$adNumber] . "' tabindex='0'><img src='../../includes/images/adImages/" . $name[$adNumber] . "' alt='" . $alt[$adNumber] . "'></a></div>";
$numberOfAds++;
if($numberOfAds == $displayNumber) { break; }
}
}
}
</code></pre>
<p><strong>Example XML</strong></p>
<pre class="lang-xml prettyprint-override"><code><smallAds>
<departmentName>all</departmentName>
<name>smallAd3.jpg</name>
<alt>Faculty Research</alt>
<linkTo>http://example.com/research/index.php</linkTo>
</smallAds>
<smallAds>
<departmentName>all, noPT</departmentName>
<name>smallAd6.jpg</name>
<alt>Advising</alt>
<linkTo>http://example.com/advising.php</linkTo>
</smallAds>
<smallAds>
<departmentName>all, noCLS</departmentName>
<name>checkYouTube.png</name>
<alt>Check us out on YouTube</alt>
<linkTo>http://www.youtube.com/user/example</linkTo>
</smallAds>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:39:27.393",
"Id": "80825",
"Score": "0",
"body": "Is using XML a requirement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:45:29.687",
"Id": "80826",
"Score": "0",
"body": "I wouldn't be opposed to json, and there aren't that many ads so it wouldn't be too much of a hassle to convert it."
}
] | [
{
"body": "<p>If you can use any format, use serialized PHP, it's by far the fastest.</p>\n\n<pre><code><?php\n\nclass Ad {\n\n public $alt;\n\n public $departmentName;\n\n public $linkTo;\n\n public $name;\n\n}\n\nfunction formatAd(Ad $ad) {\n return \"<div class='adRight'><a href='{$ad->linkTo}'><img src='../../includes/images/adImages/{$ad->name}' alt='{$ad->alt}'></a></div>\";\n}\n\nfunction rightAds($departmentName, $displayNumber) {\n static $ads = null;\n\n if (!$ads) {\n $ads = unserialize(file_get_contents(__DIR__ . \"/smallAdsByDepartment.ser\"));\n }\n\n $pt = $departmentName === \"pt\";\n\n /* @var $ad Ad */\n foreach ($ads as $delta => $ad) {\n if (strpos($ad->departmentName, $departmentName) !== false || strpos($departmentName, \"all\") !== false) {\n $noPT = strpos($ad->departmentName, \"noPT\") !== false;\n if (($pt && $noPT) || (strpos(__DIR__, \"pt\") !== false && basename($_SERVER[\"REQUEST_URI\"]) === \"admissions.php\" && $noPT) || ($departmentName === \"cls\" && strpos($ad->departmentName, \"noCLS\") !== false)) {\n unset($ads[$delta]);\n }\n }\n }\n\n if ($displayNumber <= 1) {\n echo formatAd($ads[mt_rand(0, count($ads) - 1)]);\n }\n else {\n $keys = range(0, count($ads) - 1);\n shuffle($keys);\n $c = count($keys);\n for ($i = 0; $i < $c; ++$i) {\n echo formatAd($ads[$keys[$i]]);\n if ($i === $displayNumber) {\n break;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-04T15:19:15.710",
"Id": "56114",
"ParentId": "46302",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "56114",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:34:15.560",
"Id": "46302",
"Score": "3",
"Tags": [
"php",
"performance",
"random",
"xml"
],
"Title": "Displaying random \"ads\" from an XML document"
} | 46302 |
<p>I needed a variadic function to pack and unpack bits into integer types. This is my first attempt:</p>
<pre><code>template<typename T>
constexpr T pack(bool b)
{
return b;
}
template<typename T, typename... Types>
constexpr T pack(bool b, Types... args)
{
return (b << sizeof...(Types)) | pack<T>(args...);
}
template<typename T, typename... Types>
void unpack(T packed, bool& b1)
{
b1 = packed & 1;
}
template<typename T, typename... Types>
void unpack(T packed, bool& b1, Types&... args)
{
b1 = packed & (1 << sizeof...(Types));
unpack(packed, args...);
}
</code></pre>
<p>Usage example:</p>
<pre><code>int main(void)
{
std::cout << pack<int>(1, 0, 0, 1, 0, 1, 1, 0) << std::endl; // 150
std::cout << pack<int>(1, 0, 1) << std::endl; // 5
int val = pack<int>(1, 0, 1);
bool b1, b2, b3;
unpack(val, b1, b2, b3);
std::cout << b1 << " " << b2 << " " << b3 << std::endl; // 1 0 1
}
</code></pre>
<p>Does this code contain any bugs, can it be improved, and are variadic templates used appropriately here (I still don't master their syntax)?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:50:20.297",
"Id": "80829",
"Score": "0",
"body": "Two minor things I see: 1.) Replace each `std::endl` with `\"\\n\"` 2.) In C++, `main()` doesn't need a `void` parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:52:16.323",
"Id": "80831",
"Score": "0",
"body": "OK, thanks. Anything about the core parts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:53:51.900",
"Id": "80832",
"Score": "0",
"body": "Nothing that I can see. I'm not familiar with variadic templates."
}
] | [
{
"body": "<h2>Missing overflow check</h2>\n\n<p>One serious flaw that I see in this code is that the user needs to determine the number of parameters to <code>unpack</code>. This is a no go for a function whose output depends on a runtime input. Even worse there is no check that would tell the user that the actual number overflows the number of bits given to be unpacked into.</p>\n\n<p>One possible solution would be to return an <code>std::vector<bool></code> to fit the whole number.</p>\n\n<p>The other solution would be to retain the current interface but to introduce error notification (by exception or return code).</p>\n\n<h2>Unnecessary template parameter</h2>\n\n<p>Another thing regarding the <code>unpack</code> function:\nIt seems that you don't need the <code>Types</code> parameter in the recursion end, so it becomes:</p>\n\n<pre><code>template<typename T>\nvoid unpack(T packed, bool& b1)\n{\n b1 = packed & 1;\n}\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>The function parameter names could be better.\nI assume <code>b1</code> is only appropriate in the top level call of the function. I cannot decide on a better name now, but it should indicate that it is the current bit. Likewise, <code>args</code> should be named <code>remainingBits</code> or something like this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:00:59.070",
"Id": "80834",
"Score": "0",
"body": "The unnecessary template parameter is a plain oversight. About the rest I will think about it - I will never use a vector, this is exactly the point of this exercise, but if there is a way to make things more robust without a vector, I'll pursue it. About the naming, I have often seen \"head\" and \"tail\" but I don't find them quite appropriate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:04:21.570",
"Id": "80836",
"Score": "0",
"body": "If it is only for the sake of making it \"static\" then you could make the packed parameter a template parameter, thus removing the possibility of runtime values that forbid the use of the specific parameter list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:09:57.147",
"Id": "80838",
"Score": "0",
"body": "The `pack()` function needs to be evaluable also at compile-time (provided the passed arguments are), and actually it should be now - I hope the compiler is able to understand it - so that you can even use it in a switch case.\nThe `unpack()` function should accept whatever packed value at runtime. I will really think about this, but while I consider very valuable writing robust code, I think this is one of the cases in which the client should be really aware of what it's doing. The performance of this should be no worse than a handcrafted sequence of bitwise operations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:12:59.733",
"Id": "80839",
"Score": "0",
"body": "It is hard to be aware of the value of runtime variables if you don't check them. And if you check them beforehand you might forget to update the check together with the function call. Best way is to let the function itself do the checking and report an error if there is one. I find it a fairly harsh decision to put the burden onto the user of this function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:17:22.060",
"Id": "80841",
"Score": "0",
"body": "We have vector's `operator[]` that doesn't necessarily check the boundaries (and many implementations don't), and virtually any function in the C++ standard library is prone to undefined behavior. This thing should perform as fast as it can and I do not want to introduce any branching, not to mention dynamic memory allocation. (PS: I forgot... +1 for your excellent answer)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:22:13.503",
"Id": "80843",
"Score": "0",
"body": "I place correctness over fastness. Also there are ways to introduce checks that are turned of for release builds (there are also \"checked implementations\" of `operator[]` that help to find bugs that would otherwise go unnoticed). If you are very keen about saving the user from dismal runtime (by avoiding a check that will most likely need only one clock cycle) provide a checked equivalent (like `at()`) or better a switch that will turn off the checking during release build."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:31:08.913",
"Id": "80846",
"Score": "0",
"body": "If we have to bound check everything and performance is not critical, we may use Python which is elegant and powerful. However, making a checked implementation, with checks that can be disabled via compile switches, is really a cool idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:33:25.960",
"Id": "80848",
"Score": "0",
"body": "The point is to default to the check being on. I would not even start about thinking to turn it off until I find hard evidence (by profiling) that it is a bottleneck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:35:59.543",
"Id": "80849",
"Score": "0",
"body": "OK, I see. Out of curiosity (this question may seem polemic but it's not in this context) do you use a \"safe\" STL, or do you enforce a \"safe\" mode in your STL? I really think gcc comes with a \"do whatever you want, it's your responsibility\" STL, and you have to pass a parameter to have some seatbelts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:39:28.740",
"Id": "80850",
"Score": "0",
"body": "I unfortunately do not use a safe implementation (I use the default one, which is why I make the point for the default to be \"checks on\") because I was to lazy to install a checked one yet. However, I am trying to use checked calls and write my own code with many checks. Using C++ indicates that you want to maximize performance but still you want to maximize correctness first. I myself am not clean of the fallacy of premature optimization :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:44:02.950",
"Id": "80852",
"Score": "0",
"body": "No problem, then, let the caller be aware or not of what it's doing. I think that the C++ way is not \"no checks, we want our planes to crash\" but just \"do whatever you are sure about, no unnecessary check *on my side*\". And I think you are right using a non checked STL, as your code is probably built in a way that there is no way you can read a vector beyond the boundary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:52:32.450",
"Id": "80858",
"Score": "0",
"body": "Actually, I think that I am wrong using a non checked stdlib. Even if I try to use the checked versions, something might slip through. There might be transitive errors in template functions from other libraries that can be caught this way... Sure the C/++ community has always had the \"it is your own decision\" mentality but I think it is dangerous to rely on the user making conscious decisions where in fact most decisions are made in unawareness. So the conscious decision should be to opt out from safety and not the other way around."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:20:50.790",
"Id": "80870",
"Score": "0",
"body": "Well, I have tried to implement some compile-time checks. See my updated question :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:55:58.750",
"Id": "80994",
"Score": "0",
"body": "I think you overshot a little bit. Enforcing `sizeof(T)*8` gives you a minimum of 8 parameters that the user has to pass. Of course this is the only thing you could do to check at compiletime but as the problem lies in runtime I would do this check as an assert or with if and throwing an `std::overflow_error` exception. In any case the test should be against the real value and not the maximum. Besides that it looks good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:25:52.657",
"Id": "81001",
"Score": "0",
"body": "Actually the user can pass less than 8 parameters, he/she just cannot pass more than the ones the packed integer is able to provide, and this can be checked at compile time so why should I enforce it at runtime? I encourage you to try it - if there are no bugs in the code (which is a big if), I basically implemented the checks you asked for without a single runtime instruction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T12:48:27.583",
"Id": "81008",
"Score": "0",
"body": "I misread the relation sign (or better: I assumed it was right because I thought you did the test I was meaning). What I am going on about is not too many bits to extract into but too few (say you want to store the value 8 into 2 bits). This is a pure runtime problem (as the number could be 8 but it could also be always only two bits, who knows?) and can only be checked very conservatively during compile time. If the user happens to supply to few bits she might accidentally (and without knowing) loose the most significant bits and there is no warning about this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:08:36.053",
"Id": "81012",
"Score": "0",
"body": "Honestly I have no idea of what you mean. Can you pastebin an example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:19:19.183",
"Id": "81014",
"Score": "0",
"body": "I have scribbled together a live example here: http://ideone.com/1R3xlP"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:01:37.770",
"Id": "81356",
"Score": "0",
"body": "@gd1: I just noticed that the default glibcxx already comes with checked implementations, you just have to turn them on by defining the macro `_GLIBCXX_DEBUG`. After doing this I found loads of iterator errors in one of my programs (which ran fine so far)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:07:10.773",
"Id": "81357",
"Score": "0",
"body": "God, sorry to hear that. Happy debugging. I'll do this check as well, thanks."
}
],
"meta_data": {
"CommentCount": "20",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:53:26.340",
"Id": "46304",
"ParentId": "46303",
"Score": "5"
}
},
{
"body": "<p>I guess you are aware of <a href=\"http://en.cppreference.com/w/cpp/utility/bitset\" rel=\"nofollow noreferrer\">std::bitset</a> and you have your own reasons for doing this. Your <code>pack</code> seems fine, but <code>unpack</code> requires the user to set up a particular number of <code>bool</code> variables, which is not convenient. An alternative could be to use an <code>std::array</code> for the output:</p>\n\n<pre><code>template<size_t N>\nusing size = std::integral_constant<size_t, N>;\n\ntemplate<size_t N, typename T>\nvoid unpack(size<N>, array<bool, N>& a, T) { }\n\ntemplate<size_t I, size_t N, typename T>\nvoid unpack(size<I>, array<bool, N>& a, T packed)\n{\n a[N-I-1] = (packed & (1 << I)) != 0;\n unpack(size<I+1>(), a, packed);\n}\n\ntemplate<typename T>\nstd::array<bool, 8*sizeof(T)>\nunpack(T packed)\n{\n std::array<bool, 8*sizeof(T)> a = {};\n unpack(size<0>(), a, packed);\n return a;\n}\n</code></pre>\n\n<p>which can be used like this</p>\n\n<pre><code>int val = pack<int>(1, 0, 1);\nstd::cout << unpack(val) << std::endl;\n// prints 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1\n</code></pre>\n\n<p>assuming a simple streaming operator</p>\n\n<pre><code>template<typename S, typename T, size_t N>\nS& operator<<(S& s, const std::array<T, N>& a)\n{\n for (auto i : a)\n s << i << \" \";\n return s;\n}\n</code></pre>\n\n<p>This way you know for sure there is no overflow in the output.</p>\n\n<p>Now, <code>std::vector</code> is another alternative for output that may benefit from its compact <code>std::vector<bool></code> specialization (and <code>std::bitset</code> of course). On the other hand, using <code>std::array</code>, one may obtain a really <code>constexpr</code> version of <code>unpack</code>, without recursion. <code>pack</code> may similarly be non-recursive, remaining <code>constexpr</code>. If you like this potential, I can elaborate.</p>\n\n<hr>\n\n<p><strong>Update: <code>constexpr</code> version</strong></p>\n\n<p>It turns out <code>pack</code> is quite tricky to make non-recursive <em>and</em> <code>constexpr</code>, but as promised, here is a non-recursive, <code>constexpr</code> version of <code>unpack</code> (<a href=\"http://coliru.stacked-crooked.com/a/e29d2306b001eb49\" rel=\"nofollow noreferrer\">complete, live example</a>):</p>\n\n<pre><code>template <size_t... N>\nstruct sizes { using type = sizes <N...>; };\n\ntemplate<size_t N, size_t... I, typename T>\nconstexpr std::array<bool, N>\nunpack(sizes<I...>, T packed)\n{\n return std::array<bool, N>{{(packed & (1 << (N-I-1))) != 0 ...}};\n}\n\ntemplate<size_t N, typename T>\nconstexpr std::array<bool, N>\nunpack(T packed)\n{\n return unpack<N>(typename Range<N>::type(), packed);\n}\n\ntemplate<typename T, size_t N = 8*sizeof(T)>\nconstexpr std::array<bool, N>\nunpack(T packed) { return unpack<N>(packed); }\n</code></pre>\n\n<p>where <code>Range<N></code> contains sequence <code>0,...N-1</code> and is defined <a href=\"https://codereview.stackexchange.com/a/45334/39083\">here</a>. Now you can use it like this:</p>\n\n<pre><code>int val = pack<int>(1, 0, 1);\n\n// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1\nstd::cout << unpack(val) << std::endl;\n\n// 0 0 0 0 0 1 0 1\nstd::cout << unpack<8>(val) << std::endl;\n</code></pre>\n\n<p>The first version returns the entire array needed to represent the precision of the given (integral) type. The second allows you to specify a shorter length for the array; the remaining (leftmost) bits are discarded.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:43:35.773",
"Id": "80851",
"Score": "0",
"body": "Altough I am not the OP I would like to hear about the `constexpr` version of `unpack` :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:44:50.597",
"Id": "80853",
"Score": "0",
"body": "Well obviously yes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:46:09.660",
"Id": "80854",
"Score": "0",
"body": "Ok, I will be back as soon as possible... :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:49:05.627",
"Id": "80857",
"Score": "0",
"body": "@gd1 Sorry, I forgot, it's just a shortcut. See edit for the definition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:43:54.450",
"Id": "80883",
"Score": "0",
"body": "@Nobody,gd1 Updated with `constexpr` `unpack`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:50:11.230",
"Id": "80992",
"Score": "0",
"body": "Nice, I did not know one could use the `...` to do this. Unfortunately I cannot give you another upvote."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:38:10.360",
"Id": "46311",
"ParentId": "46303",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46304",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:42:05.913",
"Id": "46303",
"Score": "6",
"Tags": [
"c++",
"c++11",
"bitwise",
"variadic"
],
"Title": "Bit packing and unpacking"
} | 46303 |
<p>I have two <code>ModelForm</code>s that are the same, except that one of them has its form layout built in a view and one has a <kbd>submit</kbd> button. These are pretty long and I have a ton of duplicate code. I have tried subclassing, but I don't understand it well enough to make it work right. I end up unable to override things.</p>
<pre><code>class SurveyForm(forms.ModelForm):
nsf_CHOICES = (
(1, 'Never',),
(2, '',),
(3, 'Sometimes',),
(4, '',),
(5, 'Frequently',),
)
nmv_CHOICES = (
(1, 'Not Descriptive'),
(2, ''),
(3, ''),
(4, 'Moderately Descriptive'),
(5, ''),
(6, ''),
(7, 'Very Descriptive'),
)
aggbs_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_0')[0].verbose_name, empty_value=0)
aggbs_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_1')[0].verbose_name, empty_value=0)
aggbs_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_2')[0].verbose_name, empty_value=0)
aggbs_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_3')[0].verbose_name, empty_value=0)
aggbs_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_4')[0].verbose_name, empty_value=0)
aggbs_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_5')[0].verbose_name, empty_value=0)
aggbs_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_6')[0].verbose_name, empty_value=0)
aggbs_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_7')[0].verbose_name, empty_value=0)
si_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_0')[0].verbose_name, empty_value=0)
si_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_1')[0].verbose_name, empty_value=0)
si_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_2')[0].verbose_name, empty_value=0)
si_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_3')[0].verbose_name, empty_value=0)
si_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_4')[0].verbose_name, empty_value=0)
si_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_5')[0].verbose_name, empty_value=0)
si_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_6')[0].verbose_name, empty_value=0)
si_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_7')[0].verbose_name, empty_value=0)
cfiab_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_0')[0].verbose_name, empty_value=0)
cfiab_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_1')[0].verbose_name, empty_value=0)
cfiab_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_2')[0].verbose_name, empty_value=0)
cfiab_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_3')[0].verbose_name, empty_value=0)
cfiab_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_4')[0].verbose_name, empty_value=0)
cfiab_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_5')[0].verbose_name, empty_value=0)
cfiab_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_6')[0].verbose_name, empty_value=0)
cfiab_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_7')[0].verbose_name, empty_value=0)
cfimb_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_0')[0].verbose_name, empty_value=0)
cfimb_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_1')[0].verbose_name, empty_value=0)
cfimb_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_2')[0].verbose_name, empty_value=0)
cfimb_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_3')[0].verbose_name, empty_value=0)
cfimb_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_4')[0].verbose_name, empty_value=0)
cfimb_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_5')[0].verbose_name, empty_value=0)
cfimb_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_6')[0].verbose_name, empty_value=0)
cfimb_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_7')[0].verbose_name, empty_value=0)
cfimb_8 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_8')[0].verbose_name, empty_value=0)
class Meta:
model = Survey
exlude = 'cei_total','aggbs_total','si_total','cfiab_total','cfimb_total'
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.form_method = 'post'
self.helper.form_tag = False
super(SurveyForm, self).__init__(*args, **kwargs)
class UpdateSurveyForm(forms.ModelForm):
nsf_CHOICES = (
(1, 'Never',),
(2, '',),
(3, 'Sometimes',),
(4, '',),
(5, 'Frequently',),
)
nmv_CHOICES = (
(1, 'Not Descriptive'),
(2, ''),
(3, ''),
(4, 'Moderately Descriptive'),
(5, ''),
(6, ''),
(7, 'Very Descriptive'),
)
aggbs_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_0')[0].verbose_name, empty_value=0)
aggbs_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_1')[0].verbose_name, empty_value=0)
aggbs_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_2')[0].verbose_name, empty_value=0)
aggbs_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_3')[0].verbose_name, empty_value=0)
aggbs_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_4')[0].verbose_name, empty_value=0)
aggbs_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_5')[0].verbose_name, empty_value=0)
aggbs_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_6')[0].verbose_name, empty_value=0)
aggbs_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('aggbs_7')[0].verbose_name, empty_value=0)
si_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_0')[0].verbose_name, empty_value=0)
si_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_1')[0].verbose_name, empty_value=0)
si_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_2')[0].verbose_name, empty_value=0)
si_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_3')[0].verbose_name, empty_value=0)
si_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_4')[0].verbose_name, empty_value=0)
si_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_5')[0].verbose_name, empty_value=0)
si_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_6')[0].verbose_name, empty_value=0)
si_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nmv_CHOICES, label=Survey._meta.get_field_by_name('si_7')[0].verbose_name, empty_value=0)
cfiab_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_0')[0].verbose_name, empty_value=0)
cfiab_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_1')[0].verbose_name, empty_value=0)
cfiab_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_2')[0].verbose_name, empty_value=0)
cfiab_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_3')[0].verbose_name, empty_value=0)
cfiab_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_4')[0].verbose_name, empty_value=0)
cfiab_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_5')[0].verbose_name, empty_value=0)
cfiab_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_6')[0].verbose_name, empty_value=0)
cfiab_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfiab_7')[0].verbose_name, empty_value=0)
cfimb_0 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_0')[0].verbose_name, empty_value=0)
cfimb_1 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_1')[0].verbose_name, empty_value=0)
cfimb_2 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_2')[0].verbose_name, empty_value=0)
cfimb_3 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_3')[0].verbose_name, empty_value=0)
cfimb_4 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_4')[0].verbose_name, empty_value=0)
cfimb_5 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_5')[0].verbose_name, empty_value=0)
cfimb_6 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_6')[0].verbose_name, empty_value=0)
cfimb_7 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_7')[0].verbose_name, empty_value=0)
cfimb_8 = forms.TypedChoiceField(required=False, widget=forms.RadioSelect(renderer=HorizRadioRenderer), choices=nsf_CHOICES, label=Survey._meta.get_field_by_name('cfimb_8')[0].verbose_name, empty_value=0)
class Meta:
model = Survey
exlude = 'cei_total','aggbs_total','si_total','cfiab_total','cfimb_total'
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.form_method = 'post'
self.helper.form_action = ''
self.helper.layout = Layout(
Field('student', type='hidden'),
Field('surveyset', type='hidden'),
Field('behavior_type', type='hidden'),
Field('ranking', type='hidden'),
Fieldset('Critical Events Index',
HTML("""
<p>Check each behavior from the list below that the child has exhibited during this school year. Complete this using your knowledge of <b>{{ student }}</b> during this school year.</p>
"""),
'cei_0','cei_1','cei_2','cei_3','cei_4','cei_5','cei_6','cei_7','cei_8','cei_9','cei_10','cei_11','cei_12','cei_13','cei_14','cei_15',
),
Fieldset('Aggressive Behavior Scale',
HTML("""
<p>The numbers one through five are used to show the estimate of the frequency with which each item occurs. Choose the number that best represents the amount of times this behavior happens. Complete this scale using your knowledge of <b>{{ student }}</b> during this school year.</p>
"""),'aggbs_0','aggbs_1','aggbs_2','aggbs_3','aggbs_4','aggbs_5','aggbs_6','aggbs_7',
),
Fieldset('Social Interaction',
HTML("""
<p>The numbers one through seven are used to show the estimate of the frequency with which each item occurs. Choose the number that best represents the amount of times this behavior happens. Complete this scale using your knowledge of <b>{{ student }}</b> during this school year.</p>
"""),'si_0','si_1','si_2','si_3','si_4','si_5','si_6','si_7',
),
Fieldset('Combined Frequency Index Adaptive Behavior',
HTML("""
<p>The numbers one through five are used to show the estimate of the frequency with which each item occurs. Choose the number that best represents the amount of times this behavior happens. Complete this scale using your knowledge of <b>{{ student }}</b> during this school year.</p>
"""), 'cfiab_0','cfiab_1','cfiab_2','cfiab_3','cfiab_4','cfiab_5','cfiab_6','cfiab_7',
),
Fieldset('Combined Frequency Index Maladaptive Behavior',
HTML("""<p>The numbers one through five are used to show the estimate of the frequency with which each item occurs. Choose the number that best represents the amount of times this behavior happens. Complete this scale using your knowledge of <b>{{ student }}</b> during this school year.</p>
"""),
'cfimb_0','cfimb_1','cfimb_2','cfimb_3','cfimb_4','cfimb_5','cfimb_6','cfimb_7','cfimb_8',
),
)
self.helper.add_input(Submit('submit', 'Update', css_class='button'))
super(UpdateSurveyForm, self).__init__(*args, **kwargs)
</code></pre>
<p>The reason I have both these is that one is used in a formset and the other is used standalone. I am also using <a href="http://django-crispy-forms.readthedocs.org/en/latest/">crispy forms</a>, hence the <code>FormHelper()</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:16:25.803",
"Id": "81061",
"Score": "1",
"body": "Can you please wrap your code at 80 columns as per PEP8? It's hard to read at the moment with all the scrolling."
}
] | [
{
"body": "<p>Here's an approach. </p>\n\n<p>Start out by defining a empty class, say, FormTemplate that inherits from forms.ModelForm and let both SurveyForm and UpdateSurveyForm inherit from FormTemplate. Make sure that works. I guess FormTemplate will need an <code>__init__()</code> that forwards <code>super(...).__init__()</code> calls to forms.ModelForm.</p>\n\n<p>Then, move nsf_CHOICES into FormTemplate and out of {Update,}SurveyForm. Make sure that works.</p>\n\n<p>Move nvm_CHOICES into FormTemplate and out of {Update,}SurveyForm. Make sure that works.</p>\n\n<p>Lather, rinse, and repeat until you've pulled all the common stuff that out you can out of the child classes and into FormTemplate.</p>\n\n<p>Use git (or some other VCS) and commit every time you get things working before doing the next piece. That way, you'll always have a working version to back up to if you need to.</p>\n\n<p>Also, as Ruslan suggests, wrapping your lines at 80 columns would make your code much more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T03:08:42.933",
"Id": "47534",
"ParentId": "46305",
"Score": "1"
}
},
{
"body": "<p>Also, it's generally considered bad practice to use <code>exclude</code>: if new fields are added to the model they will be rendered for the client by default. It's much safer to use explicitly whitelist fields using the <code>fields</code> attribute of the meta class. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-11T00:43:34.690",
"Id": "49447",
"ParentId": "46305",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:57:44.913",
"Id": "46305",
"Score": "8",
"Tags": [
"python",
"form",
"django"
],
"Title": "How to DRY up my forms.py?"
} | 46305 |
<p>Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests. </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:27:09.350",
"Id": "46308",
"Score": "0",
"Tags": null,
"Title": null
} | 46308 |
<p>I'm writing a simple Pong game. I have a method <code>bounce()</code> that makes everything run: the ball, the paddles, score etc. and it uses 12 arguments: 3 counters, 2 paddles, ball, 5 textures, 1 color. I'm a beginner to programming and only have couple months college experience so I don't know if that's too much. In classes, I usually had 1-3 arguments per method. Am I doing something wrong?</p>
<p>In method <code>run()</code> I'm creating everything I need for the graphics, then I call looped <code>bounce()</code> and I need to pass everything I just created as an argument. This seems very wrong to me, but I fail to find a way around it.</p>
<p>Please ignore non-English comments in code.</p>
<pre><code>import java.awt.Color;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.util.Random;
import acm.graphics.GImage;
import acm.graphics.GLabel;
import acm.graphics.GOval;
import acm.graphics.GRect;
import acm.program.GraphicsProgram;
/* TO DO LIST
* ------------------
* Corner Bounce
* Difficulty Level
*
*
*
*/
@SuppressWarnings("serial")
public class Pong extends GraphicsProgram {
private static final double PAUSE = 1000 / 96.0;
public Random rand = new Random();
public double mouseY;
// ball
private static final double BALL_SIZE = 20;
private static final double SPEED = 5;
public double dx = SPEED * 1.5;
public double dy = SPEED;
public double startX;
public double startY;
// paddle
private static double HEIGHT = 150;
private static double WIDTH = 15;
private static int COUNTER = 0;
public static double AI_SPEED = 9.0; // difficulty 0-20
// label
private float TRANSPARENCY = 0.0f;
public int AI_SCORE = 0;
public int PLAYER_SCORE = 0;
public static void main(String[] args) {
Pong p = new Pong();
p.run();
}
public void run() {
addMouseListeners();
GLabel counter = new GLabel(String.valueOf(COUNTER));
GLabel AiScore = new GLabel(String.valueOf(AI_SCORE));
GLabel PlayerScore = new GLabel(String.valueOf(COUNTER));
counter.setFont("Impact-600");
AiScore.setFont("Impact-100");
PlayerScore.setFont("Impact-100");
Color labelC = new Color(0, 0.0f, 0.0f, TRANSPARENCY);
Color scoreC = new Color(0, 0.0f, 0.0f, 0.1f);
counter.setColor(labelC);
AiScore.setColor(scoreC);
PlayerScore.setColor(scoreC);
counter.setLocation(getWidth() / 2 - counter.getWidth() / 2,
getHeight() / 2 + counter.getHeight() / 3.2);
counter.sendToFront();
Image texture = getImage(getCodeBase(), "texture.png");
Image texture2 = getImage(getCodeBase(), "texture2.png");
Image ballTexture = getImage(getCodeBase(), "ballTexture.png");
Image greenFlash = getImage(getCodeBase(), "greenFlash.png");
Image blueFlash = getImage(getCodeBase(), "blueFlash.png");
GImage image = new GImage(texture);
GImage image2 = new GImage(texture2);
GImage image3 = new GImage(ballTexture);
GImage image4 = new GImage(greenFlash, -250, 0);
GImage image5 = new GImage(blueFlash, -250, 0);
add(image);
add(image2);
add(image3);
add(image4);
add(image5);
add(counter);
image.setSize(WIDTH + 1, HEIGHT + 1);
image2.setSize(WIDTH + 1, HEIGHT + 1);
image3.setSize(BALL_SIZE, BALL_SIZE);
image4.setSize(100, 300);
image5.setSize(100, 300);
GOval ball = makeBall();
GRect paddleLeft = makePaddle();
GRect paddleRight = makePaddle();
add(paddleLeft);
add(paddleRight);
bounce(labelC, AiScore, PlayerScore, counter, ball, paddleLeft,
paddleRight, image, image2, image3, image4, image5);
}
public static GRect makePaddle() {
GRect result = new GRect(0, 0, WIDTH, HEIGHT);
result.setFilled(true);
result.setColor(Color.BLACK);
return result;
}
public static GOval makeBall() {
GOval result = new GOval(150, 100, BALL_SIZE, BALL_SIZE);
result.setFilled(true);
result.setColor(Color.WHITE);
return result;
}
public void mouseMoved(MouseEvent e) {
mouseY = e.getY();
}
public void bounce(Color labelC, GLabel AiScore, GLabel PlayerScore,
GLabel counter, GOval ball, GRect paddleLeft, GRect paddleRight,
GImage image, GImage image2, GImage ballTexture, GImage greenFlash,
GImage blueFlash) {
add(ball);
add(ballTexture);
add(AiScore);
add(PlayerScore);
PlayerScore.setLabel(String.valueOf(PLAYER_SCORE));
PlayerScore.setLocation(3*WIDTH+10,getHeight()-10);
AiScore.setLabel(String.valueOf(AI_SCORE));
AiScore.setLocation(getWidth()-AiScore.getWidth()-3*WIDTH-10, getHeight()-10);
startX = rand.nextInt((int) (getWidth() * 0.8))
+ (int) (0.1 * getWidth()); // zapobiega pojawieniu się piłki po
// lewej stronie lewej paletki
startY = rand.nextInt(getHeight());
ball.setLocation(startX, startY);
image2.setLocation(getWidth() - 3 * WIDTH, startY - HEIGHT / 2);
paddleRight.setLocation(getWidth() - 3 * WIDTH, startY - HEIGHT / 2);
image2.sendToFront();
counter.setLabel(String.valueOf(COUNTER));
counter.setLocation(getWidth() / 2 - counter.getWidth() / 2,
getHeight() / 2 + counter.getHeight() / 3.2);
dx = SPEED * 1.5;
dy = SPEED;
while (true) {
ball.move(dx, dy);
ballTexture.setLocation(ball.getX(), ball.getY());
ballTexture.sendToFront();
if (TRANSPARENCY >= 0.0f)
TRANSPARENCY -= TRANSPARENCY / 100f;
labelC = new Color(0, 0.0f, 0.0f, TRANSPARENCY);
counter.setColor(labelC);
if (mouseY < getHeight() - HEIGHT) { // Player
paddleLeft.setLocation(2 * WIDTH, mouseY);
image.setLocation(2 * WIDTH, mouseY);
image.sendToFront();
} else {
paddleLeft.setLocation(2 * WIDTH, getHeight() - HEIGHT);
image.setLocation(2 * WIDTH, getHeight() - HEIGHT);
image.sendToFront();
}
// AI, z którym da się wygrać
/*
double targetY = ball.getY() + BALL_SIZE / 2;
if (targetY < getHeight() - HEIGHT / 2 && targetY > HEIGHT / 2) {
if (targetY < paddleRight.getY() + HEIGHT / 2) {
paddleRight.move(0, -AI_SPEED);
image2.move(0, -AI_SPEED);
} else if (targetY > paddleRight.getY() + HEIGHT / 2) {
paddleRight.move(0, AI_SPEED);
image2.move(0, AI_SPEED);
}
}
*/
// AI, z którym nie da się wygrać
// Zamiennie z kodem powyżej
// Jeden z algorytmów musi być w komentarzu: /* .: code :. */
if (ball.getY() < getHeight() - HEIGHT / 2
&& ball.getY() > HEIGHT / 2) { // AI
paddleRight.setLocation(getWidth() - 3 * WIDTH, ball.getY()
- HEIGHT / 2);
image2.setLocation(getWidth() - 3 * WIDTH, ball.getY() - HEIGHT
/ 2);
image2.sendToFront();
} else if (ball.getY() <= HEIGHT / 2) {
paddleRight.setLocation(getWidth() - 3 * WIDTH, 0);
image2.setLocation(getWidth() - 3 * WIDTH, -0);
image2.sendToFront();
} else {
paddleRight.setLocation(getWidth() - 3 * WIDTH, getHeight()
- HEIGHT);
image2.setLocation(getWidth() - 3 * WIDTH, getHeight() - HEIGHT);
image2.sendToFront();
}
if (ballHitBottom(ball) && dy >= 0) {
dy *= -1;
}
if (ballHitTop(ball) && dy <= 0) {
dy *= -1;
}
if (ballHitPaddleRight(ball, paddleRight)) {
dx *= -1;
}
if (ballHitPaddleLeft(ball, paddleLeft)) {
dx *= -1;
COUNTER++;
counter.setLabel(String.valueOf(COUNTER));
counter.setLocation(getWidth() / 2 - counter.getWidth() / 2,
getHeight() / 2 + counter.getHeight() / 3.2);
TRANSPARENCY = 0.1f;
labelC = new Color(0, 0.0f, 0.0f, TRANSPARENCY);
counter.setColor(labelC);
boolean bool = rand.nextBoolean();
if (bool)
if (dx > 0)
dx += 1;
else
dx -= 1;
else if (dy > 0)
dy += 0.5;
else
dy -= 0.5;
}
pause(PAUSE);
if (ballOffScreen(ball)) {
if (ball.getX() + SPEED * 2 < 0) { // left
double pos = ball.getY() - greenFlash.getHeight() / 2;
remove(ball);
remove(ballTexture);
AI_SCORE+=COUNTER;
AiScore.setLabel(String.valueOf(AI_SCORE));
AiScore.setLocation(getWidth()-AiScore.getWidth()-3*WIDTH-10, getHeight()-10);
for (int i = 20; i < 100; i += 5) {
greenFlash.setLocation(-i, pos);
pause(25);
}
} else { // right
double pos = ball.getY() - blueFlash.getHeight() / 2;
remove(ball);
remove(ballTexture);
PLAYER_SCORE+=COUNTER;
PlayerScore.setLabel(String.valueOf(PLAYER_SCORE));
PlayerScore.setLocation(10+3*WIDTH,getHeight()-10);
for (int i = 20; i < 100; i += 5) {
blueFlash.setLocation(getWidth() - blueFlash.getWidth()
+ i, pos);
pause(25);
}
}
COUNTER = 0;
bounce(labelC, AiScore, PlayerScore, counter, ball, paddleLeft,
paddleRight, image, image2, ballTexture, greenFlash,
blueFlash);
}
}
}
private boolean ballHitBottom(GOval ball) {
double bottomY = ball.getY() + ball.getHeight();
return bottomY >= getHeight();
}
private boolean ballHitTop(GOval ball) {
double topY = ball.getY();
return topY <= 0;
}
private boolean ballHitPaddleRight(GOval ball, GRect paddle) {
double rightX = ball.getX() + ball.getWidth();
double rightY = ball.getY() + ball.getHeight() / 2;
double paddlePosX = paddle.getX();
double paddlePosY = paddle.getY();
if (rightX > paddlePosX && rightY > paddlePosY
&& rightY < paddlePosY + paddle.getHeight())
return true;
else
return false;
}
private boolean ballOffScreen(GOval ball) {
if (ball.getX() + SPEED * 2 < 0
|| ball.getX() + ball.getWidth() - SPEED * 2 > getWidth())
return true;
else
return false;
}
private boolean ballHitPaddleLeft(GOval ball, GRect paddle) {
double leftX = ball.getX();
double leftY = ball.getY();
double paddlePosX = paddle.getX() + WIDTH;
double paddlePosY = paddle.getY();
if (leftX < paddlePosX && leftY > paddlePosY
&& leftY < paddlePosY + paddle.getHeight())
return true;
else
return false;
}
}
</code></pre>
| [] | [
{
"body": "<p>Glad to see you made it here.</p>\n\n<p>There is no predefined number of \"<em>this many arguments and no further</em>\" so it is a subjective decision. In my experience, I would say that as soon as you see more than 5 arguments you have to be pretty sure that that is a good way to go.</p>\n\n<p>A common approach here is to create a wrapper class that just holds these variables and which can subsequently be used to keep your method arguments clean, easily adaptable (adding another variable is a matter of adding it to your class) and it's also cleaner when you have to pass it to multiple methods.</p>\n\n<p>A sample of how this might look:</p>\n\n<pre><code>class GameParameters {\n public Color labelC;\n public GLabel playerScore;\n public GImage blueFlash;\n}\n</code></pre>\n\n<p>Note that I am using <code>public</code> variables so you don't have needless clutter of getters/setters. This class is just a wrapper to send values, nothing else.</p>\n\n<p>Some notes, perhaps?</p>\n\n<h1>Naming</h1>\n\n<p>In that same method you have the following parameter names:</p>\n\n<ul>\n<li>image</li>\n<li>image2</li>\n<li>AiScore</li>\n<li>PlayerScore</li>\n</ul>\n\n<p>The former two are rather unclear: what is the purpose of these two images? Naming a variable by its purpose will be a lot clearer than \"image\" and \"image2\".</p>\n\n<p>The latter two don't follow the <code>lowerCamelCase</code> convention style which (as you can see) meddles with syntax markup.</p>\n\n<p>Also in the category of meaningful names: <code>dx</code> and <code>dy</code> are seldom meaningful. Consider making them more descriptive.</p>\n\n<h1>Magic numbers</h1>\n\n<p>Take for example this snippet:</p>\n\n<pre><code>PlayerScore.setLocation(3*WIDTH+10,getHeight()-10);\n</code></pre>\n\n<p>What are <code>3</code> and <code>10</code>? <em>Magic numbers</em> are values which look like they're being put there randomly without any context as to what they mean. </p>\n\n<p>The solution to this is to put these values into variables which will make their intention clear:</p>\n\n<pre><code>int multiplier = 3;\nint padding = 10;\n\nPlayerScore.setLocation(multiplier * WIDTH + padding, getHeight() - padding);\n</code></pre>\n\n<p>This will also have the side-effect of making sure you don't accidentally type <code>10</code> and <code>100</code> since everything is stored in one place.</p>\n\n<h1>Spacing</h1>\n\n<p>Keep your spacing consistent! In a short timespan I see these three lines:</p>\n\n<pre><code>PlayerScore.setLocation(3*WIDTH+10,getHeight()-10);\nAiScore.setLocation(getWidth()-AiScore.getWidth()-3*WIDTH-10, getHeight()-10);\nimage2.setLocation(getWidth() - 3 * WIDTH, startY - HEIGHT / 2);\n</code></pre>\n\n<p>Ideally everything should be spaced out the way the last one is: spaces between the individual operators, none right before the comma, none right next to the parentheses.</p>\n\n<h1>Split up your code</h1>\n\n<p>Your <code>bounce()</code> method is very big and looks like it does more than one thing. Consider extracting your boundary checks into a different method to keep the overview.</p>\n\n<h1>Brackets & shortcuts</h1>\n\n<p>Consider this code:</p>\n\n<pre><code>if (ball.getX() + SPEED * 2 < 0\n || ball.getX() + ball.getWidth() - SPEED * 2 > getWidth())\n return true;\nelse\n return false;\n</code></pre>\n\n<p>Always add brackets (<code>{}</code>) to your <code>if</code> statements, it doesn't matter how short the body is. If you don't, you'll guaranteed end up with a logical error when you suddenly decide to add another line to the body.</p>\n\n<p>However, in this case you might as well write</p>\n\n<pre><code>return ball.getX() + SPEED * 2 < 0 || ball.getX() + ball.getWidth() - SPEED * 2 > getWidth();\n</code></pre>\n\n<p>Although you could, for clarity purposes, also store the two conditions into variables (my variable names are examples).</p>\n\n<pre><code>boolean ballIsFast = ball.getX() + SPEED * 2 < 0;\nboolean ballIsThick = ball.getX() + ball.getWidth() - SPEED * 2 > getWidth();\n\nreturn ballIsFast || ballIsThick;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:08:11.497",
"Id": "80863",
"Score": "1",
"body": "+1, but I actually tend to disagree with \"always add brackets to if statements\". It often makes for much cleaner code to use in-line `if`s when they're very short."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:09:59.913",
"Id": "80864",
"Score": "0",
"body": "Is there really a big enough difference between `if(true) { return \"yay\"; }` and `if(true) return \"yay\";` to justify omitting them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:11:32.537",
"Id": "80866",
"Score": "0",
"body": "Oh, you want to have the brackets on the same line as well? I assumed you meant bracket, new-line / tab, body, close bracket. Again personal taste, but I find same line brackets hideous and distracting. Haha"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:13:44.653",
"Id": "80867",
"Score": "0",
"body": "@JeroenVannevel For the first 6 months at college I only used structural C/C++. Objective Java is still new to me and I can't use classes well yet. AT first I tried to make a class `Ball`,`Paddle` and use those in `Pong`, but I failed, so I merged it into one class. If I understand this correctly, to use a wrapper class i would have to create new file `GameParameters.class`, then instance of `GameParameters gamepar = new GameParameters;` and then call the values like `gamepar.playerScore.setLabel(String.valueOf(COUNTER));` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:14:07.093",
"Id": "80868",
"Score": "0",
"body": "One-line statements are the only exception I make in Java to have both brackets on the same line ;) Opening bracket on the same line is common practice in Java so that's fine, but the closing bracket is only done when it's a oneliner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:16:15.123",
"Id": "80869",
"Score": "1",
"body": "@Asalas77: yes, that's pretty much exactly it. One remark though, an instance is created like this: `GameParameters gamepar = new GameParameters();` (notice the empty brackets to signify a parameterless constructor). You should indeed look into creating separate classes if you want to do it in OO style but OO isn't always the best solution either so perhaps there are better (easier) projects to learn OO in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:24:26.170",
"Id": "80873",
"Score": "0",
"body": "@JeroenVannevel I probably won't have neought time to change it, but I'll surely try to use classes more on further assignments. One more question, you mentioned using variables to store numbers with context, doesn't it increase the required memony unnecessarily? Also, related to the first one, should i create a variables to store getter values like `counter.getHeight()` provided that those are constant?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:28:16.873",
"Id": "80876",
"Score": "3",
"body": "No, you will never notice a difference in performance by storing a value in a variable. Definitely don't hold back on that. If the result from `getHeight()` is always the same then you could, but that's up to yourself. If you use it multiple times then it might be clearer to do so, it's definitely okay."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:16:47.730",
"Id": "80908",
"Score": "0",
"body": "@JeroenVannevel i reread your post couple times, and I'm halfway through cleaning up my code, but I noticed some more things I would need to know. How does using wrapping class affect my `bounce()` parameters? Even if I won't have them in `Pong` class, but separate one, would I still have to pass all of them when using `bounce()`? If not, how do I call the method your way?\n\nSecond question, regarding Magic Numbers section, shouldn't those be treated like constants and written in all upper case like `int PADDING = 10;` according to http://geosoft.no/development/javastyle.html?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:22:36.130",
"Id": "80916",
"Score": "1",
"body": "@Asalas77: it would simply change your method signature to `bounce(GameParameters params)` where you can now use those parameters as `params.playerScore`. When you need those parameters elsewhere, you just pass your `params` object to it. As to your second question: that would make sense, but I'm not sure if that's also appropriate when you're working with a local variable instead of an instance variable. I think both are correct for local variables (in a method), but you're right if you mean instance ones. Remember to declare them `private static final`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:30:29.013",
"Id": "80952",
"Score": "1",
"body": "+1 I would only add that sometimes domain-specific names are omay: in math and graphics, `dx` is commonly understood as delta-x. Short names make complicated formulas easier to read as long as there underlying meaning is clear to the reader. Anyone maintaining this code should have this basic understanding, so the chance of confusion is low."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:39:16.277",
"Id": "80953",
"Score": "0",
"body": "@DavidHarkness: that was indeed my one reservation which is why I added \"seldom\". If I remember my math classes then I believe there were indeed a few formulas that ended with `dx` but wasn't too sure of it. I appreciate the remark!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:09:13.723",
"Id": "80999",
"Score": "0",
"body": "@JeroenVannevel i made a follow-up post on this, would you mind to take a look? [link](http://codereview.stackexchange.com/questions/46363/cleaning-up-and-commenting-on-my-code-for-pong-game)"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:52:34.913",
"Id": "46315",
"ParentId": "46310",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "46315",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:30:58.480",
"Id": "46310",
"Score": "11",
"Tags": [
"java",
"game",
"animation"
],
"Title": "Simple Pong game"
} | 46310 |
<p>I have put together a small wrapper class to simplify creating parameterized ADODB queries with VB6/VBA. At this point I'm keeping things simple, so it's only supporting <em>input parameters</em> and from what I've tested it seems to work exactly as intended.</p>
<p>The main reason for writing this, is because creating SQL Injection -safe queries with ADODB involves creating an ADODB.Parameter for each parameter value, which can be combersome; to a beginner it's much easier to just concatenate the values into the command string.</p>
<p>The first thing I did was creating a "converter" class to take any value and spit out an ADODB.Parameter object - I called that class <code>AdoValueConverter</code>:</p>
<blockquote>
<p><strong>AdoValueConverter Class</strong></p>
</blockquote>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Public Function ToStringParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Dim stringValue As String
stringValue = CStr(value)
Dim result As New ADODB.Parameter
With result
.type = adVarChar
.direction = direction
.size = Len(stringValue)
.value = stringValue
End With
Set ToStringParameter = result
End Function
Public Function ToIntegerParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Dim integerValue As Long
integerValue = CLng(value)
Dim result As New ADODB.Parameter
With result
.type = adInteger
.direction = direction
.value = integerValue
End With
Set ToIntegerParameter = result
End Function
Public Function ToLongParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Set ToLongParameter = ToIntegerParameter(value, direction)
End Function
Public Function ToDoubleParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Dim doubleValue As Double
doubleValue = CDbl(value)
Dim result As New ADODB.Parameter
With result
.type = adDouble
.direction = direction
.value = doubleValue
End With
Set ToDoubleParameter = result
End Function
Public Function ToSingleParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Dim singleValue As Single
singleValue = CSng(value)
Dim result As New ADODB.Parameter
With result
.type = adSingle
.direction = direction
.value = singleValue
End With
Set ToSingleParameter = result
End Function
Public Function ToCurrencyParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Dim currencyValue As Currency
currencyValue = CCur(value)
Dim result As New ADODB.Parameter
With result
.type = adCurrency
.direction = direction
.value = currencyValue
End With
Set ToCurrencyParameter = result
End Function
Public Function ToBooleanParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Dim boolValue As Boolean
boolValue = CBool(value)
Dim result As New ADODB.Parameter
With result
.type = adBoolean
.direction = direction
.value = boolValue
End With
Set ToBooleanParameter = result
End Function
Public Function ToDateParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter
Dim dateValue As Date
dateValue = CDate(value)
Dim result As New ADODB.Parameter
With result
.type = adDate
.direction = direction
.value = dateValue
End With
Set ToDateParameter = result
End Function
</code></pre>
<p>Then I wrote the actual wrapper class, which I've called <code>SqlCommand</code>:</p>
<blockquote>
<p><strong>SqlCommand Class</strong></p>
</blockquote>
<pre class="lang-vb prettyprint-override"><code>Private converter As New AdoValueConverter
Option Explicit
Public Function Execute(connection As ADODB.connection, sql As String, ParamArray parameterValues()) As ADODB.Recordset
Dim cmd As New ADODB.Command
cmd.ActiveConnection = connection
cmd.CommandType = adCmdText
cmd.CommandText = sql
Dim i As Integer
Dim value As Variant
For i = LBound(parameterValues) To UBound(parameterValues)
value = parameterValues(i)
cmd.parameters.Append ToSqlInputParameter(value)
Next
Set Execute = cmd.Execute
End Function
Public Function SelectSingleValue(sql As String, ParamArray parameterValues()) As Variant
Dim connection As New ADODB.connection
connection.ConnectionString = Application.ConnectionString
connection.Open
Dim cmd As New ADODB.Command
cmd.ActiveConnection = connection
cmd.CommandType = adCmdText
cmd.CommandText = sql
Dim i As Integer
Dim value As Variant
For i = LBound(parameterValues) To UBound(parameterValues)
value = parameterValues(i)
cmd.parameters.Append ToSqlInputParameter(value)
Next
Dim rs As ADODB.Recordset
Set rs = cmd.Execute
Dim result As Variant
If Not rs.BOF And Not rs.EOF Then result = rs.Fields(0).value
rs.Close
Set rs = Nothing
connection.Close
Set connection = Nothing
SelectSingleValue = result
End Function
Public Function ExecuteNonQuery(connection As ADODB.connection, sql As String, ParamArray parameterValues()) As Boolean
Dim cmd As New ADODB.Command
cmd.ActiveConnection = connection
cmd.CommandType = adCmdText
cmd.CommandText = sql
Dim i As Integer
Dim value As Variant
For i = LBound(parameterValues) To UBound(parameterValues)
value = parameterValues(i)
cmd.parameters.Append ToSqlInputParameter(value)
Next
Dim result As Boolean
On Error Resume Next
cmd.Execute
result = (Err.Number = 0)
On Error GoTo 0
End Function
Private Function ToSqlInputParameter(ByVal value As Variant, Optional ByVal size As Integer, Optional ByVal precision As Integer) As ADODB.Parameter
Dim result As ADODB.Parameter
Set result = CallByName(converter, "To" & TypeName(value) & "Parameter", VbMethod, value, ADODB.ParameterDirectionEnum.adParamInput)
If size <> 0 Then result.size = size
If precision <> 0 Then result.precision = precision
Set ToSqlInputParameter = result
End Function
</code></pre>
<p>The <code>Execute</code> method returns a <code>ADODB.Recordset</code> object, and it's up to the client code to close it - the client code owns the connection being used.</p>
<p>The <code>ExecuteNonQuery</code> method returns a <code>Boolean</code> value indicating whether the command was executed successfully (that is, without throwing any errors) - again, the client code owns the connection being used.</p>
<p>The <code>SelectSingleValue</code> method returns a <code>Variant</code> value that represents the value of the first field of the first returned record, if anything is returned from the specified SQL statement.</p>
<hr />
<h3>Usage</h3>
<pre class="lang-vb prettyprint-override"><code>Dim cmd As New SqlCommand
Dim result As Variant
result = cmd.SelectSingleValue("SELECT SomeField FROM SomeTable WHERE SomeValue = ?", 123)
</code></pre>
<pre class="lang-vb prettyprint-override"><code>Dim cmd As New SqlCommand
Dim result As ADODB.Recordset
Dim conn As New ADODB.Connection
conn.ConnectionString = "connection string"
conn.Open
Set result = cmd.Execute(conn, "SELECT * FROM SomeTable WHERE SomeField = ?", 123)
'use result
result.Close
conn.Close
</code></pre>
<pre class="lang-vb prettyprint-override"><code>Dim cmd As New SqlCommand
Dim conn As New ADODB.Connection
Dim result As Boolean
conn.ConnectionString = "connection string"
conn.Open
result = cmd.ExecuteNonQuery(conn, "UPDATE SomeTable SET SomeField = ? WHERE SomeValue = ?", 123, "abc")
conn.Close
</code></pre>
<p>Although the <code>Precision</code> doesn't get set (I have yet to figure that one out) for <code>Double</code>, <code>Single</code> and <code>Currency</code> parameters, tests have shown that all decimals are being correctly passed to the server, so there's [surprisingly] no immediately apparent bug here.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-02T17:44:09.713",
"Id": "149233",
"Score": "0",
"body": "There is already a way to create parameterized queries in ADO.NET: http://support.microsoft.com/kb/200190"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-02T17:47:41.780",
"Id": "149235",
"Score": "3",
"body": "@GregBurghardt I know, this entire code *builds* on ADODB parameterized queries (BTW this is VBA, not .NET)... if you looked at how this code is used, you realize that it *generates the parameters for you*, so `SqlCommand.SelectSingleValue(\"SELECT SomeField FROM SomeTable WHERE SomeValue = ?\", 123)` is all you need to code to get a full-fledged parameterized query, without the hassle of creating the parameters yourself."
}
] | [
{
"body": "<p>This seems extra complexity with no purpose.</p>\n\n<p>You take any type variable and automatically convert it to a parameter (this is good).</p>\n\n<p>But then something strange happens, you look at the type of the variable and convert that to a string so you can call a function named after the type to do a standard set of options that only change based on the type.</p>\n\n<p>Why have all these functions -- you don't use them anywhere else in your design. Create a function that makes a parameter based on type -- this is what you are actually doing. </p>\n\n<pre><code>Public Function ToParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter\n\n Dim result As New ADODB.Parameter\n\n result.direction = direction\n\n Select TypeName(value)\n Case \"String\"\n result.type = adVarChar\n result.size = Len(CStr(value))\n result.value = CStr(value)\n Case \"Integer\"\n result.type = adInteger\n result.value = CLng(value)\n Case \"Double\"\n result.type = adDouble\n result.value = CDbl(value)\n End Select\n\n Set ToParameter = result\n\nEnd Function\n</code></pre>\n\n<p>If you feel the function is getting \"to long\", then make a helper function that sets direction, type and value on a new ADODB.Parameter and re-factor all those lines out.</p>\n\n<p>I'm fairly sure you don't need to cast \"value\" to the type as you do, you have already checked its type and you are not changing the type.</p>\n\n<p>Remember, unless there is a reason to do something <em>all the extra stuff is just extra stuff</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:08:49.417",
"Id": "80956",
"Score": "1",
"body": "+1 for the casting which is effectively redundant. However the functions specifically fulfill the purpose of replacing a `Select..Case` block like you're suggesting. Extracting that `AdoValueConverter` type also allows extending the type with further refinements, such as configurable type mappings; sometimes a `Byte` value will need to be passed as a `smallint`, other times as an `int` - converting a value to an `ADODB.Parameter` can become quite complex with tons of edge cases (how about a string that contains a GUID, do I pass it as a `String` or a `GUID`?), I find it's a concern of its own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:14:04.500",
"Id": "80957",
"Score": "0",
"body": "I see that they replace the Select but the \"dynamically named call\" is going to be slow so I don't see an advantage to replacing it in this way just a dis-advantage. To solve the edge case a cast will work there like `ToParameter(CByte(aParm),...` vs `ToParameter(CShort(aParm),...`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:24:55.757",
"Id": "80958",
"Score": "0",
"body": "Indeed, I just benchmarked adding 10000 items to a `Collection`, direct calls: 0-15 *ticks*, indirect calls: 16-94 *ticks*. With 100000 items I see a bigger difference: 47 *ticks* for direct calls vs 180 *ticks* for indirect calls. I think it's premature optimization to presume there's a massive performance hit with `CallByName`, the number of parameters of *any possible* query is way below anything that will make a significant difference in performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:38:11.730",
"Id": "80959",
"Score": "0",
"body": "Very good point, the performance effect is basically zero for all use cases."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:59:33.080",
"Id": "46346",
"ParentId": "46312",
"Score": "18"
}
},
{
"body": "<h3>AdoConverter</h3>\n\n<p>For better extensibility, the methods in that class shouldn't be calling each others the way <code>ToLongParameter</code> is calling <code>ToIntegerParameter</code>. Also instead of hard-coding the type</p>\n\n<pre><code>Private Type TypeMappings\n BooleanMap As ADODB.DataTypeEnum\n ByteMap As ADODB.DataTypeEnum\n CurrencyMap As ADODB.DataTypeEnum\n DateMap As ADODB.DataTypeEnum\n DoubleMap As ADODB.DataTypeEnum\n IntegerMap As ADODB.DataTypeEnum\n LongMap As ADODB.DataTypeEnum\n SingleMap As ADODB.DataTypeEnum\n StringMap As ADODB.DataTypeEnum\nEnd Type\n\nPrivate mappings As TypeMappings\nOption Explicit\n\nPrivate Sub Class_Initialize()\n\n mappings.BooleanMap = adBoolean\n mappings.ByteMap = adInteger\n mappings.CurrencyMap = adCurrency\n mappings.DateMap = adDate\n mappings.DoubleMap = adDouble\n mappings.IntegerMap = adInteger\n mappings.LongMap = adInteger\n mappings.SingleMap = adSingle\n mappings.StringMap = adVarChar\n\nEnd Sub\n</code></pre>\n\n<p>The class can then expose a <code>[Type]Mapping</code> property for each <code>[Type]Map</code> member of <code>mappings</code>, and then the client code can control the type of ADODB parameter getting created.</p>\n\n<pre><code>Public Function ToLongParameter(ByVal value As Variant, ByVal direction As ADODB.ParameterDirectionEnum) As ADODB.Parameter\n\n Dim longValue As Long\n longValue = CLng(value)\n\n Dim result As New ADODB.Parameter\n With result\n .type = mappings.LongMap ' mapped type is no longer hard-coded\n .direction = direction\n .value = longValue\n End With\n\n Set ToLongParameter = result\n\nEnd Function\n</code></pre>\n\n<h3>SqlCommand</h3>\n\n<p>Passing in a <code>Connection</code> is a great idea: it enables wrapping these database operations in a transaction. However the interface of <code>SqlCommand</code> isn't consistent about it: there's no reason why <code>SelectSingleValue</code> shouldn't be taking a <code>Connection</code> parameter as well. Doing that will enable reusing an existing connection instead of creating a new one every time, on top of improving usage consistency.</p>\n\n<p>Also each exposed method <em>creates a Command object</em>, and that code is duplicated every time. You could factor it into its own private factory method:</p>\n\n<pre><code>Private Function CreateCommand(connection As ADODB.connection, ByVal cmdType As ADODB.CommandTypeEnum, ByVal sql As String, parameterValues() As Variant) As ADODB.Command\n\n Dim cmd As New ADODB.Command\n cmd.ActiveConnection = connection\n cmd.CommandType = cmdType\n cmd.CommandText = sql\n\n Dim i As Integer\n Dim value As Variant\n\n If IsArrayInitialized(parameterValues) Then\n\n For i = LBound(parameterValues) To UBound(parameterValues)\n value = parameterValues(i)\n cmd.parameters.Append ToSqlInputParameter(value)\n Next\n\n End If\n\n Set CreateCommand = cmd\n\nEnd Function\n</code></pre>\n\n<p>This turns the <code>Execute</code> method into:</p>\n\n<pre><code>Public Function Execute(connection As ADODB.connection, ByVal sql As String, ParamArray parameterValues()) As ADODB.Recordset\n\n Dim values() As Variant\n values = parameterValues\n\n Dim cmd As ADODB.Command\n Set cmd = CreateCommand(connection, adCmdText, sql, values)\n\n Set Execute = cmd.Execute\n\nEnd Function\n</code></pre>\n\n<p>And then you could add an <code>ExecuteStoredProc</code> method just as easily, without duplicating all the command-creating code:</p>\n\n<pre><code>Public Function ExecuteStoredProc(connection As ADODB.connection, ByVal spName As String, ParamArray parameterValues()) As ADODB.Recordset\n\n Dim values() As Variant\n values = parameterValues\n\n Dim cmd As ADODB.Command\n Set cmd = CreateCommand(connection, adCmdStoredProc, spName, values)\n\n Set ExecuteStoredProc = cmd.Execute\n\nEnd Function\n</code></pre>\n\n<h3>Some Opportunities</h3>\n\n<p>This \"wrapper\" doesn't really abstract away the syntax for parameterized queries; if a value is needed twice, it needs to be specified twice; also the values must be specified in the same order they're replacing question marks.</p>\n\n<p>You could implement something similar to <a href=\"https://codereview.stackexchange.com/questions/30817/how-can-i-get-rid-of-select-case-and-goto-in-this-string-formatting-helper-fun\">this StringFormat code</a> (taking a bit of a performance hit though), and enable named parameters, and a formatting syntax that would allow specifying <code>Precision</code> and <code>Size</code> for any parameter, or even a specific mapping for a given parameter (say Integer parameter 1 is mapped to a <code>smallint</code> and Integer parameter 2 maps to an <code>int</code>, both in the same query), and one could specify parameters' direction, enabling support for <em>output parameters</em> (then you'd need a way to return the parameter values) - and the order of parameters could be specified as well.</p>\n\n<p>The flipside is that this would make a new syntax to learn, which somewhat defeats the purpose of making things simpler for inexperienced programmers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:52:09.770",
"Id": "46380",
"ParentId": "46312",
"Score": "12"
}
},
{
"body": "<p>I would opt for strict type checking here. It seems a bit lazy to force it to a single when implicit in the function name. No need to use a variant and force it to a Single via a cast. </p>\n\n<p>IMHO, if the function To<b>Single</b>Parameter is expecting a <b>Single</b>, then it should get a <b>Single</b> value and complain with a type mismatch error if it doesn't receive it. </p>\n\n<p>I've also added optional parameters for the Precision and the NumericScale with default values. The ToDoubleParameter, ToCurrencyParameter should also be modified as well.</p>\n\n<p>Keep in mind that Precision is the number of digits in a number. NumericScale is the number of digits to the right of the decimal point in a number. Where a number like 99999999.99 has a Precision of 10 and a NumericScale of 2.</p>\n\n<pre><code> Public Function ToSingleParameter( _\n ByVal value As Single, _\n ByVal direction As ADODB.ParameterDirectionEnum, _\n Optional ByVal Precision As Integer = 10, _\n Optional ByVal NumericScale As Integer = 2) As ADODB.Parameter\n\n Dim result As New ADODB.Parameter\n With result\n .Precision = Precision\n .NumericScale = NumericScale\n .type = adSingle\n .direction = direction\n .value = value \n End With\n\n Set ToSingleParameter = result\n End Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-02T19:33:34.270",
"Id": "149265",
"Score": "0",
"body": "Nice catch! Welcome to CR!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-02T17:31:02.937",
"Id": "83014",
"ParentId": "46312",
"Score": "11"
}
},
{
"body": "<p>You felt the need to go through great lengths in your post here to explain that the client code owns and is responsible for opening/closing connections and closing the returned recordsets, yet I see no comments mentioning this in the code. I would add some proper documentation for something you see as being this important. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-09T19:31:10.490",
"Id": "155821",
"Score": "0",
"body": "Could use method attributes for documentation, indeed..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-09T18:06:12.360",
"Id": "86429",
"ParentId": "46312",
"Score": "5"
}
},
{
"body": "<p>Waking this one up...</p>\n\n<h2>ExecuteNonQuery</h2>\n\n<h3>Return value never assigned</h3>\n\n<p><code>ExecuteNonQuery</code> never has its return value assigned.</p>\n\n<h3>Return value type</h3>\n\n<p>You have an opportunity here to return a richer value than a <code>Boolean</code>. Very often when executing a command, you're interested in the number of records affected. You can return the number of records affected, or -1 if there is an error.</p>\n\n<h3>Execution Options</h3>\n\n<p>You're not explicitly setting any <code>Options</code> on the <code>ADODB.Command.Execute</code>. As per <a href=\"https://msdn.microsoft.com/en-us/library/ms681559(v=vs.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>Use the ExecuteOptionEnum value adExecuteNoRecords to improve performance by minimizing internal processing.</p>\n</blockquote>\n\n<h3>Assigning ActiveConnection</h3>\n\n<p><code>ActiveConnection</code> is an object whose default property is <code>ConnectionString</code>. When assigning the <code>ActiveConnection</code> property, it is better practice to always use <code>Set</code>, although ADODB will manage things behind the scenes if you forget and just assign the <code>ConnectionString</code> property.</p>\n\n<pre><code>Public Function ExecuteNonQuery(connection As ADODB.connection, sql As String, ParamArray parameterValues()) As Long\n\n Dim cmd As New ADODB.Command\n Set cmd.ActiveConnection = connection\n cmd.CommandType = adCmdText\n cmd.CommandText = sql\n\n Dim i As Integer\n Dim value As Variant\n For i = LBound(parameterValues) To UBound(parameterValues)\n value = parameterValues(i)\n cmd.parameters.Append ToSqlInputParameter(value)\n Next\n\n Dim result As Long\n On Error Resume Next\n Dim recordsAffected As Long\n cmd.Execute recordsAffected, Options:=ExecuteOptionEnum.adExecuteNoRecords\n If Err.Number = 0 Then\n result = recordsAffected\n Else\n result = -1\n End If\n On Error GoTo 0\n ExecuteNonQuery = result\nEnd Function\n</code></pre>\n\n<h2>CreateCommand factory method</h2>\n\n<h3>Checking for valid ParamArray arguments</h3>\n\n<p>As per <a href=\"https://msdn.microsoft.com/en-us/library/office/gg251721.aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n\n<blockquote>\n <p>If <code>IsMissing</code> is used on a <code>ParamArray</code> argument, it always returns <code>False</code>. To detect an empty <code>ParamArray</code>, test to see if the array's upper bound is less than its lower bound.</p>\n</blockquote>\n\n<p>Despite the documentation above, <code>IsMissing</code> <em>does</em> actually seem to return <code>True</code> when the ParamArray argument is missing, but it's still safer to check the array bounds.</p>\n\n<p>You obviously have a private helper function in <code>IsArrayInitialized</code>, but it is not necessary - if the ParamArray variable is \"missing\", it <em>will</em> be an array, but its upperbound will be -1, and its lowerbound will be 0, so the <code>For</code> statement is sufficient.</p>\n\n<pre><code>Private Function CreateCommand(connection As ADODB.connection, ByVal cmdType As ADODB.CommandTypeEnum, ByVal sql As String, parameterValues() As Variant) As ADODB.Command\n\n Dim cmd As New ADODB.Command\n cmd.ActiveConnection = connection\n cmd.CommandType = cmdType\n cmd.CommandText = sql\n\n Dim i As Integer\n Dim value As Variant\n\n For i = LBound(parameterValues) To UBound(parameterValues)\n value = parameterValues(i)\n cmd.parameters.Append ToSqlInputParameter(value)\n Next\n\n Set CreateCommand = cmd\n\nEnd Function\n</code></pre>\n\n<p>Having said that, you're going through some variable gymnastics to pass a ParamArray argument to a <em>private</em> method. You can avoid that by declaring the helper function's <code>parameterValues</code> parameter as <code>ByVal parameterValues As Variant</code>, but then you <em>do</em> need to check that it is an array before enumerating it.</p>\n\n<pre><code>Private Function CreateCommand(connection As ADODB.connection, ByVal cmdType As ADODB.CommandTypeEnum, ByVal sql As String, ByVal parameterValues As Variant) As ADODB.Command\n\n Dim cmd As New ADODB.Command\n cmd.ActiveConnection = connection\n cmd.CommandType = cmdType\n cmd.CommandText = sql\n\n Dim i As Integer\n Dim value As Variant\n\n If IsArray(parameterValues) Then\n\n For i = LBound(parameterValues) To UBound(parameterValues)\n value = parameterValues(i)\n cmd.parameters.Append ToSqlInputParameter(value)\n Next\n\n End If\n\n Set CreateCommand = cmd\n\nEnd Function\n</code></pre>\n\n<p>Then, you can simplify a public method like <code>ExecuteStoredProc</code> to:</p>\n\n<pre><code>Public Function ExecuteStoredProc(connection As ADODB.connection, ByVal spName As String, ParamArray parameterValues()) As ADODB.Recordset\n\n Set ExecuteStoredProc = CreateCommand(connection, adCmdStoredProc, spName, values).Execute\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-06T03:01:57.243",
"Id": "151825",
"ParentId": "46312",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46346",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-04T18:44:11.750",
"Id": "46312",
"Score": "32",
"Tags": [
"sql-server",
"vba",
"sql-injection",
"vb6",
"adodb"
],
"Title": "Creating ADODB Parameters on the fly"
} | 46312 |
<p>I'm not a JavaScript programmer. I have next to no idea about "what's out there" of libraries and so on. Therefore it's not unlikely that the referred to Windows HTML Application (HTA) code here, which is a mix of HTML5, CSS3 and JScript 5.6, may be incompatible with such libraries, common naming conventions, whatever, and I would like to rectify the issues that the more JavaScript-experienced reader can spot.</p>
<p>Compatibility is important because this is intended as a host environment for simple JavaScript scripts, which may likely use common libraries etc.</p>
<p>This code consists of a number of logical modules encapsulated in a single .HTA file by design<sup>*</sup>.</p>
<p>Therefore, even though it's only about half-finished it's too large to present inline here, I think, at about 750 lines. And since I have no idea what the issues could be, I'm reluctant to pare it down to what <strong>I</strong> think can be relevant. I think would be bound to err there.</p>
<p>Code at <a href="http://pastebin.com/FW88DLS1" rel="nofollow noreferrer">http://pastebin.com/FW88DLS1</a>.</p>
<p>Oh, in order to make sense of the code it might help to see how the app looks:</p>
<p><img src="https://i.stack.imgur.com/nkS5V.png" alt="enter image description here"></p>
<hr>
<p>As per request in comments I tried to post the full code inline here, but there was a limitation of 30.000 characters, while the code is some 36.000 characters.</p>
<p>Here's the CSS part (first part of the code):</p>
<pre><code><html>
<!-- Windows HTA application "Text Stream Host". Copyright (©) 2014 Alf P. Steinbach -->
<head id="head-element">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="MSThemeCompatible" content="yes">
<title id="title-element"></title>
<style>
* { font: 10pt 'MS Shell Dlg 2'; }
code { font: 10pt 'Courier new'; }
body {
padding: 0; margin: 0; overflow: hidden;
background-color: #F0F0F0;
}
#text-stream-display p { margin: 0; padding: 0; color: #000080; }
#control-area {
padding-top: 0; padding-left: 0; padding-right: 0.5em; padding-bottom: 0;
overflow: none;
margin: 0;
position: absolute;
left: 0; top: 0;
/*background-color: #FF0000;*/
width: 30em; height: 2em; left: -14em; top: +14em;
transform: rotate(-90deg);
}
#info-area {
background-color: white;
overflow: none;
position: absolute;
left: 2.5em; top: 0; right: 0; bottom: 0px;
}
#commandline-display {
color: gray;
overflow: auto;
white-space: nowrap;
padding: 0.5em;
border-bottom: 1px solid gray;
margin-bottom: 0.5em;
position: absolute; left: 0; top: 0; right: 0;
height: 7em;
}
.command-line { background-color: #F0FFF0; }
#text-stream-display {
overflow: auto;
white-space: nowrap;
padding: 0.5em;
position: absolute;
left: 0; top: 0px; right: 0; bottom: 0px;
}
.checkbox-div {
border: 1px black solid;
border-radius: 5px;
padding-bottom: 0.2em; margin-bottom: 0.1em;
padding-right: 0.5em;
display: inline-block;
cursor: pointer;
}
.checkbox-div:hover {
background: #D0E0FF;
}
</style>
</code></pre>
<p>Here's the first logical JavaScript module (following right after the above in the full code):</p>
<pre><code> <!-- Namespace js_util
JavaScript utilities -->
<script type="text/javascript">
js_util = new function()
{
this.is_whitespace_character = function( ch )
{
return (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t');
};
this.is_whitespace = function( s )
{
with( this )
{
var n = s.length;
for( var i = 0; i < n; ++i )
{
if( !is_whitespace_character( s.substr( i, 1 ) ) )
{
return false;
}
}
}
return true;
};
this.hex_digits = '0123456789ABCDEF';
this.hex_from_int = function( number, n_digits )
{
if( n_digits == undefined ) { n_digits = 8; }
var digits = new Array();
for( var i = 1; i <= n_digits; ++i )
{
digits.push( number & 0xF );
number >>>= 4;
}
var result = '';
for( var i = n_digits - 1; i >= 0; --i )
{
result += this.hex_digits.substr( digits[i], 1 );
}
return result;
}
this.add_class = function( html_elem, classname )
{
var classname_set = html_elem.classList;
if( !classname_set.contains( classname ) )
{
classname_set.toggle( classname );
return true;
}
return false;
}
this.unquoted = function( s )
{
var quote = '"';
var n = s.length;
if( n <= 1 )
{
return s;
}
if( s.substr( 0, 1 ) == quote && s.substr( n - 1, 1 ) == quote )
{
return s.substring( 1, n - 1 );
}
return s;
}
this.local_file_url = function( filespec )
{
with( this )
{
var url = 'file:///' + unquoted( filespec ).replace( /\\/g, '/' );
return url;
}
}
};
</script>
</code></pre>
<p>Here's the second JavaScript module:</p>
<pre><code> <!-- Namespace windows.wsh
Windows Script Host (shell functionality only). -->
<script type="text/javascript">
var windows = windows || {};
windows.wsh = new function()
{
this.shell = new ActiveXObject( 'WScript.Shell' );
this.sleep = function( millisecs )
{
with( this )
{
var nowindow = 0;
var wait = true;
shell.Run( 'ping 1.1.1.1 -n 1 -w ' + millisecs, nowindow, wait );
}
};
this.is_running = function( wsh_execution )
{
return (wsh_execution.Status == 0);
};
this.run_hidden = function( command )
{
var hidden_window = 0;
var wait_for_completion = true;
with( this )
{
return shell.Run( command, hidden_window, wait_for_completion );
}
}
};
</script>
</code></pre>
<p>Here's the third JavaScript module:</p>
<pre><code> <!-- Namespace windows.fs
File System Object (part of Window's script support). -->
<script type="text/javascript">
var windows = windows || {};
windows.fs = new function()
{
this.fso = new ActiveXObject( "Scripting.FileSystemObject" );
this.tempfolder = this.fso.GetSpecialFolder( 2 );
this.tempfolder_path = this.tempfolder.Path;
this.open_for_reading = function( textfile_spec )
{
var for_reading = 1;
var do_not_create = false;
var ascii_encoding = 0;
var utf16_encoding = -1;
var default_encoding = -2;
with( this )
{
return fso.OpenTextFile(
textfile_spec,
for_reading, do_not_create, default_encoding
);
}
}
this.joined_paths = function( folder_path, filename )
{
with( this ) return fso.BuildPath( folder_path, filename );
}
this.temp_filename = function()
{
with( this ) return fso.GetTempName();
}
this.temp_filepath = function()
{
with( this ) return joined_paths( tempfolder_path, temp_filename() );
}
this.quoted = function( path )
{
var quote = '"';
var is_quoted = (path.length > 0 && path.substr( 0, 1 ) == quote);
return (is_quoted? path : quote + path + quote);
}
};
</script>
</code></pre>
<p>Here's the fourth JavaScript module:</p>
<pre><code> <!-- Namespace windows.process_info
Windows process information. -->
<script type="text/javascript">
var windows = windows || {};
windows.process_info = new function()
{
var pg = {}; // "private globals" namespace, to make that explicit.
pg.Record = function()
{
this._add_item = function( spec )
{
i_delimiter = spec.indexOf( '=' );
if( i_delimiter != -1 )
{
var property_name = spec.substring( 0, i_delimiter );
var value = spec.substr( i_delimiter + 1 );
this[property_name] = value;
}
}
};
this.new_records = function()
{
var filepath = windows.fs.temp_filepath();
var exitcode = windows.wsh.run_hidden(
'cmd /c wmic process list full >' + windows.fs.quoted( filepath )
);
if( exitcode != 0 )
{
return null; // TODO: exception
}
var records = new Array();
var current_record = null;
var f = windows.fs.open_for_reading( filepath );
while( !f.AtEndOfStream )
{
var line = f.ReadLine();
var i_end = line.length - 1;
while( i_end >= 0 && line.substr( i_end, 1 ) < ' ' )
{
--i_end;
}
if( 0 <= i_end && i_end < line.length - 1 )
{
line = line.substr( 0, i_end + 1 );
}
if( js_util.is_whitespace( line ) )
{
if( current_record != null )
{
records.push( current_record );
current_record = null;
}
}
else // line.length > 0
{
if( current_record == null )
{
current_record = new pg.Record();
}
current_record._add_item( line );
}
}
// Complete a possible last record.
if( current_record != null )
{
records.push( current_record );
}
f.Close();
windows.fs.fso.DeleteFile( filepath );
return records;
};
};
</script>
</code></pre>
<p>When I try to post the fifth and main JavaScript module, I get an error about exceeding the max length. So that module plus the main HTML body is missing here. <strong><a href="http://pastebin.com/FW88DLS1" rel="nofollow noreferrer">Consult the PasteBin posting for a complete version that can be tried out</a></strong> – which I believe is a practical necessity for gaining a good understanding of code.</p>
<p><hr>
<sup><sup>*</sup>Single file: the idea is to provide a simple text only i/o host environment for learning programming, where one simply drags the javascript source onto the HTA file. And for beginners I think it's decidedly an advantage to have the host environment as a single file, with no special installation issues etc.</sup></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:21:17.173",
"Id": "80871",
"Score": "0",
"body": "Have you considered jsbin.com, or jsfiddle.net, or plnkr.co instead of writing your own environment?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:24:57.587",
"Id": "80875",
"Score": "0",
"body": "@konijn: Thanks for those references. Are they local execution environments? Needs to be local."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:28:55.117",
"Id": "80877",
"Score": "0",
"body": "No, why do they need to be local?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:29:32.880",
"Id": "80879",
"Score": "0",
"body": "@konijn: usually that's because of connectivity issues. for corporate work there's also security aspects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T05:36:18.290",
"Id": "80979",
"Score": "0",
"body": "@AlfP.Steinbach jsbin is open source https://github.com/jsbin/jsbin/ so is plnkr https://github.com/filearts/plunker"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:14:33.653",
"Id": "81456",
"Score": "0",
"body": "I'm amazed that someone disliked the *question* enough to downvote. Oh well. Humanity."
}
] | [
{
"body": "<p>A few things immediately caught my eye:</p>\n\n<ul>\n<li><p>You're using a weird construct: <code>new function() {}</code>. The <code>function(){}</code> expression already creates a new function, but in addition to that you're using it with <code>new</code> to invoke it as a constructor for new object. The way you're using it, you could easily replace it with just plain object literal. For example in <code>js_util</code>:</p>\n\n<pre><code>js_util = {\n isWhitespaceCharacter: function(ch) {\n return (ch == ' ' || ch == '\\n' || ch == '\\r' || ch == '\\t');\n },\n ...\n};\n</code></pre>\n\n<p>But you really need to familiarize yourself with JavaScript's prototypal object model. Otherwise you're just programming by coincidence - without really knowing what the code does.</p></li>\n<li><p>Don't use the <code>with</code> statement. It makes code hard to read and reason about. It's one of the grand mistakes in JavaScript language. Avoid it. In your case, just prefix the instance variables/functions with <code>this.</code> - it's not so long to write.</p></li>\n<li><p>It's very unusual to place the opening <code>{</code> on a separate line in JavaScript. This kind of indentation style is rarely seen. I suggest you adopt the common style of placing <code>{</code> on the same line as <code>if</code> etc.</p></li>\n<li><p>The common variable naming convention in JavaScript is to use <code>camelCase</code> not <code>under_scores</code>.</p></li>\n<li><p>Your <code>is_whitespace</code> function could be much more easily implemented with just a simple regular expression:</p>\n\n<pre><code>isWhitespace: function(s) {\n return /^\\s*$/.test(s);\n}\n</code></pre></li>\n</ul>\n\n<p>And don't take my word for it. Run your JavaScript through an analyzer like <a href=\"http://www.jshint.com/\">JSHint</a> - it will warn you about these and other issues.</p>\n\n<p><strong>PS.</strong> I think overall your code is very nicely and cleanly written. It just falls short on looking and feeling like JavaScript.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:30:38.217",
"Id": "80920",
"Score": "0",
"body": "Thanks for the comments and link to JSHint (all new to me). Re `new function()`, I use that intentionally to create a logical namespace, which is a single object -- no need for prototype. I avoided the object literal notation for three reasons, mostly emotional: (1) the commas instead of semicolons, (2) the thought of n-hundred lines long literal (even if the same could be said for the function body), and (3) that, having been away from Javascript for 10 or more years I'm unsure if the functions introduced in a literal can refer to each other or to other data items there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:20:15.910",
"Id": "81300",
"Score": "0",
"body": "under_scores is called snake_case afaik ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:06:13.823",
"Id": "46326",
"ParentId": "46313",
"Score": "5"
}
},
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>Please use lowerCamelCase -> <code>is_whitespace_character</code> -> <code>isWhiteSpaceCharacter</code>, that is the standard for JavaScript</li>\n<li>Considering <code>\\n</code> and <code>r</code> as whitespace characters while technically legit seems old skool</li>\n<li>It does not make sense to have a function to detect white space in a string, and a function to detect a single white space character, it should be 1 function. A character is a string of length 1 after all</li>\n<li>Consider replacing <code>s.substr( i, 1 )</code> with <code>s[i]</code>, it is more succinct</li>\n<li>Consider using better variables, anything outside of Spartan convention ( i(nteger), s(tring), o(bject), e(vent), c(har) ) should have a proper name. So <code>var n = s.length</code> is no good</li>\n<li>Do not use <code>with</code> in JavaScript, most developers will not know how it works, and most developers create hard to solve bugs with <code>with</code></li>\n<li>I think there are succinct regex expression to check for a string being whitespace</li>\n<li>Consider using <code>.toString(16)</code> in <code>hex_from_int</code>, it will cut 90% of that function</li>\n<li>In <code>local_file_url</code>, it does not make sense to create a <code>var</code> and then <code>return</code> that variable on the next line, you should <code>return</code> immediately</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:23:58.570",
"Id": "81301",
"Score": "0",
"body": "Thanks for you comments. Regarding formatting conventions, I hear. THanks. Regarding e.g. `\\r` as whitespace being \"old skool\", well if correctness is old skool then that's my thing. The code would not work correctly with a more limited whitespace notion. Re the whitespace-for-character and whitespace-for-general string, that makes eminent sense: it's far better to have separate functions than a single function that delegates to two different internal implementations (there's no point in such delegation). However, when implement as a regex there's no such consideration, but also less control."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:29:32.503",
"Id": "81303",
"Score": "0",
"body": "Re string indexing, thanks, I don't know where I got the idea that JavaScript didn't support it. Of course it does. Re spartan variable names, no it's not a good idea to give e.g. a loop control variable a more descriptive name than `i`. Re \"most developers will not know how [the `with` statement]` works\", I have tried, many years ago, to code and design for the lowest common denominator of programmers, due to earlier arguments from those below the median. And in my experience that's not only futile but directly counter-productive, so, don't do as I did. But sure, general use of `with` = Evil."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:33:08.053",
"Id": "81304",
"Score": "0",
"body": "Re `.toString(16)` for hex representation, I did consider it, and no it does not cut 90% of that function. In particular you need to handle negative numbers correctly. Re \"create a `var` and then `return` that variable on the next line\" as meaningless, yes it might look that way. That's a debugging hook. It was used and left as-was. ;-) IME that generally avoids doing the same work repeatedly. So, I beg to differ eith the \"you should `return` immediately\". But all in all, thanks a bunch for the observations and advice. Very through. Thanks. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:36:47.123",
"Id": "81306",
"Score": "0",
"body": "Re: `.toString(16)`, it does handle negative numbers. Also there is no need to create a `var` as a debugging hook ? You can simply put the breakpoint on the `return` statement and evaluate what you are about to return ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:42:43.050",
"Id": "81307",
"Score": "0",
"body": "I found that .toString(16) handles negative numbers by adding a minus sign in front. In contrast, the desired hex representation (for this code at least) is hex representation of the bitpattern. After all that's the point of hex. Re \"simply put a breakpoint\", I wasn't debugging with a debugger. ;-) I guess I have a lot to learn about JavaScript debugging, but what I found was that Microsoft has discontinued their old JScript debugger, and replaced with something in Office, and that even though the HTA code is executed by the IE engine I was unable to use IE debugging facilities. But, learning."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:15:24.143",
"Id": "46544",
"ParentId": "46313",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:47:18.257",
"Id": "46313",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"css",
"html5",
"windows"
],
"Title": "What are practical issues using this code with common JavaScript libraries?"
} | 46313 |
<p>I have a bunch of functions that return strings based upon score ranges. Then I have another function that sums everything up and assigns a numeric weight.</p>
<pre><code>@property
def risk_status(self):
""" This function assigns numeric weight to risks. It returns an over all integer score. """
# Build a string of risks, ie "High Risk@At Risk@@Extreme Risk"
raw_string_of_risks = self.si_risk + '@' + self.aggbs_risk + '@' + self.cfimb_risk + '@' + self.cfiab_risk + '@' + self.cei_risk
# Build a list ["High Risk", "At Risk", "Extreme Risk"]
risks = raw_string_of_risks.split('@')
# Formula for over all risk status. ["High Risk", "At Risk", "Extreme Risk"] => 2+1+3 = 6
status = risks.count("At Risk")*1 + risks.count("High Risk")*2 + risks.count("Extreme Risk")*3
return status
</code></pre>
<p>I'm afraid with a gazillion records this property might slow things down. It will never get a string longer than 65 characters to parse, but will doing this over and over again really slow things down?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:48:41.393",
"Id": "80905",
"Score": "1",
"body": "I don't know if it will speed things up a lot, but instead of building your raw_string_of_risks and then breaking it into a list, why don't you just create the list ... `risks = [self.si_risk, self.aggbs_risk, ...]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:26:56.100",
"Id": "81392",
"Score": "0",
"body": "That is much better! Slapping my forehead!"
}
] | [
{
"body": "<p>Concatenating an splitting seems like you're making extra work for yourself. I suggest summing the results of a string-to-integer translation.</p>\n\n<pre><code>from collections import defaultdict\n\n_RISK_SCORE = defaultdict(int, [('Extreme Risk', 3), ('High Risk', 2), ('At Risk', 1)])\n\n@property\ndef risk_status(self):\n \"\"\" This function assigns numeric weight to risks. It returns an overall integer score. \"\"\"\n return sum(self._RISK_SCORE[r] for r in (\n self.si_risk,\n self.aggbs_risk,\n self.cfimb_risk,\n self.cfiab_risk,\n self.cei_risk,\n ))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T07:49:21.670",
"Id": "81885",
"Score": "0",
"body": "Why defaultdict? It will mask any typos."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T07:53:56.353",
"Id": "81886",
"Score": "0",
"body": "@Suor The author never explicitly stated that `self.si_risk` etc. would only take on those three string values. This code, with `defaultdict`, most closely mimics the behaviour of the original code, which also masks typos."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T06:10:35.117",
"Id": "46358",
"ParentId": "46314",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46358",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:48:40.660",
"Id": "46314",
"Score": "4",
"Tags": [
"python",
"performance",
"django"
],
"Title": "Code efficiency with many records"
} | 46314 |
<p>I have <code>Article</code> and <code>Category</code>, with a <code>has_and_belongs_to_many</code> relation between the two.</p>
<p>I want to use <code>Article.in_categories(category_ids)</code> to get any <code>Article</code> that is in any of the <code>category_ids</code> passed, and I want to handle the possibility of <code>category_ids</code> being <code>nil</code> in a way that all <code>Article</code> items are returned. The <code>category_ids</code> value is coming from a form, and I want the user to be able to ignore the <code>Category</code> selection part of the form if they do not want to limit their selection by that criteria.</p>
<p>I currently have this in place on the <code>Article</code> model:</p>
<pre><code>def self.in_categories(category_ids = nil)
category_ids.blank? ? all : includes(:categories).where(categories: { id: category_ids })
end
</code></pre>
<p>If I do not have the check for <code>category_ids</code> being <code>nil</code>, then it will only return the <code>Article</code> items that are not in any <code>Category</code>.</p>
<p>I do not want to manually set <code>category_ids = [1,2,3]</code> (for example) in the method call, because a <code>Category</code> can be added/removed.</p>
<p>Is there a better way of handling this than the way I already do?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:28:46.983",
"Id": "81071",
"Score": "1",
"body": "Not quite an answer, so I'll comment instead: I'd suggest handling possible `nil` values elsewhere, and simply not call `in_categories` unless you have some IDs and it makes sense to do so. Right now, `in_categories` is basically a sometimes-alias for `all`, which smells weird to me. I'd expect it always filter the article records somehow, given its name."
}
] | [
{
"body": "<p>Generally you'll want to make sure this always gets passed an array so I'd choose to set the argument to an empty array rather than nil. Since in the successful case the method receives an array, you should treat it as such. If you ever expect to get a nil passed in (like you might from params), you can also catch if it is blank or empty to handle all cases safely.</p>\n\n<p>If you get rid of the ternary, you can simply put a guard as the first line and that clarifies the method a lot more. You'll see the use of guards throughout the Rails source itself.</p>\n\n<pre><code>def self.in_categories(category_ids=[])\n return all if category_ids.blank? || category_ids.empty?\n includes(:categories).where(categories: { id: category_ids })\nend\n</code></pre>\n\n<p>Alternatively you could always cast the parameter to an array and only handle that case.</p>\n\n<pre><code>def self.in_categories(category_ids=nil)\n category_ids = category_ids.to_a\n return all if category_ids.empty?\n includes(:categories).where(categories: { id: category_ids })\nend\n</code></pre>\n\n<p>I've run into this \"undocumented feature\" on several occasions with Rails and it trips me up every time. Hopefully someone has a better solution so that Rails, but it is also good to just be explicit on the results if you can't consolidate.</p>\n\n<p>Looks like there are quite a few discussions about this <a href=\"https://github.com/rails/arel/pull/245\" rel=\"nofollow\">https://github.com/rails/arel/pull/245</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:39:49.717",
"Id": "46385",
"ParentId": "46319",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:57:29.127",
"Id": "46319",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Searching has_and_belongs_to_many relations for article categories"
} | 46319 |
<h2>Problem Statement</h2>
<blockquote>
<p>Given \$n\$ digits and \$m\$ indices \$x\$ from \$1. \ldots,n\$, calculate the
difference \$b_y = a_x - a_y\$ for all indices \$y \; (y < x)\$. Then, calculate \$B1\$,
the sum of all \$b_y\$ which are greater than \$0\$ and \$B2\$,
the sum of all \$b_y\$ which are less than \$0\$. The answer for this step is \$B1 - B2\$.</p>
<p><strong>Input</strong></p>
<p>The first line contains two integers \$n, m\$ denoting the number of
digits and number of steps. The second line contains \$n\$ digits (without
spaces) \$a_1, a_2, ..., a_n\$. Each of next \$m\$ lines contains single integer
\$x\$ denoting the index for current step.
<sub>(<a href="http://www.codechef.com/APRIL14/problems/ADIGIT" rel="nofollow">ADIGIT: Chef and Digits</a> from CodeChef)</sub></p>
</blockquote>
<h2>My Issue</h2>
<p>I've tried quite hard to optimize the following solution, but online judge always shows Time Limit Exceeded.</p>
<h2>My Question</h2>
<p>Is it possible to optimize this code further to bring time down less than 1 second, or should I change my approach or perhaps shift to C?</p>
<pre><code>import sys
final=[]
z,y=[int(x) for x in sys.stdin.readline().split()]
stra=sys.stdin.readline()
for i in xrange(y):
b1=b2=0
curr=int(input())-1
for x in stra[:curr]:
mu=int(stra[curr])-int(x)
if(mu>0):
b1+=mu
else:
b2+=mu
final.append(str(b1-b2))
print("\n".join(final))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:40:56.473",
"Id": "80904",
"Score": "0",
"body": "Don't know if it will speed it up much, but put the int(stra[curr]) before the inner for loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-27T10:15:31.623",
"Id": "111053",
"Score": "0",
"body": "Did you master the problem?"
}
] | [
{
"body": "<p>A better algorithm usually wins over micro-optimizations.</p>\n\n<ul>\n<li><p>Do you really need to do all these calculations every time? Maybe you could cache them and re-use the results.</p></li>\n<li><p>You could perform all the string to int conversions up front, afterwards only looking up numbers from array.</p></li>\n<li><p>This whole <code>b1</code> & <code>b2</code> thing could be replaced with simple <code>abs()</code> function call. Not sure if it would speed things up, but it sure would simplify the code.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:29:02.050",
"Id": "46324",
"ParentId": "46320",
"Score": "7"
}
},
{
"body": "<p>This would avoid looping <strong>m</strong> times through the string:</p>\n\n<ol>\n<li>Sort a copy of the list of indices <strong>x</strong> given in the input.</li>\n<li>Sweep through the string, counting the occurrences of each digit as you go along. Each time you hit one of the <strong>x</strong>, compute the answer from the current counts. Put the answer in a dict indexed by <strong>x</strong>.</li>\n<li>Output the answers in correct order by looping through the original list and looking up the value in the dict.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:56:26.443",
"Id": "46579",
"ParentId": "46320",
"Score": "5"
}
},
{
"body": "<h2>Issues with your code</h2>\n\n<p>You didn't put any effort into <strong>choosing good names</strong>. Given a code challenge, either stick to the variable names used in the problem statement (<code>n, m</code>, ...) or, preferably, choose explicit and descriptive names such as <code>steps</code>, <code>digits</code> and <code>indices</code> rather than <code>z</code>, <code>y</code>, etc.</p>\n\n<p>Why should you bother with this? Because good names reveal <em>intent</em>, and knowing what the code is supposed to do makes it possible for you and others to understand and improve it easily.</p>\n\n<hr>\n\n<p>Your <strong>algorithm</strong> uses a naive, brute-force approach. This is fine as a starting point!<br>\nBut when you get a <em>time limit exceeded</em> message, you need to think about smarter solutions. </p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/46324/9390\">Rene's answer</a> gives you some good advice: He suggests that you employ <em>caching</em>, separate I/O from the calculation, and <em>add up all the absolute values of <code>by</code></em>, thus skipping the calculation of <code>B1</code> and <code>B2</code>. This is a good start but you can go much further. </li>\n<li><a href=\"https://codereview.stackexchange.com/a/46579/9390\">Janne's answer</a> tells you the essence of what's wrong with your algorithm: you need to <em>avoid looping over the previous digits for every step</em>. Why? Because there will be up to <strong>10<sup>5</sup> (one hundred thousand) digits</strong> and up to <strong>10<sup>5</sup> steps</strong>. However, it is unnecessary to make a sorted copy of the <code>indices</code> — see below.</li>\n</ul>\n\n<h1>How?</h1>\n\n<p>Start by <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\"><strong>separating your concerns</strong></a>. Python has functions, so use them to group relevant parts of your code together, while keeping different levels of abstraction separate. Start at the most general level:</p>\n\n<pre><code>def main():\n print(*solve(sys.stdin), sep='\\n')\n</code></pre>\n\n<p>We are saying: <em>print</em> each line of the result of <em>solving</em> the problem with the input from <code>sys.stdin</code>.<br>\nOur next concern is to parse the input:</p>\n\n<pre><code>def solve(lines):\n _, digits, *indices = lines\n return calculate_answer(as_ints(digits.rstrip()), as_ints(indices))\n</code></pre>\n\n<p>We discard the first line <code>_</code> because we can deduce the length of the digits and the number of steps from the rest of the input, so there is no need to waste cycles parsing them. We then store the <code>digits</code> which are given in the second line, as well as the <code>indices</code> from the following lines.</p>\n\n<p>To get rid of the redundancies in your integer-conversion code, we extract a function:</p>\n\n<pre><code>def as_ints(iterable):\n return [int(x) for x in iterable]\n</code></pre>\n\n<p>We can pass the <code>digits</code> (stripping the newline character at the end) and the <code>indices</code> to this function to obtain usable values which we can use to <code>calculate_answer(digits, indices)</code>. Since we have already parsed the input, this function can be focused on our algorithm to solve the problem. </p>\n\n<pre><code>def calculate_answer(digits, indices):\n</code></pre>\n\n<ol>\n<li><p><strong>Store the indices in a dictionary</strong>, which allows them to be looked up in constant time. </p>\n\n<pre><code>result = dict.fromkeys(indices)\n</code></pre></li>\n<li><p>Set up another dictionary to count the <strong>number of occurrences of each unique digit</strong>, which will help us avoid iterating over all previous digits on every step.</p>\n\n<pre><code>counts = defaultdict(int)\n</code></pre></li>\n<li><p>Iterate over the <code>digits</code> and keep track of each digit's <code>index</code>, starting with <code>1</code></p>\n\n<pre><code>for index, digit in enumerate(digits, start=1):\n</code></pre></li>\n<li><p>If the current <code>index</code> is in <code>result</code> and we have not calculated a value for it yet:<br>\nAssign to the current <code>index</code> the sum of all the absolute values of the differences between the current <code>digit</code> and each unique previous digit <code>d</code> multiplied by its occurrences <code>n</code>.</p>\n\n<pre><code> if index in result and result[index] is None:\n result[index] = sum(n * abs(digit - d) for d, n in counts.items())\n</code></pre></li>\n<li><p>Increment the number of occurrences of the digit we just encountered:</p>\n\n<pre><code> counts[digit] += 1\n</code></pre></li>\n<li><p>In the order of the given indices, retrieve each calculated value from <code>result</code>.</p>\n\n<pre><code>return (result[i] for i in indices)\n</code></pre></li>\n</ol>\n\n<h1>Result</h1>\n\n<p>The end result is fast enough to be accepted by CodeChef. As you didn't specify a language version, this is in Python 3, which you should use as well. If you insist on sticking with Python 2.x, you will need to make the necessary adjustments.</p>\n\n<pre><code>import sys\nfrom collections import defaultdict\n\n\ndef main():\n print(*solve(sys.stdin), sep='\\n')\n\n\ndef solve(lines):\n _, digits, *indices = lines\n return calculate_answer(as_ints(digits.rstrip()), as_ints(indices))\n\n\ndef calculate_answer(digits, indices):\n result = dict.fromkeys(indices)\n counts = defaultdict(int)\n for index, digit in enumerate(digits, start=1):\n if index in result and result[index] is None:\n result[index] = sum(n * abs(digit - d) for d, n in counts.items())\n counts[digit] += 1\n return (result[i] for i in indices)\n\n\ndef as_ints(iterable):\n return [int(x) for x in iterable]\n\n\nif __name__ == '__main__':\n main() \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T05:16:49.520",
"Id": "46781",
"ParentId": "46320",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "46781",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:10:25.147",
"Id": "46320",
"Score": "10",
"Tags": [
"python",
"optimization",
"performance",
"programming-challenge"
],
"Title": "How can I make my solution for Chef and Digits run faster?"
} | 46320 |
<p>After taking some great advice on <a href="https://codereview.stackexchange.com/questions/46293/quadratic-expression-calculator">this question</a>, I'm hoping for some more feedback on my quadratic expression calculator.</p>
<p>This is my code as stands:</p>
<pre><code>public class Quadratic_Equations {
private final static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Please enter a, b and c or enter \"exit\" at any time to exit");
double a = promptUserUntilValidInput("Please enter a:");
double b = promptUserUntilValidInput("Please enter b:");
double c = promptUserUntilValidInput("Please enter c:");
System.out.println(formatOutput(calculateQuadraticFormula(a, b, c)));
System.out.println();
}
}
private static String formatOutput(Set<Double> resultsFromEquation) {
if (resultsFromEquation == null)
return "These numbers do not compute - they produce an illegal result.";
else {
return resultsFromEquation.toString();
}
}
private static double promptUserUntilValidInput(String prompt){
if (prompt.equals("exit")) {
sc.close();
System.exit(0);
}
boolean valid = false;
Double value = new Double(0.0);
while(!valid){
System.out.println(prompt);
value = tryParse(sc.nextLine());
if (value != null)
valid = true;
}
return value;
}
private static Double tryParse(String text){
try{
return Double.parseDouble(text);
}
catch (NumberFormatException e){
return null;
}
}
public static Set<Double> calculateQuadraticFormula(double a, double b, double c) {
Set<Double> results = new HashSet<Double>();
double temp = (b * b) - (4 * a * c);
if (temp < 0)
return null;
if( temp == 0 ) {
results.add(-b / 2 * a);}
else if( temp > 0) {
results.add( (-b + Math.sqrt(temp) ) / (2 * a) );
results.add( (-b - Math.sqrt(temp) ) / (2 * a) );
}
return results;
}
}
</code></pre>
<p>Before I go on, there are a few things I should point out.</p>
<p>I'm aware this could be better if the quadratic stuff was in a class of its own - however, for the purposes of this simple exercise I'm happy skipping that.</p>
<p>My main issues are:</p>
<ol>
<li><p>static Scanner. Some people on previous question suggested making this a private variable, but then it needs to get passed to <em>everything</em>. Is this worth it?</p></li>
<li><p>Does it look okay to close the scanner (and exit the program) where I do?</p></li>
<li><p>Do other methods look single-responsibility-ish enough?</p></li>
</ol>
| [] | [
{
"body": "<p>The static Scanner is a problem, a better way to do it is with the Java try-with-resources. If you add the scanner as an input parameter to the prompt function, you can do:</p>\n\n<p>Change your prompt method from:</p>\n\n<blockquote>\n<pre><code>private static double promptUserUntilValidInput(String prompt){\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>private static double promptUserUntilValidInput(Scanner sc, String prompt){\n</code></pre>\n\n<p>and then change your main-method to:</p>\n\n<pre><code>public static void main(String[] args) {\n try (Scanner sc = new Scanner(System.in)) {\n while (true) {\n System.out.println(\"Please enter a, b and c or enter \\\"exit\\\" at any time to exit\");\n double a = promptUserUntilValidInput(sc, \"Please enter a:\");\n double b = promptUserUntilValidInput(sc, \"Please enter b:\");\n double c = promptUserUntilValidInput(sc, \"Please enter c:\");\n System.out.println(formatOutput(calculateQuadraticFormula(a, b, c)));\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<p>Instead of doing the System.exit, I would prefer a less abrupt exit. Consider a custom Exception, like \"EndOfProgramException\" which you can catch....</p>\n\n<pre><code>private static class EndOfProgramException extends RuntimeException {\n EndOfProgramException () {\n super();\n }\n}\n</code></pre>\n\n<p>and throw this exception in your prompt method:</p>\n\n<pre><code> if (prompt.equals(\"exit\")) {\n throw new EndOfProgramException();\n }\n</code></pre>\n\n<p>and catch it in the main:</p>\n\n<pre><code>public static void main(String[] args) {\n try (Scanner sc = new Scanner(System.in)) {\n while (true) {\n System.out.println(\"Please enter a, b and c or enter \\\"exit\\\" at any time to exit\");\n double a = promptUserUntilValidInput(sc, \"Please enter a:\");\n double b = promptUserUntilValidInput(sc, \"Please enter b:\");\n double c = promptUserUntilValidInput(sc, \"Please enter c:\");\n System.out.println(formatOutput(calculateQuadraticFormula(a, b, c)));\n System.out.println();\n }\n } catch (EndOfProgramException e) {\n System.out.prinln(\"Exiting...\");\n }\n}\n</code></pre>\n\n<p>As for the single-responsibility, it would look pretty clean with the above changes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:19:39.757",
"Id": "80912",
"Score": "0",
"body": "Sorry - how could I catch the exception in the prompt method? Currently I call the readLine method when calling tryParse. How would I fit the detect \"exit\" in there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:23:55.420",
"Id": "80917",
"Score": "0",
"body": "Ahh... yes, I missed that. It is a bit of a hack, but adding it to the try-parse would be easy. Better would be to read the line before calling tryParse, and to check it then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:25:48.263",
"Id": "80918",
"Score": "0",
"body": "I thought that - all advice so far has been to leave tryParse to do one thing. That's what I'll do"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:06:19.873",
"Id": "81135",
"Score": "0",
"body": "Wherever you feel the urge to call `System.exit()`, throw an `EndOfProgramExeption` instead. That would cause the program flow to jump to the end of `main()`, where it would be caught."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:04:59.093",
"Id": "46323",
"ParentId": "46322",
"Score": "5"
}
},
{
"body": "<h3>Bugs</h3>\n\n<ul>\n<li><p><code>calculateQuadraticFormula()</code> calculates wrong results for double roots. Watch your operator associativity!</p>\n\n<pre><code>if( temp == 0 ) {\n results.add(-b / 2 * a);}\n</code></pre></li>\n<li><p>The \"exit\" feature doesn't work. The <em>prompt</em> would never be <code>\"exit\"</code>, would it?</p>\n\n<pre><code>private static double promptUserUntilValidInput(String prompt){\n if (prompt.equals(\"exit\")) {\n sc.close();\n System.exit(0);\n }\n</code></pre></li>\n</ul>\n\n<h3>Design issues</h3>\n\n<ul>\n<li>Class names should be nouns, and the name should reflect their purpose. I recommend <code>QuadraticSolver</code> as the class name.</li>\n<li>The <code>calculateQuadraticFormula()</code> function could then be simply named <code>solve()</code>.</li>\n<li>The class should not hold a <code>Scanner</code> as a member variable, as that would violate the Single Responsibility Principle. It can be a local variable in <code>main()</code> that gets passed to the prompting function. (The scanner should be created using a try-with-resources block.)</li>\n<li>Returning <code>null</code> from the solver is annoying for the caller to handle. I suggest returning an empty set if there are no real roots.</li>\n<li>I suggest returning two copies of the result if it is a double root, but that is a matter for debate.</li>\n</ul>\n\n<h3>Style issues</h3>\n\n<ul>\n<li>You assign the expression <code>(b * b) - (4 * a * c)</code> to a variable named <code>temp</code>. Why not use a descriptive name <code>discriminant</code>?</li>\n<li><p>The <code>promptUserUntilValidInput()</code> function could be better if you removed its <code>tryParse()</code> helper, I think. (Furthermore, <code>promptUser…</code> is redundant — who else are you going to prompt?)</p>\n\n<p>Also, since there is a <code>System.exit()</code> hidden inside, it needs to be documented. (Actually, @rolfl's suggestion to throw an exception is better.)</p>\n\n<pre><code>/**\n * Prompts the user to enter a number, and retries until the input is a\n * valid double. Calls System.exit(0) if the input is \"exit\", or if EOF\n * is encountered.\n */\nprivate static double promptUntilValidInput(String prompt, Scanner sc) {\n do {\n try {\n System.out.print(prompt);\n String input = sc.nextLine();\n if (\"exit\".equals(input)) {\n System.exit(0);\n }\n return Double.parseDouble(input);\n } catch (NoSuchElementException eof) {\n System.out.println();\n System.exit(0);\n } catch (NumberFormatException retryOnBadInput) {\n }\n } while (true);\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T09:57:42.783",
"Id": "80987",
"Score": "0",
"body": "Thank you for this. Can I ask what you mean when you say that returning the null from the solver is annoying for the caller to handle. After your suggestion I'm returning an empty set and then in the formatResult method I check if its empty. Why is this better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:08:47.987",
"Id": "80988",
"Score": "1",
"body": "Returning null forces the caller to check for a null. Returning an empty set lets the caller write simpler code, such as `System.out.println(\"Equation has \" + solve(a, b, c).size() + \" real solutions.\");` That would be uglier if you returned `null`. Another way to think of it is that anything that removes the possibility of a `NullPointerException` is beneficial."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:45:13.117",
"Id": "46330",
"ParentId": "46322",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:32:46.803",
"Id": "46322",
"Score": "8",
"Tags": [
"java",
"beginner"
],
"Title": "Quadratic Expression Calculator 2"
} | 46322 |
<p>Today, my project was to make a matrix in my web browser. It is really slow, so help with optimizing it would be nice. It runs slow on my PC, yet alone my iPod 4 which this is going to be for.</p>
<pre><code><html>
<head>
<title>Matrix</title>
<style type="text/css">
body {
background-color:black;
background-size: 100%;
}
#mat {
font-size:8px;
font-family:"Courier";
font-weight:bold;
}
</style>
<body onLoad="randomMatrix()">
<div id="mat">
<span style="color:#005400"> hi </span><span>hi</span>
</div>
<script type="text/javascript">
function randomLine()
{
var text = "<span>";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < 63; i++ ) text += "</span><span style=\"color:"+randomGreen()+"\">"+possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function randomMatrix() {
document.getElementById("mat").innerHTML = randomLine();
for(var i = 0; i<45;i++) document.getElementById("mat").innerHTML += "<br/>"+randomLine();
sleep(125, randomMatrix);
}
function sleep(millis, callback) {
setTimeout(function()
{ callback(); }
, millis);
}
function randomGreen() {
return "#00"+randInt(0,255).toString(16)+"00";
}
function randInt(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
</body>
</html>
</code></pre>
<p>You can try it out <a href="http://jsfiddle.net/xy2EN/3/" rel="nofollow">here</a>. ANY speed improvements would greatly help!</p>
| [] | [
{
"body": "<p><a href=\"http://jsfiddle.net/xy2EN/6/\">Here's what I did</a></p>\n\n<pre><code>var theMatrix = (function (containerId, lines, columns) {\n // We wrap everything in a closure, and expose only a single\n // global. Avoids global pollution, and keeps everything in\n // one place.\n\n var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n // We break functionality into functions, naming verbosely\n function randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n\n function randomGreen() {\n return \"#00\" + randomInt(0, 255).toString(16) + \"00\";\n }\n\n function randomLetter() {\n return characters.charAt(Math.floor(Math.random() * characters.length));\n }\n\n function generateLine(columns) {\n var line = document.createElement('div');\n while (columns--) {\n var letter = document.createElement('span');\n letter.style.color = randomGreen();\n letter.innerHTML += randomLetter();\n line.appendChild(letter);\n }\n return line;\n }\n\n function writeLines(container, lines, columns) {\n for (var i = 0; i < lines; i++) {\n container.appendChild(generateLine(columns));\n }\n }\n\n function startMatrix(container,columns) {\n setInterval(function loop() {\n // Instead of rebuilding the DOM all at once, we change\n // by line, by removing the top line, and appending\n // at the bottom.\n var firstLine = container.firstChild;\n container.removeChild(firstLine);\n container.appendChild(generateLine(columns));\n\n // Also, used doesn't care, you can replace the line\n // before this with the following line to cycle the\n // lines instead of regenerating the last line\n //container.appendChild(firstLine);\n }, 50);\n }\n\n // The exposed function. The only function that \"keeps state\"\n // (knows instance settings). All other function are reusable\n // and are not bound to a single call\n return function (containerId, lines, columns) {\n var container = document.getElementById(containerId);\n\n // we write the initial lines\n var textNodes = writeLines(container, lines, columns);\n\n // start the matrix\n startMatrix(container,columns);\n };\n}());\n\n\ntheMatrix('mat', 50, 80);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:08:40.273",
"Id": "80998",
"Score": "0",
"body": "This is great! It even runs decently on my iPod!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:24:41.040",
"Id": "46336",
"ParentId": "46327",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46336",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:13:30.997",
"Id": "46327",
"Score": "5",
"Tags": [
"javascript",
"html",
"css",
"matrix"
],
"Title": "Dynamic matrix in web browser"
} | 46327 |
<p>I know there is a better way to store data. What is the most concise way to simplify this script?</p>
<pre><code>from random import randint
from sys import exit
import os
os.system('clear')
print "Welcome to the dice rolling simulator!"
raw_input("Press enter to begin.")
total = 0
completed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
def roll():
os.system('clear')
die1 = randint(1, 6)
die2 = randint(1, 6)
global total
total = die1 + die2
storetotal()
print "Die 1: %d \nDie 2: %d \nTotal: %d." % (die1, die2, total)
print "\n\nRoll again?"
roll_again = raw_input("Press enter to roll again, type 'stats' to view scores, or 'quit' to exit.\n> ")
if roll_again == "":
roll()
elif roll_again == "stats":
stats()
elif roll_again == "quit":
exit(0)
else:
print "I don't know what that means so you get to roll again."
raw_input("> ")
roll()
def stats():
global total
print "2s: %d \n3s: %d \n4s: %d \n5s: %d \n6s: %d \n7s: %d \n8s: %d" % (completed[0],
completed[1], completed[2], completed[3],
completed[4], completed[5], completed[6])
print "9s: %d \n10s: %d \n11s: %d \n12s: %d""" % (completed[7], completed[8],
completed[9], completed[10])
raw_input("")
roll()
def storetotal():
if total == 2:
completed[0] += 1
elif total == 3:
completed[1] += 1
elif total == 4:
completed[2] += 1
elif total == 5:
completed[3] += 1
elif total == 6:
completed[4] += 1
elif total == 7:
completed[5] += 1
elif total == 8:
completed[6] += 1
elif total == 9:
completed[7] += 1
elif total == 10:
completed[8] += 1
elif total == 11:
completed[9] += 1
else:
completed[10] += 1
roll()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-12T17:56:14.063",
"Id": "239759",
"Score": "0",
"body": "I tried all the above codes but it shows invalid syntax T.T"
}
] | [
{
"body": "<p>So, first, it's all a bit confusing when the indentation is messed up (which is important in Python). You should first get that in order.</p>\n\n<p>Also globals are usually a bad idea, and they're not necessary here. It also appears that, even properly executed, you've built this program as an infinite recursion (which is very inefficient). Instead you should just have your code in a loop implemented as a <a href=\"http://en.wikipedia.org/wiki/Finite-state_machine\">finite state machine</a> (one state for rolling, another for stats, and an exit-state for quitting.</p>\n\n<p>Also python uses underscore_naming so storetotal should be store_total (or better yet update_total). Also storetotal can be simplified greatly to a single line:</p>\n\n<pre><code>completed[total - 2] += 1\n</code></pre>\n\n<p>And the stats printing lines can be similarly simplified:</p>\n\n<pre><code>for i in xrange(0, 11):\n print '%ds: %d' % (i + 2, completed[i])\n</code></pre>\n\n<p>From a style perspective, Python also uses single-quotes, not double-quotes.</p>\n\n<p>The resultant code should look something like this:</p>\n\n<pre><code>from random import randint\nfrom sys import exit\nimport os\n\n\ndef handle_roll(total_counts):\n die1, die2 = randint(1, 6), randint(1, 6)\n total = die1 + die2\n total_counts[total - 2] += 1\n\n print 'Die 1: %d \\nDie 2: %d \\nTotal: %d.' % (die1, die2, total)\n print '\\n\\nRoll again?'\n response = raw_input('Press enter to roll again, type \"stats\" to view scores, or \"quit\" to exit.\\n> ').lower()\n if response == '':\n return handle_roll\n elif response == 'stats':\n return handle_stats\n elif response == 'quit':\n return None\n\n return handle_unknown\n\n\ndef handle_stats(total_counts):\n for i in xrange(0, 11):\n print '%ds: %d' % (i + 2, total_counts[i])\n raw_input('')\n return handle_roll\n\n\ndef handle_unknown(total_counts):\n print 'I don\\'t know what that means so you get to roll again.'\n raw_input('')\n return handle_roll\n\n\ndef main():\n os.system('clear')\n print 'Welcome to the dice rolling simulator!'\n raw_input('Press enter to begin.')\n\n total_counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n state = handle_roll\n while state != None:\n os.system('clear')\n state = state(total_counts)\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:01:35.197",
"Id": "80923",
"Score": "1",
"body": "Using single or double quotes in python is a matter of preference. Also, PEP 257 enforces using double quotes for docstrings. Agree with the rest."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:48:24.827",
"Id": "46332",
"ParentId": "46328",
"Score": "8"
}
},
{
"body": "<h1>Line by line analysis</h1>\n\n<p>Use four spaces to indent python code. Never use tabs.</p>\n\n<pre><code>from random import randint\nfrom sys import exit\nimport os\n</code></pre>\n\n<p>It is a good practice to do top-level imports (without importing module members). This way it's easier to understand what package the methods come from.</p>\n\n<pre><code>os.system('clear')\nprint \"Welcome to the dice rolling simulator!\"\nraw_input(\"Press enter to begin.\")\n\ntotal = 0\n\ncompleted = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n</code></pre>\n\n<p>Use list comprehensions.</p>\n\n<pre><code>def roll():\n</code></pre>\n\n<p>Roll method is confusing. You expect it to roll a die, but it processes iterations of the game. A while loop would be more explicit here.</p>\n\n<pre><code>os.system('clear')\ndie1 = randint(1, 6)\ndie2 = randint(1, 6)\nglobal total\n</code></pre>\n\n<p>Global variables are no-no. Never.</p>\n\n<pre><code>total = die1 + die2\nstoretotal()\nprint \"Die 1: %d \\nDie 2: %d \\nTotal: %d.\" % (die1, die2, total)\nprint \"\\n\\nRoll again?\"\nroll_again = raw_input(\"Press enter to roll again, type 'stats' to view scores, or 'quit' to exit.\\n> \") \n</code></pre>\n\n<p>You're exceeding recommended 80 column length limit.</p>\n\n<pre><code>if roll_again == \"\":\n roll()\n</code></pre>\n\n<p>See how I changed this block in a code below.</p>\n\n<pre><code>elif roll_again == \"stats\":\n stats()\nelif roll_again == \"quit\":\n exit(0)\n</code></pre>\n\n<p>Return from the method is sufficient here.</p>\n\n<pre><code>else:\n print \"I don't know what that means so you get to roll again.\"\n raw_input(\"> \")\n roll()\n\ndef stats():\nglobal total\nprint \"2s: %d \\n3s: %d \\n4s: %d \\n5s: %d \\n6s: %d \\n7s: %d \\n8s: %d\" % (completed[0], completed[1], completed[2], completed[3], \n completed[4], completed[5], completed[6])\nprint \"9s: %d \\n10s: %d \\n11s: %d \\n12s: %d\"\"\" % (completed[7], completed[8], \n completed[9], completed[10]) \n</code></pre>\n\n<p>Indentation here is completely messed up.</p>\n\n<pre><code>raw_input(\"\")\nroll()\n\ndef storetotal():\n</code></pre>\n\n<p>PEP8: <code>store_total</code>.</p>\n\n<pre><code>if total == 2:\n completed[0] += 1\nelif total == 3:\n completed[1] += 1\nelif total == 4:\n completed[2] += 1\nelif total == 5:\n completed[3] += 1\nelif total == 6:\n completed[4] += 1\nelif total == 7:\n completed[5] += 1\nelif total == 8:\n completed[6] += 1\nelif total == 9:\n completed[7] += 1\nelif total == 10:\n completed[8] += 1\nelif total == 11:\n completed[9] += 1\nelse:\n completed[10] += 1\n\n\nroll()\n</code></pre>\n\n<h1>Improved code</h1>\n\n<p>I simplified your <code>roll</code> method to <code>roll2d6</code> and moved all the other code into <code>main</code>.</p>\n\n<pre><code>import random\nimport os\n\n\ndef roll2d6():\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n return die1 + die2\n\n\ndef display_stats(stats):\n for i, result in enumerate(stats):\n print \"%ds: %d\" % (i + 2, result)\n\n\ndef update_stats(total, stats):\n stats[total - 2] += 1\n return stats\n\n\ndef main():\n stats = [0 for _ in xrange(10)]\n\n os.system('clear')\n print \"Welcome to the dice rolling simulator!\"\n raw_input(\"Press enter to begin.\")\n while True:\n os.system('clear')\n total = roll2d6()\n stats = update_stats(total, stats)\n print \"Die 1: %d \\nDie 2: %d \\nTotal: %d.\" % (die1, die2, total)\n print \"\\n\\nRoll again?\"\n roll_again = raw_input((\n \"Press enter to roll again, type 'stats' to view scores, \"\n \"or 'quit' to exit.\\n> \"))\n if roll_again.lower() == \"stats\":\n display_stats(stats)\n elif roll_again.lower() == \"quit\":\n break\n elif roll_again.lower() != \"\":\n print \"I don't know what that means so you get to roll again.\"\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:14:54.793",
"Id": "80930",
"Score": "1",
"body": "Additional suggestion : `stats = [0] * 10`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:22:31.620",
"Id": "80931",
"Score": "1",
"body": "Also : call `lower()` on the result of `raw_input()` before storing in `roll_again` / write `elif roll_again.lower() == \"\": continue` to have all conditions written in a positive way - it makes the code longer but also clearer imho."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T01:25:33.673",
"Id": "80939",
"Score": "0",
"body": "Check highest voted answer: http://stackoverflow.com/questions/119562/tabs-versus-spaces-in-python-programming ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:13:00.920",
"Id": "80945",
"Score": "0",
"body": "`display_stats(stats)` would be cleaner with `enumerate(stats, start=2)` rather than `i + 2` on every iteration and `update_stats(total, stats)` is just a waste of space, it is only called once and is basically a one-liner so why not inline it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:54:26.690",
"Id": "80955",
"Score": "1",
"body": "There's a coding style that any logical selfcontained subunit should be def'd so it can be reused elsewhere. Space is cheap, and you won't notice any speed difference."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:58:16.453",
"Id": "46333",
"ParentId": "46328",
"Score": "15"
}
}
] | {
"AcceptedAnswerId": "46333",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:16:52.003",
"Id": "46328",
"Score": "11",
"Tags": [
"python",
"python-2.x",
"random",
"simulation",
"dice"
],
"Title": "Dice-rolling simulator"
} | 46328 |
<p>Please be brutal, and let me know how I've done on this problem, provided I coded it at an interview for a top tech firm.</p>
<p><strong>Time it took me:</strong> 44 minutes</p>
<p><strong>Worst case time complexity:</strong> O(n<sup>2</sup>)? Am I right?</p>
<p><strong>Space Complexity:</strong> O(n)?</p>
<p><strong>Problem:</strong></p>
<blockquote>
<p>A group of people stand before you arranged in rows and columns.
Looking from above, they form an R by C rectangle of people. You will
be given a <code>String[]</code> people containing the height of each person.
Elements of people correspond to rows in the rectangle. Each element
contains a space-delimited list of integers representing the heights
of the people in that row.</p>
<p>Your job is to return 2 specific heights in
a <code>int[]</code>. The first is computed by finding the shortest person in each
row, and then finding the tallest person among them (the
"tallest-of-the-shortest"). The second is computed by finding the
tallest person in each column, and then finding the shortest person
among them (the "shortest-of-the-tallest").</p>
</blockquote>
<p><strong>Definition:</strong></p>
<blockquote>
<p><strong>Class:</strong> <code>TallPeople</code></p>
<p><strong>Method:</strong> <code>getPeople</code></p>
<p><strong>Parameters:</strong> <code>String[]</code></p>
<p><strong>Returns:</strong> <code>int[]</code></p>
<p><strong>Method signature:</strong> <code>int[] getPeople(String[] people)</code> (be sure your method is public)</p>
<p><strong>Constraints:</strong></p>
<ul>
<li>people will contain between 2 and 50 elements inclusive.</li>
<li>Each element of people will contain between 3 and 50 characters inclusive.</li>
<li><p>Each element of people will be a single space-delimited list of positive integers such that: </p>
<ol>
<li><p>Each positive integer is between 1 and 1000 inclusive with no extra
leading zeros.</p></li>
<li><p>Each element contains the same number of integers.</p></li>
<li><p>Each element contains at least 2 positive integers.</p></li>
<li><p>Each element does not contain leading or trailing whitespace.</p></li>
</ol></li>
</ul>
</blockquote>
<p><strong>Examples:</strong> </p>
<blockquote>
<pre><code>{"9 2 3",
"4 8 7"}
</code></pre>
<p>Returns: { 4, 7 }</p>
<p>The heights 2 and 4 are the shortest from the rows,
so 4 is the taller of the two. The heights 9, 8, and 7 are the tallest
from the columns, so 7 is the shortest of the 3. 1) </p>
<pre><code>{"1 2",
"4 5",
"3 6"}
</code></pre>
<p>Returns: { 4, 4 } </p>
<pre><code>{"1 1",
"1 1"}
</code></pre>
<p>Returns: { 1, 1 }</p>
</blockquote>
<p><strong>Answer:</strong></p>
<pre><code>public static int[] getPeople(String[] people){
int maxOfMinHeight = Integer.MIN_VALUE;
int minOfMaxHeight = Integer.MAX_VALUE;
int count=0;
String[][]findMaxOfMin = new String[people.length][people[0].split(" ").length];
int[][] findMinOfMax = new int[people[0].split(" ").length][people.length];
for(String s : people){
String[] sort = s.split(" ");
Arrays.sort(sort);
findMaxOfMin[count++]=sort;
}
for(int i=0; i<findMaxOfMin.length; i++){
maxOfMinHeight = Math.max(maxOfMinHeight, Integer.valueOf(findMaxOfMin[i][0]));
}
count=0;
int cols = people[0].split(" ").length;
for(int i=0; i<cols; i++){
int[] temp = new int[people.length];
for(int j=0; j<people.length; j++){
temp[j] = Integer.valueOf( ((String[])people[j].split(" "))[i]);
}
Arrays.sort(temp);
findMinOfMax[count++]=temp;
}
for(int i=0; i<findMinOfMax.length; i++){
minOfMaxHeight = Math.min(minOfMaxHeight, findMinOfMax[i][people.length-1]);
}
return new int[] {minOfMaxHeight, maxOfMinHeight};
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:49:44.607",
"Id": "80921",
"Score": "1",
"body": "From where do you get these problems? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:54:27.467",
"Id": "80922",
"Score": "0",
"body": "@SimonAndréForsberg TopCoder. :) I have a major interview coming up in September, and I am preparing for it now."
}
] | [
{
"body": "<ol>\n<li><p>Split it up! The current method does more than one thing, I'd create at least three helper methods:</p>\n\n<pre><code>int[][] parseInput(String[] input);\nint getMaxOfMinHeightInColumns(int[][] peoples);\nint getMinOfMaxHeightInRows(int[][] peoples);\n</code></pre>\n\n<p>It would be easier to follow and understand.</p></li>\n<li><p>I looks like a bug that the following testcase fails:</p>\n\n<pre><code>@Test\npublic void test() {\n String[] input = {\"9 2 3\",\n \"4 8 7\"};\n int[] result = getPeople(input);\n assertArrayEquals(new int[] {4, 7}, result);\n}\n</code></pre></li>\n<li><p>Reusing the count variable is a bad sing:</p>\n\n<blockquote>\n<pre><code>count=0;\n</code></pre>\n</blockquote>\n\n<p>Try to use two different variables for different purposes and more descriptive names. What does it count? Put that into the name of the variable.</p></li>\n<li><p>A few explanatory variable would be more readable here and remove some duplication:</p>\n\n<blockquote>\n<pre><code>String[][]findMaxOfMin = new String[people.length][people[0].split(\" \").length];\nint[][] findMinOfMax = new int[people[0].split(\" \").length][people.length];\n</code></pre>\n</blockquote>\n\n<p>Consider creating one for <code>people.length</code> and another for <code>people[0].split(\" \").length</code> (columnNumber, rowNumber, for example).</p></li>\n<li><p><code>(String[])</code> casting seems unnecessary here:</p>\n\n<blockquote>\n<pre><code>temp[j] = Integer.valueOf( ((String[])people[j].split(\" \"))[i]);\n</code></pre>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T00:37:13.697",
"Id": "80934",
"Score": "0",
"body": "what about the space complexity and time complexity of the problem I solved?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T01:07:34.213",
"Id": "80935",
"Score": "0",
"body": "@bazang: Space complexity seems O(n). I can't say too much about time complexity I didn't understand the code completely."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:36:05.677",
"Id": "46337",
"ParentId": "46329",
"Score": "6"
}
},
{
"body": "<p>Complexity will essentially be defined by this structure:</p>\n\n<blockquote>\n<pre><code>for(int i=0; i<cols; i++){\n int[] temp = new int[people.length];\n for(int j=0; j<people.length; j++){\n temp[j] = Integer.valueOf( ((String[])people[j].split(\" \"))[i]);\n }\n Arrays.sort(temp);\n findMinOfMax[count++]=temp;\n}\n</code></pre>\n</blockquote>\n\n<p>which, using 'c' for <code>cols</code>, and 'p' for <code>people.length</code> will produce a complexity of:</p>\n\n<ul>\n<li><p><em>O( p * c )</em> for the inner for-loop</p>\n\n<ul>\n<li>the loop itself is is <em>O(p)</em> and</li>\n<li><em>O(c)</em> for the <code>((String[])people[j].split(\" \"))</code></li>\n</ul></li>\n<li><p><em>O(p log p)</em> for the <code>Arrays.sort(temp)</code></p></li>\n</ul>\n\n<p>Putting those together in the outer O(c) loop, I calculate the complexity to be in the order of:</p>\n\n<p><em><strong>O( pc<sup>2</sup> + cp log p )</em></strong></p>\n\n<p>The <strong><em>O(pc<sup>2</sup>)</em></strong> will be the dominant complexity.</p>\n\n<p>If you move the Split to be outside the outer loop, and do something like:</p>\n\n<pre><code>int[][] data = new int[people.length][cols];\nfor (int j = 0; j < people.length; j++) {\n String[] parts = people[j].split(\" \");\n for (int i = 0; i < cols; i++) {\n data[j][i] = Integer.valueOf(parts[i]);\n }\n}\nfor(int i=0; i<cols; i++){\n int[] temp = new int[people.length];\n for(int j=0; j<people.length; j++){\n temp[j] = data[j][i];\n }\n Arrays.sort(temp);\n findMinOfMax[count++]=temp;\n}\n</code></pre>\n\n<p>Then your overall complexity will drop to <strong><em>O(pc log p)</em></strong> because that part of the complexity will bcome dominant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T01:51:50.603",
"Id": "46342",
"ParentId": "46329",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46337",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T22:25:19.517",
"Id": "46329",
"Score": "9",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Sorting and searching problem related to a group of people standing in a rectangle"
} | 46329 |
<p>I have the following C++ interface (in Qt) for a tree node, inspired somewhat by Valve's implementation of a culling octree:</p>
<pre><code>/**
* @brief Interface for a recursive tree node.
*/
class ITreeNode
{
public:
/**
* @brief Virtual destructor.
*/
virtual ~ITreeNode() {}
/**
* @brief Adds a child node to this node.
* @param node Node to add.
*/
virtual void addChild(ITreeNode* node) = 0;
/**
* @brief Removes the child node at the given index from this node.
* @param index Index of child to remove.
* @return Child removed, or NULL if the index was invalid.
*/
virtual ITreeNode* removeChild(int index) = 0;
/**
* @brief Removes the given child node if it exists.
* @param node Node to remove.
*/
virtual void removeChild(ITreeNode* node) = 0;
/**
* @brief Returns the child at a given index.
* @param index Index of the child.
* @return Child at this index, or NULL if the index was invalid.
*/
virtual ITreeNode* childAt(int index) const = 0;
/**
* @brief Returns whether the given node is recorded as a child of this node.
* @param node Node to search for.
* @return True if the given node is recorded as a child; false otherwise, or if the node provided is NULL.
*/
virtual bool containsChild(ITreeNode* node) const = 0;
/**
* @brief Returns whether this node is an ancestor of the given node.
* @note This means that this node is present further up the path from the root node to the given node.
* @param node Node to check ancestry of.
* @return True if this node is an ancestor of the given node, false otherwise or if the given node is NULL.
*/
virtual bool isAncestor(const ITreeNode* node) const = 0;
/**
* @brief Returns whether this node is a successor of the given node.
* @note This means that the given node is present further up the path from the root node to this node.
* @param node Node to check successors of.
* @return True if this node is a successor of the given node, false otherwise or if the given node is NULL.
*/
virtual bool isSuccessor(const ITreeNode *node) const = 0;
/**
* @brief Returns the number of direct children this node has
* @return Number of children recorded in this node.
*/
virtual int childCount() const = 0;
/**
* @brief Returns whether this node is a leaf (ie. it has no children).
* @return True if the node is a leaf, false otherwise.
*/
virtual bool isLeaf() const = 0;
/**
* @brief Returns a pointer to the parent of this node.
* @return Pointer to parent, or NULL if no parent is recorded.
*/
virtual ITreeNode* parent() const = 0;
/**
* @brief Sets the parent of this node.
* @param parent Parent node to set.
*/
virtual void setParent(ITreeNode* parent) = 0;
/**
* @brief Returns whether this node is the root (ie. it has no parent).
* @return True if the node is the root of the tree, false otherwise.
*/
virtual bool isRoot() const = 0;
/**
* @brief Recursively deletes all of this node's children, leaving this node as a leaf.
*/
virtual void pruneSubtree() = 0;
/**
* @brief Removes the node from the tree structure, leaving the remainder disjoint.
*
* The node will be removed as a child from its parent, and will leave all its children as roots of
* their respective subtrees.
* @return List of child nodes removed from this node.
*/
virtual QList<ITreeNode*> detachNode() = 0;
};
</code></pre>
<p>In order to improve my understanding of how interfaces should be designed I'm looking for a critique, if possible, of the functionality of this interface. My general target was to include a useful set of basic tree-related functions - obviously the bare minimum would be simply adding/removing/getting children, but I also felt as though automating potentially useful processes such as removing all children (<code>pruneSubtree()</code> - thinking recursive deletion) and removing a node from a given tree structure to leave a forest might help make future tasks easier.</p>
<p>I'm also torn on whether it's better to pass a node pointer in when adding a child (the method Valve used, where the node takes ownership of the child being added) or to have the add method not require a pointer and simply have the node create and manage its own children - I'm not clued up on the relative merits of these two choices, so arguments for and against would be helpful.</p>
<p>So basically:</p>
<ul>
<li>Is this interface complete? Does it attempt to do too much or too little?</li>
<li>Is it a good idea to include potentially specialised functions such as <code>pruneSubtree()</code> and <code>detachNode()</code> early on, or leave them for subclasses?</li>
<li>Is it better to have the implementing class manage all children in memory, or allow them to be passed in externally?</li>
<li>Are there situations in which functionality such as this wouldn't necessarily require an interface? In what situations do interfaces begin to become necessary?</li>
<li>Should enforcing potentially high-level conditions, such as no circular node links, etc., be considered at this stage?</li>
<li>Any other important points I have failed to mention?</li>
</ul>
| [] | [
{
"body": "<blockquote>\n <p>Is this interface complete? Does it attempt to do too much or too little?</p>\n</blockquote>\n\n<p>In my opinion, interfaces should be as small as possible, providing only methods that are really required to be called without knowing (or casting to) the actual subclass. I don't know how you use it, but my first impression is: your interface contains too many methods...</p>\n\n<blockquote>\n <p>Are there situations in which functionality such as this wouldn't necessarily require an interface?</p>\n</blockquote>\n\n<p>An interface is useful if you have two or more classes that are implemented differently but require the same interface. In your case I don't think that the actual subclasses will implement this interface with significant differences. (Actually I don't see <em>any</em> methods I would expect to behave differently)</p>\n\n<p>So maybe instead of an interface a real base class would be the better choice to avoid code duplicates. You could implement a treenode class (implementing all those methods itself) and inherit from it to only change/add the different behaviours... (Again I can only guess as I don't see your subclasses)</p>\n\n<blockquote>\n <p>Is it better to have the implementing class manage all children in memory, or allow them to be passed in externally?</p>\n</blockquote>\n\n<p>Well, your children's nodes <em>are</em> passed in externally (and I think that's the only way that makes sense) - you only have to decide whether to let the parent node take over ownership of its children or not.</p>\n\n<p>As long as you don't share single instances of your nodes between different trees (or at least different parents) or reuse them in any other way, I would prefer the parents to take ownership (delete them when they are no longer needed).</p>\n\n<p>Objects taking ownership of their children is also a well known practice in Qt. As you're using Qt, I would recommend mimicking this behaviour.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-28T10:26:45.190",
"Id": "89779",
"Score": "0",
"body": "Great analysis, that's really helpful. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T15:09:24.753",
"Id": "51543",
"ParentId": "46334",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "51543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:06:12.277",
"Id": "46334",
"Score": "5",
"Tags": [
"c++",
"tree",
"interface",
"qt"
],
"Title": "Interface for a tree node in Qt"
} | 46334 |
<p>I'm trying to get a certain number of date ranges given a start date. Here's my code:</p>
<pre><code>var startDate = new DateTime(2014, 1, 1);
var dates = new List<DateBlock>();
int counter = 0;
while(counter < 6)
{
if (startDate >= DateTime.UtcNow)
{
dates.Add(new DateBlock
{
StartDate = startDate,
EndDate = startDate.AddDays(30)
});
counter++;
}
startDate = startDate.AddDays(30);
}
var first = dates.First();
dates.Insert(0, new DateBlock
{
StartDate = first.StartDate.AddDays(-30),
EndDate = first.StartDate
});
</code></pre>
<p>I'm wondering if there is a better way of doing this?</p>
<p>EDIT:
If the start date is 1/1/1 it should loop through and increment by 30 days and only add to the list if the current date is greater than or equal to UtcNow. Also it should keep going into the future until 6 more DateBlock's are added to the list.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:22:53.320",
"Id": "81026",
"Score": "0",
"body": "So it should only start adding date ranges when the start date is in the future?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:33:17.237",
"Id": "81028",
"Score": "0",
"body": "@MitchellLee Correct."
}
] | [
{
"body": "<p>The loop to find the starting date is clearly not needed. This can be done with library object TimeSpan -- like this:</p>\n\n<pre><code>void Main()\n{\n var startDate = new DateTime(2014, 1, 1);\n var dates = new List<DateBlock>();\n\n int priorPeriods = ((DateTime.UtcNow-startDate).Days) / 30;\n\n DateTime dateIndex = startDate.AddDays(priorPeriods*30);\n for(int index = 0; index < 6; index++)\n {\n dates.Add(new DateBlock { StartDate = dateIndex, EndDate = dateIndex.AddDays(30) });\n dateIndex = dateIndex.AddDays(30);\n }\n}\n\npublic class DateBlock\n{\n public DateTime StartDate { get; set;}\n public DateTime EndDate { get; set; }\n}\n</code></pre>\n\n<p>You might have to check the edge case (today is exactly divisible by 30) to see it matches requirements.</p>\n\n<hr>\n\n<p>Here is how you do it with linq (looks cooler, but slower)</p>\n\n<pre><code>void Main()\n{\n var startDate = new DateTime(2014, 1, 1);\n var dates = new List<DateBlock>();\n\n int priorPeriods = ((DateTime.UtcNow-startDate).Days) / 30;\n\n dates = Enumerable.Range(0,6)\n .Select(index => new DateBlock {\n StartDate = startDate.AddDays((priorPeriods+index)*30),\n EndDate =startDate.AddDays((priorPeriods+index+1)*30)\n }).ToList();\n }\n\npublic class DateBlock\n{\n public DateTime StartDate { get; set;}\n public DateTime EndDate { get; set; }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:09:13.023",
"Id": "81035",
"Score": "0",
"body": "Removed my answer (didn't see this post), this is effectively the same thing I was getting at, and the code works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:16:31.787",
"Id": "81036",
"Score": "0",
"body": "@MitchellLee - I added the linq version for you, not Aggregate but Range"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:56:26.463",
"Id": "81039",
"Score": "0",
"body": "I knew I didn't need the unnecessary loop for prior dates! I checked if the boundary was right on a multiple of 30 and it works. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:23:46.273",
"Id": "82690",
"Score": "0",
"body": "I expect you will have subtle errors. `DateTime` comparisons always compare the entire value: `new DateTime(2014, 1, 1)` and `DateTime.Now` will not be equal unless `Now` just happens to be midnight- down to the millisecond. Use `StartDate.Date == DateTime.Now.Date` for example, which sets the time to midnight - thus essentially comparing only the DATEs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T04:10:44.713",
"Id": "82697",
"Score": "0",
"body": "@radarbob - there are no subtle errors, I tested this code. Look again, I'm using the `Days` field and only adding days to the DateTime inputs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T05:52:49.170",
"Id": "83593",
"Score": "0",
"body": "`DateTime.UtcNow-startDate` is making my spidey sense tingle: ok, `startDate` has a midnight time so it won't cause a \"off by one\" error in this case; but in my experience w/o fastidiously applying `Date` property something will screw up - and funny how long it seems to work, until it does not. In one case a datetime in our DB one day did not have a midnight time and the code broke. And Further; however `startDate` does not appear to be in UTC form while the left operand is, so the calculation could be in error in any case: I don't live on the prime meridian"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T09:07:25.967",
"Id": "83606",
"Score": "0",
"body": "@radarbob - Why does `startData` not appear to be in UTC? I declare it. Did you want a comment above the decl that it is a UTC date? Everything here is working with dates not with hours -- so it does not matter. If there were any hour comparisons it would matter, but there are not."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:54:53.230",
"Id": "46374",
"ParentId": "46343",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46374",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:02:35.303",
"Id": "46343",
"Score": "5",
"Tags": [
"c#",
"datetime"
],
"Title": "Date ranges from a given start date"
} | 46343 |
<p>I want my socket class to be reviewed, including recommendations and optimizations.</p>
<p>Sokect.hpp</p>
<pre><code> class Socket {
protected:
Socket(SOCKET s);
Socket();
SOCKET s_;
sockaddr_in sa_;
int* count_;
private:
static void StartSocket();
static void EndSocket();
static int totalNumberSockets_;
public:
virtual ~Socket();
Socket(const Socket&);
std::string RecvData();
void SendData(std::string);
void Close();
};
using namespace std;
//start sockect
void Socket::StartSocket() {
if (!totalNumberSockets_) {
WSADATA info;
if (WSAStartup(MAKEWORD(2, 0), &info)) {
throw "Could not start WSA";
}
}
++totalNumberSockets_;
}
//end end the socket
void Socket::EndSocket() {
WSACleanup();
}
Socket::Socket() : s_(0) {
StartSocket();
s_ = socket(AF_INET, SOCK_STREAM, 0);
if (s_ == INVALID_SOCKET) {
cerr << "Error at Socket(): " << WSAGetLastError() << endl;
throw "INVALID_SOCKET";
}
count_ = new int(1);
}
Socket::Socket(SOCKET s) : s_(s) {
StartSocket();
count_ = new int(1);
};
Socket::~Socket() {
if (!--(*count_)) {
Close();
delete count_;
}
--totalNumberSockets_;
if (!totalNumberSockets_)
EndSocket();
}
Socket::Socket(const Socket& o) {
count_ = o.count_;
(*count_)++;
s_ = o.s_;
totalNumberSockets_++;
}
void Socket::Close() {
closesocket(s_);
}
std::string Socket::RecvData() {
std::string strBuffer;
do{
char buffer;
int recvInt = recv(s_, &buffer, 1, 0);
if (recvInt == INVALID_SOCKET)
{
return "";
}
if (recvInt == SOCKET_ERROR)
{
if (errno == EAGAIN) {
return strBuffer;
}
else {
// not connected anymore
return "";
}
}
strBuffer += buffer;
if (buffer == '\n') return strBuffer;
} while (true);
}
void Socket::SendData(std::string s) {
s += "\n";
send(s_, s.c_str(), s.length(), 0);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:52:21.350",
"Id": "80960",
"Score": "0",
"body": "you can see those post and get some recommendations http://codereview.stackexchange.com/questions/43369/socket-wrapper-class\r\nhttp://codereview.stackexchange.com/questions/43443/windows-socket-class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:12:27.613",
"Id": "80962",
"Score": "0",
"body": "@Jamal just want to ask is count_ = new int(1); is good practice or not or can I write it deffrent"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:17:44.733",
"Id": "80965",
"Score": "0",
"body": "Your use of `count_` seems utterly pointless. I don't see where it's accomplishing anything that a simple `int count_;` couldn't do perfectly well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:22:48.170",
"Id": "80966",
"Score": "0",
"body": "@JerryCoffin i use it only to count how many socket is created when I do web request"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:24:00.723",
"Id": "80967",
"Score": "0",
"body": "Sure--but that doesn't explain anything about why you're allocating it dynamically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:37:25.827",
"Id": "80972",
"Score": "0",
"body": "@JerryCoffin just want to ask can I rewrite my code without using count? because I'm new in socket programming ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:45:25.757",
"Id": "80973",
"Score": "0",
"body": "Yes, I think you can (see the answer I just posted)."
}
] | [
{
"body": "<p>I think you have too many different responsibilities bound up into one class. That ends up not only making that class more complex, but adding extra complexity overall as well. As a starting point, I'd have a really trivial class that does nothing but stack-based management of the WSAStartup/WSACleanup:</p>\n\n<pre><code>struct socket_user {\n socket_user() {\n WSADATA info;\n if (WSAStartup(MAKEWORD(2, 0), &info)) \n throw \"Could not start WSA\"; \n }\n ~socket_user() { \n WSACleanup();\n }\n};\n</code></pre>\n\n<p>Then you can just embed an instance of that into your socket class:</p>\n\n<pre><code>class Socket {\n socket_user s;\n // ...\n};\n</code></pre>\n\n<p>Windows keeps a counter internally, so you're allowed to call WSAStartup repeatedly with matching calls to WSACleanup. No need for extra work on your own part to do that counting over again. So, that trivial class replaces about half the code in the question.</p>\n\n<p>That leaves (mostly) your <code>RecvData</code> and <code>SendData</code>. I think <code>RecvData</code> is open to some improvement as well. Right now, it makes a separate call to <code>recv</code> for each byte of data. That's likely to add a fair amount of overhead. I'd consider passing a somewhat larger buffer to <code>recv</code> so you can receive more data at a time, and spend proportionally less time just jump to/returning from <code>recv</code>. Even increasing the buffer size to 16 bytes is likely to reduce overhead substantially.</p>\n\n<p>I don't really like how you're handling errors either. In particular, if you get a SOCKET_ERROR, you throw away data you've already received and read. If you've already received some data, I'd prefer to see that returned, and let the application decide whether it's really worth keeping or not.</p>\n\n<pre><code> if (recvInt == INVALID_SOCKET)\n {\n return strBuffer;\n }\n</code></pre>\n\n<p>That brings us to another point: I'd rather see more descriptive names than <code>recvInt</code> and <code>strBuffer</code>. I'd consider something like <code>socket_error</code> and just <code>buffer</code> respectively (odd how removing part of the latter name actually makes the result <em>more</em> meaningful, but there it is).</p>\n\n<p>I'd also like to see the code put into relevant name spaces. For example, those parts that relate to IP in general (e.g., IP addresses) could be an an <code>IP</code> namespace. Those parts specific to <code>TCP</code> or <code>UDP</code> would go in that namespace (which would itself be inside the IP namespace, since UDP and TCP are both IP protocols).</p>\n\n<p>Code might look something like this:</p>\n\n<pre><code>#ifndef SOCK2_INCLUDED_\n#define SOCK2_INCLUDED_\n\n#include <string>\n#include <iostream>\n#include <winsock2.h>\n#include <algorithm>\n\n#pragma comment(lib, \"ws2_32.lib\")\n\nnamespace IP {\nstruct socket_user { \n WSADATA data;\n socket_user() {\n WSAStartup(MAKEWORD(2, 2), &data);\n }\n ~socket_user() { \n WSACleanup();\n }\n};\n\nclass address {\n socket_user u;\n struct sockaddr_in dest;\n struct in_addr addr;\n\n hostent *lookup(std::string const &hostname) { \n hostent *host;\n\n if (isdigit(hostname[0])) {\n addr.s_addr = inet_addr(hostname.c_str());\n host = gethostbyaddr((char const *)&addr, sizeof(addr), AF_INET);\n }\n else \n host = gethostbyname(hostname.c_str());\n return host;\n }\n\npublic:\n\n address(std::string const &hostname, short port=80) {\n hostent *host = lookup(hostname);\n\n dest.sin_family = AF_INET;\n dest.sin_port = htons(port);\n\n addr.S_un.S_un_b.s_b1 = host->h_addr_list[0][0];\n addr.S_un.S_un_b.s_b2 = host->h_addr_list[0][1];\n addr.S_un.S_un_b.s_b3 = host->h_addr_list[0][2];\n addr.S_un.S_un_b.s_b4 = host->h_addr_list[0][3];\n dest.sin_addr = addr;\n }\n\n address(unsigned char b0, unsigned char b1, unsigned char b2, unsigned char b3, short port)\n {\n addr.S_un.S_un_b.s_b1 = b0;\n addr.S_un.S_un_b.s_b2 = b1;\n addr.S_un.S_un_b.s_b3 = b2;\n addr.S_un.S_un_b.s_b4 = b3;\n dest.sin_family = AF_INET;\n dest.sin_port = htons(port);\n dest.sin_addr = addr;\n }\n\n operator SOCKADDR *() const { return (SOCKADDR *)&dest; }\n\n size_t size() const { return sizeof(dest); }\n\n friend std::ostream &operator<<(std::ostream &os, address const &a) {\n return os << (short)a.addr.S_un.S_un_b.s_b1\n << \".\" << (short)a.addr.S_un.S_un_b.s_b2\n << \".\" << (short)a.addr.S_un.S_un_b.s_b3\n << \".\" << (short)a.addr.S_un.S_un_b.s_b4;\n }\n};\n\nnamespace UDP { \nclass socket { \n SOCKET s;\n socket_user u;\npublic:\n socket() : s(::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) {}\n\n int setopt(int option, char const *val=NULL, int len = 0) {\n return setsockopt(s, SOL_SOCKET, option, val, len);\n }\n\n template <class T>\n int setopt(int option, T val) {\n return setsockopt(s, SOL_SOCKET, option, (char *) &val, sizeof(val));\n }\n\n template <class T>\n int send(T const &t, address const &a) { \n return sendto(s, (char *)&t, sizeof(t), 0, a, a.size());\n }\n\n template <class T>\n void read(address const &a, T &buffer) {\n connect(s, a, a.size());\n recv(s, (char *)&buffer, sizeof(buffer), 0);\n }\n\n ~socket() { closesocket(s); }\n};\n}\n\nnamespace TCP {\nclass socket { \n socket_user u;\n SOCKET s;\n address a;\n bool connected;\n\n void connect() { \n if (connected) \n return;\n ::connect(s, a, a.size()); \n connected = true; \n }\n\n void disconnect() {\n closesocket(s);\n connected = false;\n }\n\npublic:\n socket(address const &a_) \n : s(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)), a(a_), connected(false) \n {\n connect();\n }\n\n int send(std::string const &str) {\n return ::send(s, str.data(), str.size(), 0);\n }\n\n int read(void *buffer, size_t size) { \n return ::recv(s, (char *)buffer, size, 0);\n }\n\n template <class T>\n int read(T &b) {\n return ::recv(s, (char *) &b, sizeof(b), 0);\n }\n\n ~socket() { closesocket(s); }\n};\n}\n\n}\n\n#endif\n</code></pre>\n\n<p>For the moment, I've only included IP and UDP. TCP would be similar, but would (obviously enough) create a connection-oriented TCP socket. To get an idea of what code using this would look like, let's consider a small utility to retrieve and display the time from a time server. To show both TCP and UDP sockets, I'll include two versions: one using the RFC 868 time protocol (which uses TCP), the other using the RFC 4330 SNTP protocol, which uses UDP. Note that for real use, the latter is strongly preferred (UDP imposes a great deal less overhead, and the SNTP packet format supports much more accurate results as well).</p>\n\n<pre><code>#include \"sock2.h\"\n#include <time.h>\n\n#if RFC_868\n// TIME (RFC 868) version\nint main(){\n IP::address a(\"time-c.nist.gov\", 37);\n\n IP::TCP::socket s(a);\n DWORD t;\n s.read(t);\n time_t now = htonl(t) - 2208988800L;\n struct tm *n = localtime(&now);\n std::cout << n->tm_year + 1900 << \"/\" << n->tm_mon << \"/\" << n->tm_mday\n << \"\\t\" << n->tm_hour << \":\" << n->tm_min << \":\" << n->tm_sec << \"\\n\";\n}\n\n#else\n// SNTP (RFC 4330) version\nstruct ntp_packet {\n // conversion from NTP epoch to Unix/Windows epoch (midnight jan 1, 1900 to midnight jan 1, 1970).\n static const int epoch = (86400U * (365U * 70U + 17U));\n static const int port = 123;\n static const int timeout = 6000;\n\n unsigned char mode_vn_li;\n unsigned char stratum;\n char poll;\n char precision;\n\n unsigned long root_delay;\n unsigned long root_dispersion;\n unsigned long reference_identifier;\n unsigned long reference_timestamp_secs;\n unsigned long reference_timestamp_fraq;\n unsigned long originate_timestamp_secs;\n unsigned long originate_timestamp_fraq;\n unsigned long receive_timestamp_seqs;\n unsigned long receive_timestamp_fraq;\n unsigned long transmit_timestamp_secs;\n unsigned long transmit_timestamp_fraq;\n\n ntp_packet() {\n memset(this, 0, sizeof(*this));\n mode_vn_li = (4 << 3) | 3;\n originate_timestamp_secs = htonl(time(0) + epoch);\n }\n\n operator time_t() { return ntohl(transmit_timestamp_secs) - epoch; }\n};\n\nint main() {\n IP::address a(\"time-c.nist.gov\", ntp_packet::port);\n IP::UDP::socket s;\n\n int timeout = ntp_packet::timeout;\n s.setopt(SO_RCVTIMEO, timeout);\n\n ntp_packet packet;\n s.send(packet, a);\n s.read(a, packet);\n time_t now = (time_t) packet;\n struct tm *n = localtime(&now);\n std::cout << n->tm_year + 1900 << \"/\" << n->tm_mon+1 << \"/\" << n->tm_mday\n << \"\\t\" << n->tm_hour << \":\" << n->tm_min << \":\" << n->tm_sec << \"\\n\";\n}\n\n#endif\n</code></pre>\n\n<p>In both cases, the overhead imposed by the socket interface is fairly minimal. In fact, the majority of the space is simply for the declaration of the fields in the SNTP packet. I suppose that could be reduced, but it hardly seems worthwhile. Note that although we ignore most of these in SNTP, they're actually used in NTP, so the server expects the packet you send to include all the fields, even though we just set most of them to zeros.</p>\n\n<p>A few notes: the SNTP code probably has at least some degree of fragility. In theory the compiler could insert arbitrary padding between the fields, so what we see comes out misaligned. In fact, doing so would be quite unusual--the packet format is designed so all the 32-bit fields are aligned to 32-bit boundaries, so the compiler won't normally insert extra padding between the fields.</p>\n\n<p>These also assume that the <code>time_t</code> for the computer is based on an epoch of midnight, 1 Jan 1970. That's pretty common (used by both Windows and Linux), but not strictly required by standard C++ (though if memory serves, it <em>is</em> required by Posix).</p>\n\n<p>This also depends on the <code>ntp_packet</code> being a standard layout class--i.e., since it doesn't contain any virtual functions or anything like that, it can be written to like a POD (but since it has a ctor, it's not technically a POD). <code>Standard layout</code> is new with C++11, so theoretically it could break on older compilers. Again, likelihood of actual breakage is quite low in practice (actually, I don't know of any compiler it will break with, though there are obviously quite a few with which I haven't tested).</p>\n\n<p>Note, however, that those both apply only to the SNTP implementation, not to the actual sockets code. Also note the fairly minimal degree of overhead imposed by using sockets this way. We basically define an address object, open a socket, and read/write our data.</p>\n\n<p>Also note the use of the template member functions for reading and writing data, as well as setting socket options (I've set the timeout on the UDP socket to demonstrate the latter). These simplify client code (no need to pass buffer sizes) as well as improving safety (no chance of accidentally passing the wrong size and overwriting a buffer). </p>\n\n<p>So, some classes for sockets, and functioning RFC 868 and 4330 clients, with the longer of the two clients still only using 7 lines of code devoted to sockets. Of course, these <em>are</em> pretty simple protocols. Implementing things like WebSockets would add quite a be more code and complexity.</p>\n\n<p>As a final note: although it's not nearly as elaborate in many ways, some might note that this code bears some resemblance to Boost ASIO, especially in terms of naming. That wasn't exactly intentional, but was a result of (I'd guess) similar thinking processes. For servers or clients that aren't as simple as the ones I've shown here, I'd give serious consideration to using ASIO instead of hand-rolling something like this. This is all right for simple tasks like I've shown here; if you need much more than that, ASIO is almost certainly a better choice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T05:02:43.170",
"Id": "80976",
"Score": "0",
"body": "thanks but I don't get increase the buffer size can you explan move in code. because when I read about it on internet it confuse me ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:43:54.580",
"Id": "46354",
"ParentId": "46350",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "46354",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:43:24.940",
"Id": "46350",
"Score": "14",
"Tags": [
"c++",
"windows",
"socket"
],
"Title": "First socket class"
} | 46350 |
<p>I find myself using a lot of <code>.find</code> functions within what I'm developing. The reason being that I need to run this same function on a TON of different characters eventually, and the easiest way I could find to do this was make appropriate sections <code>classes</code> and wrap each character in their respective <code>ID</code>.</p>
<p>Is using <code>.find</code> a ton (to only target the classes within the <code>#characterId</code>) considered bad practice?</p>
<h3>JS Fiddle Example: <a href="http://jsfiddle.net/hgwNU/6/" rel="noreferrer">http://jsfiddle.net/hgwNU/6/</a></h3>
<h3>Example Script:</h3>
<p>(<code>x</code> is the internal <code>javascript object</code>, where <code>y</code> is the <code>DOM ID</code> for what to target)</p>
<pre><code>function updateDom(x,y){
if(x.pc < 1 || x.speed >= 4){
y.find('.addSpeed').attr('disabled', 'disabled');
}
if(x.speed <= 1){
y.find('.remSpeed').attr('disabled', 'disabled');
}
if(x.speed > 1){
y.find('.remSpeed').removeAttr('disabled');
}
if(x.speed < 4 && x.pc > 0){
y.find('.addSpeed').removeAttr('disabled');
}
y.find(":checkbox").each(function() {
if($(this).data('pc') > x.pc && $(this).prop('checked')==false){
$(this).attr('disabled', 'disabled');
} else if ($(this).data('pc') <= x.pc) {
$(this).removeAttr('disabled');
}
});
for (var key in x) {
y.find('#' + key).text(x[key]);
};
}
</code></pre>
<p><strong>Called with:</strong></p>
<pre><code>updatePlayer(bulk,$('#bulkUi'));
</code></pre>
<h3>JS Fiddle Example: <a href="http://jsfiddle.net/hgwNU/6/" rel="noreferrer">http://jsfiddle.net/hgwNU/6/</a></h3>
<p>I suppose I'm just curious if I'm off to a good start for how to manipulate both the <code>GUI</code> and the internal <code>object</code> effectively, easily, quickly and repeatedly. Looking for best practices if anybody has any feedback thus far.</p>
| [] | [
{
"body": "<p>The most immediate problems:</p>\n\n<ul>\n<li><p>Use better variable names than <code>x</code> and <code>y</code>. It's almost unreadable this way. If one of them is the player data object and the other one a jQuery DOM object, why not name them <code>player</code> and <code>dom</code> respectively.</p></li>\n<li><p>Values of HTML <code>id</code> attribute should be unique across the whole page. When you have several player boxes on one page, you're better off using classes than ID-s.</p></li>\n</ul>\n\n<p>If you're planning to place <em>a ton</em> of these characters on a page, you might be better of using event delegation, instead of binding the event handlers on each and every element - see the jQuery.on() function reference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:20:00.910",
"Id": "81067",
"Score": "0",
"body": "Regarding the `id` attribute, that was a mistake I corrected right after posting this.\n\nGood point for the `parameter` names. Just tried to make it quick and dirty :-P.\n\nAnd this paragraph seems to indicate that [doing it this way is ideal...?](https://api.jquery.com/on/#event-performance)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T09:54:30.873",
"Id": "46360",
"ParentId": "46352",
"Score": "4"
}
},
{
"body": "<p>It is much faster to look up items by id (I assume a hash table because sometimes ids are defacto duplicate) than searching for a class in a collection (which is what you force the browser to do when you select by class). This is specially so in old browsers like some old versions of IE.</p>\n\n<p>Also, you should use else's (removing in turn redundant if's), and group the if's : </p>\n\n<p>I would place the simpler if's at the top of the code (those who only depend on variable):</p>\n\n<pre><code>if(x.speed > 1){\n y.find('.remSpeed').removeAttr('disabled');\n}\nelse{\n y.find('.remSpeed').attr('disabled', 'disabled');\n}\n</code></pre>\n\n<p>in fact i would separate the find from the actually work on the attribute:</p>\n\n<pre><code>var remSpeed = y.find('.remSpeed');\nif(x.speed > 1){\n remSpeed('disabled');\n}\nelse{\n remSpeed('disabled', 'disabled');\n}\n\n\nvar addSpeed = y.find('.addSpeed');\nif(x.pc < 1 || x.speed >= 4){\n addSpeed.attr('disabled', 'disabled');\n}\nelse{\n addSpeed.removeAttr('disabled');\n}\n</code></pre>\n\n<p>You could also simplify the other set of conditionals:</p>\n\n<pre><code> if($(this).data('pc') > x.pc){\n if ($(this).prop('checked')==false)\n {\n $(this).attr('disabled', 'disabled');\n }\n }\n else\n {\n $(this).removeAttr('disabled');\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:20:47.200",
"Id": "46365",
"ParentId": "46352",
"Score": "4"
}
},
{
"body": "<p>Personally instead of using <code>.find</code> I prefer passing <code>context</code> to the jQuery selector like this;</p>\n\n<pre><code>$('.remSpeed', y);\n</code></pre>\n\n<p>Which will find all instances of <code>.remSpeed</code> that are within the element <code>y</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:57:40.820",
"Id": "81353",
"Score": "0",
"body": "Doesn't this only work for direct descendents?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:34:37.100",
"Id": "81396",
"Score": "0",
"body": "@NicholasHazel Nope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:37:13.003",
"Id": "81401",
"Score": "0",
"body": "Thanks for the answer :-) Is there a performance increase doing it this way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:42:01.613",
"Id": "81404",
"Score": "0",
"body": "It appears the [`find()` method is slightly faster](http://jsperf.com/jquery-find-vs-context-2). But I still get around 600k operations per second for the context selector, so hardly noticeable. I use context because I find it easier to read and understand, rather than for performance reasons."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:33:23.997",
"Id": "46367",
"ParentId": "46352",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:29:05.060",
"Id": "46352",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html",
"classes",
"dom"
],
"Title": "New Game - Am I going down the right path for DOM manipulation?"
} | 46352 |
<p>I am using Unity3D and I made a super simply pooling system to reuse a specific object. My only concern is I am not sure if I am doing it the best possible way. If I were doing this in C++ there would be a bunch of pointers and be passing pointers to the objects.</p>
<p>Now in C# I understand many things are hidden as pointers. So, I am unclear whether the things if I should just return things, thinking it is by value or do it by reference in C#'s way of using 'ref'.</p>
<p>What I mainly want to achieve is preventing me from duplicating the objects, but rather passing the memory address of where my objects are.</p>
<p>Hoping someone could provide some insight. </p>
<p>Here is the code: (probably most interest would be in <code>GetObject</code> and <code>ReturnObject</code> methods</p>
<pre><code>using UnityEngine;
using System.Collections;
public class PoolingSystem : MonoBehaviour
{
[SerializeField]
// Keeping track of which units to create and put into a pool
private GameObject _object;
// Root container for the spawned objects given in the inspector
private GameObject _root;
[SerializeField]
// Number of objects to keep track for in the pool
private int _num_obj;
// Number of objects currently in use
private int _num_used;
// Keep track of _pooled objects
private GameObject[] _pool;
// Keep track of which index in the _pool is being used
private bool[] _in_use;
// Default vector to move objects away from the scene
private Vector3 _default;
/// <summary>
/// Gets the object in which the pooling system is focusing on
/// </summary>
/// <value>The object.</value>
public GameObject pool_obj
{
get { return _object; }
}
/// <summary>
/// Gets the total amount of objects this pooling system should restrict to.
/// </summary>
/// <value>The total.</value>
public int total
{
get { return _num_obj; }
}
/// <summary>
/// Gets the current number of objects in use by the pool system for the specific object
/// </summary>
/// <value>The number_in_use.</value>
public int number_in_use
{
get { return _num_used; }
}
void Awake ()
{
_pool = new GameObject[_num_obj];
_in_use = new bool[_num_obj];
_root = new GameObject();
_root.name = string.Format("PoolingSystem: {0}", _object.name);
_num_used = 0;
_default = new Vector3(9999,9999,9999);
for(int i=0;i<_num_obj;++i)
{
// Create specified object
_pool [i] = Instantiate(_object, Vector3.zero, Quaternion.identity) as GameObject;
// Mark object not in use
_in_use[i] = false;
// Parent the pooled objects into root
_pool[i].transform.parent = _root.transform;
// Turned off specific components of the object
Shutoff(ref _pool[i]);
}
}
// Just some components to turn on
void ReadyToDeploy(ref GameObject unit, Vector3 location)
{
unit.SetActive(true);
unit.transform.position = location;
}
// Just some components to turn off
void Shutoff(ref GameObject unit)
{
unit.transform.position = _default;
unit.SetActive(false);
}
/// <summary>
/// Gets an object of the desired type. If there is an object to spare return the object, else return null.
/// </summary>
/// <returns>The object.</returns>
/// <param name="location">Location.</param>
public GameObject GetObject(Vector3 location)
{
GameObject obj = null;
for(int i = 0; i < _num_obj; ++i)
{
if(_in_use[i] == false)
{
obj = _pool[i];
_in_use[i] = true;
_num_used += 1;
ReadyToDeploy (ref obj, location);
i = _num_obj;
}
}
if(obj == null)
{
Debug.LogWarning(string.Format("PoolSystem: object -> {0} has met max limit.", obj));
}
return obj;
}
/// <summary>
/// Returns the object back to the pooling system. Returns true if it was sucessful in putting it back, else false.
/// </summary>
/// <returns><c>true</c>, if object was returned, <c>false</c> otherwise.</returns>
/// <param name="obj">Object.</param>
public bool ReturnObject(GameObject obj)
{
bool recieved = false;
if(obj.tag == this._object.tag)
{
for(int i = 0; i < _num_obj; i++)
{
if(_in_use[i])
{
_pool[i] = obj;
Shutoff (ref _pool[i]);
_in_use[i] = false;
_num_used -= 1;
i = _num_obj;
recieved = true;
}
}
}
else
{
Debug.LogError(string.Format("Parameter: {0} is type {1} which is not the same type as '{1}'", obj.name, obj.tag, this._object.tag));
}
return recieved;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:25:14.130",
"Id": "84278",
"Score": "0",
"body": "Off topic and entirely optional, but I recommend using Microsoft's C# coding style guidelines for ease of reading for both yourself and other programmers: http://msdn.microsoft.com/en-us/library/ff926074.aspx and http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:31:32.150",
"Id": "84322",
"Score": "0",
"body": "Minor thing: `recieved` is misspelled. It should be `received`."
}
] | [
{
"body": "<p>Classes, such as your <code>GameObject</code> are passed by reference (i.e. as a pointer) by default. No duplication happens and you do not need a keyword for that. C# handles it all for you.</p>\n\n<p>Structs and primitive types such as <code>Vector3</code> or <code>int</code> are value types which are passed by value by default and are therefore copied when you pass them into functions.</p>\n\n<p>Therefore you can remove the <code>ByRef</code> keywords whenever you're passing your pooled object around for clarity at the least, and do not have to worry about duplicated objects unless you're passing a struct (which are meant to be small anyway) or a primitive type (which again, should be small).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:23:18.013",
"Id": "48037",
"ParentId": "46353",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:30:03.673",
"Id": "46353",
"Score": "3",
"Tags": [
"c#",
"unity3d"
],
"Title": "Pooling System: is it worth improving or not for a simple implementation?"
} | 46353 |
<p>When the app is run on an iPhone or simulator, tapping the screen spawns a dog class and displays an image of the dog.</p>
<p>I'd like comments, issues, whatever. Is this a decent first Objective-C project, and can others learn from it?</p>
<p>The code is meant to demonstrate Objective-C, Cocoa and UIKit.</p>
<p>Primary files in the project:</p>
<h2>Protocols</h2>
<p><strong>GKLiving.h</strong></p>
<pre><code>//
// GKLiving.h
// SampleApp
//
// Cocoa foundation classes
#import <Foundation/Foundation.h>
#pragma mark - Defines
#pragma mark - The Living protocol of the GK namespace
@protocol GKLiving <NSObject>
#pragma mark - Mandatory methods
#pragma mark - Optional methods
@optional
@end
</code></pre>
<p><strong>GKAnimalia.h</strong></p>
<pre><code>//
// GKAnimalia.h
// SampleApp
//
// Cocoa foundation classes
#import <Foundation/Foundation.h>
#import "GKLiving.h"
#pragma mark - Defines
#pragma mark - The Animalia protocol of the GK namespace
@protocol GKAnimalia <GKLiving>
#pragma mark - Mandatory methods
+ (NSString *)stringRepresentationOfBreed;
#pragma mark - Optional methods
@optional
@end
</code></pre>
<p><strong>GKCanidae.h</strong></p>
<pre><code>//
// GKCanidae.h
// SampleApp
//
// Cocoa foundation classes
#import <Foundation/Foundation.h>
#pragma mark - Defines
#define GKCANIDAE_UNKNOWN_BREED @"Mutt"
#pragma mark - The Canidae protocol of the GK namespace
@protocol GKCanidae <GKAnimalia>
#pragma mark - Mandatory methods
// Note that the "+" makes this a class-level method (it is
// not an instance method).
+ (NSString *)says;
#pragma mark - Optional methods
@optional
@end
</code></pre>
<h2>Dog Classes</h2>
<p><strong>GKDog.h</strong></p>
<pre><code>//
// GKDog.h
// SampleApp
//
// Cocoa foundation classes
#import <Foundation/Foundation.h>
// Protocols
#import "GKAnimalia.h"
#import "GKCanidae.h"
#pragma mark - Defines
#define GKDOG_PRIVATE_THOUGHTS @"I love you"
#define GKDOG_SOUND @"Arf"
#define GKDOG_PLACEHOLDER_PATH \
[[NSBundle mainBundle] pathForResource:@"how-to-draw-a-dog-4" ofType:@"jpg"]
#pragma mark - The Dog class of the GK namespace
// 1. No namespaces in Objective-C, so class prefixes are used instead.
// The "NS" prefix (for NextStep, I assume) is pretty common.
// 2. This class conforms to the GKCanidae protocol.
// For a truer take on protocol naming conventions, see this article:
// http://stackoverflow.com/questions/7483813/protocol-naming-in-objective-c
//
@interface GKDog : NSObject <GKCanidae>
#pragma mark - Properties with getters/setters
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *breed;
@property (assign, nonatomic) NSInteger age;
// A cute picture of the dog
@property (strong, nonatomic) NSString *pictureUrlString;
#pragma mark - Instance methods
- (void)becomeMutt;
@end
</code></pre>
<p><strong>GKYorkshireTerrier.h</strong></p>
<pre><code>//
// GKYorkshireTerrier.h
// SampleApp
//
#import "GKDog.h"
#pragma mark - Defines
#define GKYORKSHIRETERRIER_BREED @"Yorkie"
#define GKYORKSHIRETERRIER_PICTURE_URL @"http://www.acuteaday.com/blog/wp-content/uploads/2010/12/yorkie-puppy-091210.jpg"
#pragma mark - The YorkshireTerrier class of the GK namespace
@interface GKYorkshireTerrier : GKDog
@end
</code></pre>
<p><strong>GKYorkshireTerrier.m</strong></p>
<pre><code>//
// GKYorkshireTerrier.m
// SampleApp
//
#import "GKYorkshireTerrier.h"
@implementation GKYorkshireTerrier
#pragma mark - Class methods from GKAnimalia
+ (NSString *)stringRepresentationOfBreed
{
return GKYORKSHIRETERRIER_BREED;
}
#pragma mark - Initializers
- (instancetype)init
{
self = [super init];
if (self)
{
self.breed = [GKYorkshireTerrier stringRepresentationOfBreed];
self.pictureUrlString = GKYORKSHIRETERRIER_PICTURE_URL;
}
return self;
}
- (instancetype)initWithName:(NSString *)name
{
self = [self init];
if (self)
{
self.name = name;
}
return self;
}
- (instancetype)initWithName:(NSString *)name andAge:(NSInteger)age
{
self = [self initWithName:name];
if (self)
{
self.age = age;
}
return self;
}
@end
</code></pre>
<h2>Main Dog Spawning</h2>
<p><strong>GKDogSpawner.h</strong></p>
<pre><code>//
// GKDogSpawner.h
// SampleApp
//
// Cocoa foundation classes
#import <Foundation/Foundation.h>
#pragma mark - Defines
#define GKDOGSPAWNER_IMAGE_MIN_X 0.0f
#define GKDOGSPAWNER_IMAGE_MAX_X ([UIScreen mainScreen].bounds.size.width - GKDOGSPAWNER_IMAGE_WIDTH)
#define GKDOGSPAWNER_IMAGE_MIN_Y 0.0f
#define GKDOGSPAWNER_IMAGE_MAX_Y ([UIScreen mainScreen].bounds.size.height - GKDOGSPAWNER_IMAGE_HEIGHT)
#define GKDOGSPAWNER_IMAGE_WIDTH 64.0f
#define GKDOGSPAWNER_IMAGE_HEIGHT 64.0f
#pragma mark - The DogSpawner class of the GK namespace
@interface GKDogSpawner : NSObject
#pragma mark - Instance methods
- (void)spawnDogWithClassNamed:(NSString *)className onView:(UIView *)targetView;
@end
</code></pre>
<p><strong>GKDogSpawner.m</strong></p>
<pre><code>//
// GKDogSpawner.m
// SampleApp
//
#import "GKDogSpawner.h"
#import "GKDog.h"
#import "GKYorkshireTerrier.h"
#import "GKRandomNumber.h"
// AFNetworking
// https://github.com/AFNetworking/AFNetworking
#import "UIImageView+AFNetworking.h"
@implementation GKDogSpawner
#pragma mark - Instance methods
- (void)spawnDogWithClassNamed:(NSString *)className onView:(UIView *)targetView
{
// Create a dog instance of the specified class
Class dogMetaClass = NSClassFromString(className);
GKDog *newDog = [[dogMetaClass alloc] init];
// Just for fun...
if ([newDog isKindOfClass:[GKYorkshireTerrier class]])
{
NSLog(@"Whoa, you spawned a %@! They typically say %@ regularly.", [newDog breed], [dogMetaClass says]);
}
// Create a UIImage from the placeholder's local path
UIImage *placeholderImage = [UIImage imageWithContentsOfFile:GKDOG_PLACEHOLDER_PATH];
// Create an NSURL object from the picture's URL string
NSURL *pictureUrl = [NSURL URLWithString:[newDog pictureUrlString]];
// -- Create a UIImageView and populate its image from the picture URL.
// -- While it's loading, the placeholder will be shown.
// -- The -setImageWithURL:placeholderImage: method is from the "UIImageView+AFNetworking"
// category on UIImageView; it provides plugin functionality that is not native to the base
// UIImageView class.
CGFloat x = [GKRandomNumber floatFrom:GKDOGSPAWNER_IMAGE_MIN_X to:GKDOGSPAWNER_IMAGE_MAX_X];
CGFloat y = [GKRandomNumber floatFrom:GKDOGSPAWNER_IMAGE_MIN_Y to:GKDOGSPAWNER_IMAGE_MAX_Y];
CGRect dogImageFrame = CGRectMake(x, y, GKDOGSPAWNER_IMAGE_WIDTH, GKDOGSPAWNER_IMAGE_HEIGHT);
UIImageView *dogImageView = [[UIImageView alloc] initWithFrame:dogImageFrame];
[dogImageView setImageWithURL:pictureUrl placeholderImage:placeholderImage];
// Add the dog image view as a child of the target view. This will make the image visible.
[targetView addSubview:dogImageView];
}
@end
</code></pre>
<h1>Gesture Recognizers</h1>
<p><strong>GKTapHandler.h</strong></p>
<pre><code>//
// GKTapHandler.h
// SampleApp
//
// Cocoa foundation classes
#import <Foundation/Foundation.h>
#pragma mark - Defines
#pragma mark - The TapHandler class of the GK namespace
@interface GKTapHandler : NSObject <UIGestureRecognizerDelegate>
#pragma mark - Instance methods
// Use "IBAction" to link methods to the Storyboard
- (IBAction)handleTouch:(id)sender;
@end
</code></pre>
<p><strong>GKTapHandler.m</strong></p>
<pre><code>//
// GKTapHandler.m
// SampleApp
//
#import "GKTapHandler.h"
#import "GKDogSpawner.h"
#import "GKRandomNumber.h"
@implementation GKTapHandler
#pragma mark - Instance variables
{
GKDogSpawner *_dogSpawner;
NSArray *_dogTypes;
}
#pragma mark - Initializers
- (instancetype)init
{
self = [super init];
if (self)
{
// Initialize the dog spawner
self->_dogSpawner = [[GKDogSpawner alloc] init];
// Initialize and populate the dog types. Note the nil guard value.
self->_dogTypes = [NSArray arrayWithObjects:
@"GKLhasaApso",
@"GKYorkshireTerrier",
nil];
}
return self;
}
#pragma mark - Instance methods
- (IBAction)handleTouch:(id)sender
{
NSUInteger totalDogTypes = self->_dogTypes.count;
NSUInteger randomDogTypeIndex = [GKRandomNumber unsignedIntFrom:0 to:totalDogTypes];
NSString *dogType = [self->_dogTypes objectAtIndex:randomDogTypeIndex];
id applicationDelegate = [[UIApplication sharedApplication] delegate];
UIView *targetView = [applicationDelegate window].rootViewController.view;
[self->_dogSpawner spawnDogWithClassNamed:dogType onView:targetView];
}
@end
</code></pre>
<h2>Utility Classes</h2>
<p><strong>GKRandomNumber.h</strong></p>
<pre><code>//
// GKRandomNumber.h
// SampleApp
//
// Cocoa foundation classes
#import <Foundation/Foundation.h>
#pragma mark - Defines
#pragma mark - The RandomNumber class of the GK namespace
@interface GKRandomNumber : NSObject
#pragma mark - Class methods
+ (NSUInteger)unsignedIntFrom:(NSUInteger)min to:(NSUInteger)max;
+ (float)floatFrom:(NSUInteger)min to:(NSUInteger)max;
@end
</code></pre>
<p><strong>GKRandomNumber.m</strong></p>
<pre><code>//
// GKRandomNumber.m
// SampleApp
//
#import "GKRandomNumber.h"
// Required for arc4random_uniform
#include <stdlib.h>
@implementation GKRandomNumber
#pragma mark - Class methods
+ (NSUInteger)unsignedIntFrom:(NSUInteger)min to:(NSUInteger)max
{
NSUInteger range = max - min;
u_int32_t generatedInteger = arc4random_uniform((u_int32_t)range);
NSUInteger result = generatedInteger + min;
return result;
}
+ (float)floatFrom:(NSUInteger)min to:(NSUInteger)max
{
return (float)[self unsignedIntFrom:min to:max];
}
@end
</code></pre>
<h2>View Controllers</h2>
<p><strong>GKViewController.h</strong></p>
<pre><code>//
// GKViewController.h
// SampleApp
//
// Main library for the iOS user interface
#import <UIKit/UIKit.h>
#pragma mark - Defines
#pragma mark - The ViewController class of the GK namespace
@interface GKViewController : UIViewController
// Use "IBOutlet" to link properties to the Storyboard
@property (weak, nonatomic) IBOutlet UITapGestureRecognizer *tapRecognizer;
@end
</code></pre>
| [] | [
{
"body": "<p>Because this question is so, so large, I won't get into all the specifics of everything I see. I will point out some things, and provide some examples from one file or another, and as you work through my answer, you should work through your project to find all the other instances of an example I point out.</p>\n<p>I will start with a simple answer to the topic question:</p>\n<h1>Is this a decent first Objective-C project, and can others learn from it?</h1>\n<p>Simply, yes. I haven't built and compiled and tried running this, but I assume you have. Certainly anyone whose Objective-C knowledge is below that of this project would be able to learn from it. And it's fairly well organized, clean, etc, so I'll pass it as decent as well.</p>\n<p>But in the first few paragraphs, you talk about wanting for a project to serve as an example of Objective-C "standard practice". A perfectly fine want--but let's be clear, this project isn't that.</p>\n<p>Also, while I did say that someone could learn from this project, I think the audience of people who would take the time to learn from this is fairly narrow. At least in my personal experience as a programmer, I learn best when adding small chunks of knowledge at a time. To me, learning programming is like having a rubber band ball. It's really hard to get that ball started. But once you do, all you have to do to keep it going is snap one more rubber band on here and there.</p>\n<p>Your project is, in my opinion, a bit too complex for Objective-C and iOS beginners and covers far too much ground. And the project contains some problems that if a more advanced Objective-C user "learned" as the way to do it, he wouldn't have benefited all that much.</p>\n<p>So, now that that's out of the way, I'll start at the top, and work my way down.</p>\n<p>It is likely that this answer my be broken into multiple answers or will receive future edits. Basically, treat this as an answer in progress, as there's quite a few things here I want to address, and I won't be able to address it all in one sitting--you didn't write this whole project in one sitting, did you?</p>\n<hr />\n<p>First of all, some of the problems that are consistent throughout the entirety of the project:</p>\n<p>EDIT: As a note here, I'm pointing to sections of your code you've marked off with a <code>#pragma mark</code>. I wanted to come back and edit in some clarity. The <code>#pragma mark</code> themselves are for the most part okay. These are basically just comments with some special features, and using <code>#pragma mark</code>s to mark off sections is great. I'm mostly discussing the content in each of these sections.</p>\n<hr />\n<h1><code>#pragma mark - Namespace ...</code></h1>\n<pre><code>// 1. No namespaces in Objective-C, so class prefixes are used instead.\n// The "NS" prefix (for NextStep, I assume) is pretty common.\n</code></pre>\n<p>Correct and correct. "NS" does stand for NextStep. In iOS development, most of the Foundation classes you'll use are prefixed with NS or UI. You'll run into some other common ones too like CG, AF, etc.</p>\n<p>But more importantly, you're correct about the fact that there are no namespaces in Objective-C. As such, a project hoping to serve as the "standard practice" for Objective-C shouldn't have a <code>#pragma mark - Namespace</code> in every single header file in its project. True Objective-C projects should have this no where. Best case scenario, you might see it in an Objective-C++ project.</p>\n<p>It is perfectly fine for a programmer coming from a non-Objective-C background to do something like this if it helps the organization of the project because he's used to thinking of it in some other way, but it's definitely not "standard practice".</p>\n<hr />\n<h1><code>#pragma mark - Defines</code></h1>\n<p>You've included this line in most of the files. The fact of the matter is, you shouldn't be using <code>#define</code> so often that it's a regularly occurring section in your code.</p>\n<p>Certainly, you shouldn't be using <code>#define</code> simply for constant values. That's what the <code>const</code> keyword is for. And if you need to declare a constant value in a <code>.h</code> file so it can be seen by multiple files, well, that's what the <code>extern</code> keyword is for.</p>\n<p>So for example this:</p>\n<pre><code>#define GKDOGSPAWNER_IMAGE_MIN_X 0.0f\n</code></pre>\n<p>Should be replaced with this:</p>\n<pre><code>extern CGFloat const DKDOGSPAWNER_IMAGE_MIN_X;\n</code></pre>\n<p>in the <code>.h</code>, and then define it in the <code>.m</code> of the same file:</p>\n<pre><code>CGFloat const DKDOGSPAWNER_IMAGE_MIN_X = 0.0f;\n</code></pre>\n<p>Applying this thinking to all of your defines eliminates all but 3 of the <code>#defines</code>.</p>\n<p>The last three could also potentially be eliminated via functions. For example:</p>\n<pre><code>#define GKDOGSPAWNER_IMAGE_MAX_X ([UIScreen mainScreen].bounds.size.width - GKDOGSPAWNER_IMAGE_WIDTH)\n</code></pre>\n<p>could be replaced with:</p>\n<pre><code>CGFloat GKDOGSPAWNER_IMAGE_MAX_X();\n</code></pre>\n<p>in the <code>.h</code>, then define the function in the <code>.m</code>:</p>\n<pre><code>CGFloat GKDOGSPAWNER_IMAGE_MAX_X() {\n return ([UIScreen mainScreen].bounds.size.width - GKDOGSPAWNER_IMAGE_WIDTH);\n}\n</code></pre>\n<p>In this case though, the <code>#define</code> doesn't bother me as much.</p>\n<p>These points on <code>#define</code> aren't really even Objective-C specific. They can apply across all of the C-Based languages that support preprocessor statements (though the syntax may vary slightly from language to language).</p>\n<hr />\n<h1><code>#pragma mark - Mandatory methods</code></h1>\n<h1><code>#pragma mark - Optional methods</code></h1>\n<p>It is fine to have these <code>#pragma mark</code>s in, particularly in large protocols or just large files. But having these marks does not excuse not marking the methods with code that actually makes methods <code>required</code> or <code>optional</code>.</p>\n<p>This is something that doesn't really translate unless you're in an IDE, but a <code>#pragma mark</code> and other codes show up in different colors. In my current Xcode theme, all precompiler code (which includes <code>#pragma mark</code>) shows up as brown. Things like <code>@protocol</code>, <code>@required</code>, <code>@optional</code>, and <code>@end</code> show up as pink.</p>\n<p>So if I were to load up your code in Xcode, a quick glance at your protocols would show me the keyword <code>@required</code> never shows up. It'd be a bit confusing. Now, all methods in a protocol are by default <code>@required</code> (unless marked <code>@optional</code>), but if we're going to talk about standard practice, I am certainly of the opinion that a section of <code>@required</code> methods should be explicitly marked with the <code>@required</code> keyword. It is my personal habit to individually mark every method in a protocol so there is no mistaking the intent of any of the protocol methods. This may be a bit overboard for a "standard practice", but I certainly think the <code>@required</code> keyword belongs, for clarity.</p>\n<hr />\n<h1>GKRandomNumber.h / GKRandomNumber.m</h1>\n<p>There are a few problems I have with this class.</p>\n<p>First, it's not really a class, is it? No one should ever instantiate an object of this class, and yet they could.</p>\n<p>There are two fixes. Fix one is to use preprocessor statements to prevent instantiation and subclassing. I don't really like this fix, but it is a possibility. Preventing instantiation looks like this in the <code>.h</code> file:</p>\n<pre><code>+ (id)alloc __attribute__((unavailable("GKRandomNumber cannot be instantiated")));\n- (id)init __attribute__((unavailable("GKRandomNumber cannot be instantiated")));\n</code></pre>\n<p>But this is a little silly. Especially when the two methods in this class are so simple. We don't need a class because we don't need Objective-C style methods. We can simply use C-style functions:</p>\n<pre><code>NSUInteger randomUnsignedInt(NSUInteger min, NSUInteger max);\n</code></pre>\n<p>My second big problem with these files is that the method names don't say "random" in them--they should. The name of the file or class isn't enough. Consider <code>NSArray</code> or <code>NSString</code>, for example. Look at all their methods. If you're using an <code>NSArray</code>, you know you're dealing with an <code>NSArray</code>, but Apple says this isn't enough, and as such, all the methods look like this:</p>\n<ul>\n<li>array</li>\n<li>arrayWithArray:</li>\n<li>arrayWithContentsOfFile:</li>\n<li>arrayWithContentsOfURL:</li>\n<li>arrayWithObject:</li>\n<li>arrayWithObjects:</li>\n<li>arrayWithObjects:count:</li>\n</ul>\n<p>My third big problem with this pair of files is that you have a method for grabbing an integer in a range... but require only unsigned integers. If I want to assure a positive number, I can just assure my minimum number is greater than zero, right? Why are we dealing only with unsigned integers?</p>\n<p>Fourth, your method has no way of dealing with when the value sent for <code>max</code> is larger than the value sent for <code>min</code>. Given we're dealing with UNSIGNED INTEGERS, this will be a big, big problem. If you try to find a random number between 10 and 5, you won't get 6, 7, 8, or 9. When you find the range (5-10) using unsigned ints, you'll get underflow, and it will wrap around to some number about 5 less than whatever the max for NSUInteger is (which will depend on system). So your range will be almost the entire spectrum of unsigned ints. When you add your min back (10, not 5), you will definitely be outside the range of 5 to 10. The answer to this problem is to do things the way Apple has done. Rather than taking a starting point and an ending point, you take a starting point and a range.</p>\n<p>Fifth, you're doing a lot of unhelpful and misleading castings. The float version of your random number method doesn't really return a random float... it returns a random NSUInteger cast as a float. And your NSUInteger doesn't really return a random NSUInteger in the given range... it returns a u_int32_t cast as an NSUInteger.</p>\n<p><code>u_int32_t</code> is a typedef from C that is a 32-bit integer, no matter the operating system.</p>\n<p><code>NSInteger</code> is a typedef from Objective-C. On 32-bit systems it's a 32-bit integer. On 64-bit systems, it's a 64-bit integer.</p>\n<p><code>float</code> is a floating point number and not an integer.</p>\n<p>Again, I'm not super familiar with arc4random_uniform, and using <code>u_int32_t</code> may be a limitation of this function. But if that's the case, then your Objective-C method should reflect this. If you're using a <code>u_int32_t</code> range and getting the result from the random function as a <code>u_int32_t</code>, then the method should take <code>u_int32_t</code> arguments and return a <code>u_int32_t</code> value. If the end user of this method needs to cast it as something else, then let them, but if the internals of the method do all the actual work in some particular data type, you should probably use that data type as the return type and the argument type.</p>\n<p>And this logic applies to the <code>float</code> version of the method. To me, a method that says it returns a random float is a method that will return more than just an integer cast to a float. If I want a random whole number to use as an argument to some method that expects a floating point number, then I need to use a method to generate a random int and cast it to a float myself or generate a random float and come up with some method for zeroing out the decimals. Either way, I shouldn't be mislead by a method that claims to return a float and only returns integers cast as floats.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:05:51.127",
"Id": "81414",
"Score": "0",
"body": "Excellent feedback; I'll take in your advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:50:58.200",
"Id": "84153",
"Score": "0",
"body": "Found something interesting about const NSString values: http://stackoverflow.com/questions/6828831/sending-const-nsstring-to-parameter-of-type-nsstring-discards-qualifier"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T23:26:29.627",
"Id": "84248",
"Score": "0",
"body": "Correct. But you don't have any NSString's that I recommended `const`ing, but `NSString * const someString` would be the correct way to do it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T13:30:05.533",
"Id": "46454",
"ParentId": "46357",
"Score": "13"
}
},
{
"body": "<p>Now, given that basically all Objective-C is written to make use of Cocoa frameworks, and we're talking about programs to run on OSX or iOS, we have to discuss Apple. Apple is pretty consistent when their method naming conventions, and their way of doing things. So any conversation about Objective-C standard practice would be incomplete without a very serious conversation for the \"Apple way\". So, let's go over your project's inconsistencies with the \"Apple way\".</p>\n\n<hr>\n\n<p>First of all, your initializers. You're accessing properties through their accessor methods in your initializer methods. This is an absolute no-no in Objective-C, and <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html\">Apple explicitly states not to do this</a>. The short answer as to why is basically because it is an absolute maintenance nightmare.</p>\n\n<p>Basically, in <code>init</code>, <code>dealloc</code>, and the accessor methods themselves (should you choose to override them), you need to access the instance variable directly.</p>\n\n<hr>\n\n<p>And while we're on the topic of instance variables, can we discuss the instance variables you declare in the <code>.m</code> and access elsewhere via <code>self->_iVar</code>? I don't understand why you're doing this. I mean, I understand what this is, but I'm confused as to your inconsistency. To me, anything \"standard practice\" should certainly be consistent.</p>\n\n<p>The only reason to <code>self-></code> an instance variable is when a scoping issue is overshadowing the instance variable, and we're talking only about an instance variable that's not declare as a <code>@property</code>.</p>\n\n<p>If your intention is to make private properties for your classes, you can do this with a class category in the <code>.m</code> file:</p>\n\n<pre><code>@interface YourClass()\n\n@property (nonatomic,strong) NSString *yourIvar;\n\n@end\n\n@implementation YourClass\n// stuff\n</code></pre>\n\n<p>This is the same as declaring a property in the interface of the <code>.h</code> file, except the variable is private. Now, you can access the variable within the class via <code>self.yourIvar</code> instead of needed to do <code>self->_yourIvar</code>.</p>\n\n<p>You really shouldn't ever need to use the arrow operator in Objective-C really. It's fine to have non-property instance variables, but these should be so clearly name that you're not going to run into any scoping issues. It may be common practice to use <code>self</code> in front of every instance variable in other languages, but it's just not really done in Objective-C--it's not standard practice.</p>\n\n<p>And the biggest problem you'd run into is that Objective-C programmers that don't come from a background where they've used the dereferencing arrow will have to stop and figure out what that is and what that means... because as I've said, it's just not typically used in Objective-C.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:06:29.247",
"Id": "81415",
"Score": "0",
"body": "Thanks for the heads-up on not using property accessors in initializers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:28:13.923",
"Id": "84171",
"Score": "0",
"body": "Again with regards to using accessors in initializers, would that rule only apply to base classes within an inheritance chain?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T23:17:28.220",
"Id": "84247",
"Score": "0",
"body": "No. There is no concept of a `Final` class in Objective-C, as such, any class can technically be inherited from. The only place it would possibly be even remotely save to use an accessor would be in an `init` method with a return type defined as whatever the class is instead of `id` or `instancetype`, but I'd recommend both against using a return type other than `instancetype` and using the accessors even if you did change the return type."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:57:08.727",
"Id": "46485",
"ParentId": "46357",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "46454",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T05:51:26.463",
"Id": "46357",
"Score": "5",
"Tags": [
"objective-c",
"ios",
"cocoa"
],
"Title": "Spawning a Dog class"
} | 46357 |
<p>I'm new to C, and as an exercise I'm building 4 different factorial algorithm implementations and measuring their running time. I'm looking for this feedback, especially:</p>
<ul>
<li><p>The implementation of the factorial algorithms. Can the they be improved? Is there something you would do different? Is something wrong?</p></li>
<li><p>The implementation of the execution time measuring system. Is there a different/better way to measure function running time? Would you do something differently? Is something wrong?</p></li>
</ul>
<p>But I'm also interested in anything else you see wrong in the program. </p>
<p>The program works from the command line:</p>
<pre><code>./factorial <factorial to be calculated> <number of repetitions>
</code></pre>
<p>The program then prints the results to the console.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// =========================================================================
// Functions
// =========================================================================
// Using for loop
double iterative_for_factorial(double n) {
double acc = 1;
for (n = n; n > 0; n--) acc *= n;
return acc;
}
// Using while loop
double iterative_while_factorial(double n) {
double acc = 1;
while (n > 0) {
acc *= n;
n--;
}
return acc;
}
// Using recursion
double recursive_factorial(double n) {
if (n < 1) return 1;
return n * recursive_factorial(n-1);
}
// Using recursion and ternary operator
double recursive_ternary_factorial(double n) {
return n < 1 ? 1 : n * recursive_ternary_factorial(n - 1);
}
// =========================================================================
// Timing
// =========================================================================
// Measures the CPU time of a function executed x times
double timeIt(double n, double times, double(*f)(double)) {
clock_t start = clock();
for (double i = 0; i < times; i++) {
f(n);
}
return (clock() - start);
}
// =========================================================================
// Main()
// =========================================================================
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("\nusage: factorial <factorial to calculate> <repetitions>\n\n");
return 1;
}
double number = atof(argv[1]);
double times = atof(argv[2]);
double iterative_for_time = timeIt(number, times, iterative_for_factorial) / 1000000.0;
double iterative_while_time = timeIt(number, times, iterative_while_factorial) / 1000000.0;
double recursive_time = timeIt(number, times, recursive_factorial) / 1000000.0;
double recursive_ternary_time = timeIt(number, times, recursive_ternary_factorial) / 1000000.0;
double iterative_for_average = iterative_for_time / times;
double iterative_while_average = iterative_while_time / times;
double recursive_average = recursive_time / times;
double recursive_ternary_average = recursive_ternary_time / times;
printf("\n");
printf("==============================================\n");
printf("==============================================\n\n");
printf("Factorial Algorithm\n");
printf("Factorial calculated: %f\n", number);
printf("Number of times: %f\n", times);
printf("(all results are in seconds) \n");
printf("----------------------------------------------\n");
printf("\n");
printf("Total time:\n");
printf("iterative_for_factorial: %f\n", iterative_for_time);
printf("iterative_while_factorial: %f\n", iterative_while_time);
printf("recursive_factorial: %f\n", recursive_time);
printf("recursive_ternary_factorial: %f\n", recursive_ternary_time);
printf("\n");
printf("Average time:\n");
printf("iterative_for_factorial: %f\n", iterative_for_average);
printf("iterative_while_factorial: %f\n", iterative_while_average);
printf("recursive_factorial: %f\n", recursive_average);
printf("recursive_ternary_factorial: %f\n", recursive_ternary_average);
printf("\n");
printf("==============================================\n");
printf("==============================================\n\n");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:11:05.473",
"Id": "81059",
"Score": "1",
"body": "Just use a library, like [GMP's](https://gmplib.org/manual/) [mpz_fac_ui()](https://gmplib.org/manual/Number-Theoretic-Functions.html#Number-Theoretic-Functions)"
}
] | [
{
"body": "<p>I find it odd that the input to the factorial functions is a <code>double</code> rather than an <code>int</code>. There's no need to consider non-integral values of <code>n</code>, nor is there a need to allow large <code>n</code>. In fact, <em>n</em>! will start losing precision at around <em>n</em> = 19, since an <a href=\"http://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format%3a_binary64\">IEEE double</a> can only store numbers up to about 9 × 10<sup>16</sup> accurately. At <em>n</em> = 171, the result overflows completely.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T12:14:09.270",
"Id": "81007",
"Score": "0",
"body": "So, should I be using long as return type for more accurate results at high values?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:56:21.527",
"Id": "81038",
"Score": "0",
"body": "A `double` would make since if you did consider non-integral values. You can [extend the factorial function](http://en.wikipedia.org/wiki/Gamma_function) to the real numbers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:57:27.763",
"Id": "46368",
"ParentId": "46361",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>Those comment headers seem distracting and don't add anything of value. I'd just remove them.</p></li>\n<li><p>An <em>unformatted</em> output can be done with <code>puts()</code> instead of <code>printf()</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T04:16:34.367",
"Id": "46879",
"ParentId": "46361",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46368",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:11:22.387",
"Id": "46361",
"Score": "4",
"Tags": [
"c",
"algorithm",
"performance",
"beginner",
"console"
],
"Title": "Different factorial algorithm implementations and measuring their execution time"
} | 46361 |
<p>I am trying to make a linked list using 3 classes, however I cannot find ANY information online about it, and I can't seem to figure it out myself.</p>
<p>If you could please correct and explain what I am doing wrong, I would greatly appreciate it.</p>
<p><strong>LinkTest.h:</strong></p>
<pre><code>#include <string>
class Test
{
public:
void get(int &, std::string &);
private:
int int1;
std::string string1;
};
typedef class TestNode
{
private:
Test test;
TestNode* next;
} *TestPtr;
class TestList
{
public:
TestList();
void add(int &, std::string &);
void print();
private:
TestPtr head;
TestPtr tail;
TestPtr temp;
};
</code></pre>
<p><strong>LinkTest.cpp:</strong></p>
<pre><code>#include <iostream>
#include "LinkTest.h"
using namespace std;
void Test::get(int &otherint1, string &otherstring1)
{
int1 = otherint1;
string1 = otherstring1;
}
TestList::TestList()
{
head = NULL;
tail = NULL;
temp = NULL;
}
void TestList::add(int &otherint1, string &otherstring1)
{
TestPtr* n = new TestPtr;
n->next = NULL;
n->get(otherint1, otherstring1);
if(head != NULL)
{
tail = head;
while(tail->next != NULL)
{
tail = tail->next;
}
tail->next = n;
}
else
{
head = n;
}
}
void TestList::print()
{
tail = head;
while(tail != NULL)
{
cout << tail->test.int1 << " " << tail->test.string1 << endl;
temp = tail;
tail = tail->next;
}
}
</code></pre>
<p>The main function just does:</p>
<pre><code>int otherint1 = 1;
string otherstring1 = "hi";
TestList l;
l.add(otherint1, otherstring1);
otherint1 = 2;
otherstring1 = "there";
l.add(otherint1, otherstring1);
l.print();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:50:49.040",
"Id": "80993",
"Score": "0",
"body": "Linked Lists are not normally classified by how many classes they have. What made you classify it that way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:58:30.227",
"Id": "80995",
"Score": "0",
"body": "Every example I find is usually:\nclass TestList{\nstruct Node{\n...\n} *NodePtr;\nNodePtr head;\nNodePtr tail;\nNodePtr temp;\n//functions...\n}\nAnd NodePtr's data is usually just an int or string, not a class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:28:09.423",
"Id": "81002",
"Score": "1",
"body": "OK, then what you have is a Singly-Linked list optimized for tail 'add' ( O(1) add performance... ). Each time you add a node at the end, you update the 'tail' to point to the new node. This means you can simply add the node at tail.next, then move tail to point at the new node. If you remove the last node though, it is complicated, you have to 'reverse' the tail by scanning the entire list."
}
] | [
{
"body": "<p>At first glance, your code appears to work, but there is some confusion going on. I'll highlight what I consider to be the four top issues instead of making an exhaustive list.</p>\n\n<ol>\n<li>The <code>Test::get()</code> method is actually a setter, not a getter, and should be named <code>Test::set()</code>.</li>\n<li><p>The <code>Test</code> class seems to represent the kind of data you want to store in the list. You should just eliminate <code>Test</code> in favour of <code>std::pair<int, std::string></code>.</p>\n\n<p>The linked list code doesn't really have any business providing an <code>add()</code> method that takes two kinds of data to be stuffed into the new node. Instead of calling <code>TestList::add(int, std::string)</code>, just make the construction explicit to the caller, as <code>TestList::add(std::pair<int, std::string>(someInt, someString))</code>.</p></li>\n<li><code>TestList</code> has three member variables: <code>head</code>, <code>tail</code>, and <code>temp</code>. Of those three, only <code>head</code> stores object state and deserves to be a member variable. <code>tail</code> and <code>temp</code> should just be local variables within functions that need them.</li>\n<li>You call <code>new</code>, but it's not paired with a <code>delete</code> anywhere. That's a memory leak. The memory that you allocate should be cleaned up in a destructor.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:35:45.817",
"Id": "81003",
"Score": "0",
"body": "I have not heard of pair before, do I need a special library for that?\nAnd yes, I added delete into the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:37:48.577",
"Id": "81004",
"Score": "0",
"body": "See http://en.cppreference.com/w/cpp/utility/pair."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:45:31.270",
"Id": "81005",
"Score": "0",
"body": "Oh, I'd like to stay away from template for now.\nI will definitely try it out in another program in the near future though, thanks for the suggestion.\n\nAs for this program, would you be able to fix the print and add functions for me please? I get errors for when I try to use TestPtr and when I try the line in print():\ncout << tail->test.int1 << \" \" << tail->test.string1 << endl;\n\nIt confuses me, because to me, that seems logical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:25:26.760",
"Id": "81016",
"Score": "0",
"body": "@user40128 Note that you're already using templates; they're just hidden: `std::string` is an alias for `std::basic_string<char, ...>`. If you just want to avoid the syntax all over the place, you could add your own `typedef std::pair<int, std::string> IntString;` alias."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:30:53.260",
"Id": "81050",
"Score": "0",
"body": "@user40128: You can;t really stay away from templates. `std::string` is a template for example. Don't treat templates as special. They are just normal classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:31:36.903",
"Id": "81051",
"Score": "0",
"body": "@MichaelUrman, by template, I mean template<T>, like for the pair<> function"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:27:27.310",
"Id": "46366",
"ParentId": "46362",
"Score": "6"
}
},
{
"body": "<h3>LinkTest.h:</h3>\n\n<p>Test is not really a test class.</p>\n\n<pre><code>class Test\n{\npublic:\n void get(int &, std::string &);\nprivate:\n int int1;\n std::string string1;\n};\n</code></pre>\n\n<p>That's confusing. This is the type of data that you store in the list. Please rename it more appropriately. Common omong containers is <code>value_type</code>.</p>\n\n<p>Again with <code>TestNode</code> the naming thing.</p>\n\n<pre><code>typedef class TestNode\n{\n private:\n Test test;\n TestNode* next;\n} *TestPtr;\n</code></pre>\n\n<p>This is not your grandpa's C; this is <strong>C++</strong>. struct live in the same namespace as other types and objects. Also multiple declarations on the same line is frowned upon so split the above into multiple declarations to make it clear wheat is happening.</p>\n\n<pre><code>class TestNode\n{\n private:\n Test test;\n TestNode* next;\n};\ntypedef TestNode* TestPtr;\n // ^^^^^^^^^ Note * on left side.\n // The type you are defing is a TestNode pointer => New Name TestPre\n</code></pre>\n\n<p>Personally I don't like hiding pointers behind typedefs. It hides pointers that I want to see because memory management needs to be done with them. I would personally drop the typedef.</p>\n\n<p>Again <code>Test</code> in the name. </p>\n\n<pre><code>class TestList\n</code></pre>\n\n<p>Rather than adding two different types that have nothing to do with your list.</p>\n\n<pre><code> void add(int &, std::string &);\n</code></pre>\n\n<p>You should add (or push) the data that is held by your list. In this case <code>Test</code>.</p>\n\n<pre><code> // pass a test object that is copied into the list.\n void push_back(Test const& ); \n</code></pre>\n\n<p>In modern versions of C++ we now use the term <code>emplace</code> for this you pass the parameters that can be used in the constructor of your data class. Unfortunately your data class has no constructor (apart from the default). </p>\n\n<pre><code> class Test\n {\n public: Test(int v, std::string const& x)\n int1(v), string1(x){}\n };\n // Pass the values for the constructor of a Test object.\n // The object will be created emplace using the constructor.\n // rather than the copy constructor used by push_front() \n void emplace_back(int const&, std::string const&)\n</code></pre>\n\n<p>Having a print function is fine (but you should pass a stream to print it on).</p>\n\n<pre><code> void print(std::ostream& s = std::cout); // default to std::cout\n // if not explicitly specified.\n</code></pre>\n\n<p>But you should probably also define an <code>operator<<</code> for your class that calls it. Most people basically do away with the print and just put the logic of the print in <code>operator>></code> and make it a friend of the class.</p>\n\n<pre><code> std::ostream& operator<<(std::ostream& s, TestList& data)\n {\n data.print(s);\n return s;\n }\n</code></pre>\n\n<h3>LinkTest.cpp:</h3>\n\n<p>Include from the most specific to the most general.</p>\n\n<pre><code>#include <iostream>\n#include \"LinkTest.h\"\n</code></pre>\n\n<p>The most specific is the header file for this class. Followed by any header files for classes that you specifically use followed by C++ libraries )as these are general files but are built on-top of C files) followed by C libraries (as these are the most general system files).</p>\n\n<pre><code>#include \"LinkTest.h\"\n#include <iostream>\n</code></pre>\n\n<p>Don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>see <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n\n<p>Obviously not a get()</p>\n\n<pre><code>void Test::get(int &otherint1, string &otherstring1)\n{\n int1 = otherint1;\n string1 = otherstring1;\n}\n</code></pre>\n\n<p>This is setting the values. It looks more like a constructor than a get. Pass by <code>const&</code> this is a more healthy contract the promises you will not modify the passed parameters (it also allows you to use temporaries). </p>\n\n<pre><code>void TestList::add(int &otherint1, string &otherstring1)\n{\n</code></pre>\n\n<p>Yep you should have a constructor that does all this work.</p>\n\n<pre><code> TestPtr* n = new TestPtr;\n n->next = NULL;\n n->get(otherint1, otherstring1);\n</code></pre>\n\n<p>Would have looked much nicer as:</p>\n\n<pre><code> TestPtr* n = new TestPtr(otherint1, otherstring1);\n</code></pre>\n\n<p>PS. These are horrible parameter names and do not help in self documenting code.</p>\n\n<p>The <code>tail</code> value is a member of the class. Why it it not maintained as always pointing at the last element? Then you would not need to search for the last element every time you add something new to the class.</p>\n\n<pre><code> tail = head;\n while(tail->next != NULL)\n {\n tail = tail->next;\n }\n tail->next = n;\n</code></pre>\n\n<p>The complexities of maintaining a list are reduced considerably if you use a <code>sentinel</code> value. See: <a href=\"https://codereview.stackexchange.com/q/46019/507\">Linked List reversal</a></p>\n\n<p>Then you don't need to worry about when the head is NULL (because it never is).</p>\n\n<pre><code> else\n {\n head = n;\n }\n</code></pre>\n\n<p>Also you don't handle memory management.</p>\n\n<p>Technically for every <code>new</code> there should be a call to <code>delete</code>. But that's old school thinking. There should never be any <code>delete</code> specifically in your code. You should be using smart pointers to manage your pointers so that they are exception safe.</p>\n\n<pre><code>void TestList::print()\n{\n // Don't use tail here.\n // tail should always point at the last element in the list.\n // Only moe it when there is a new last element.\n tail = head;\n\n // here use a local function scope temporary (call it printLoop or something).\n while(tail != NULL)\n</code></pre>\n\n<p>Don't use <code>std::endl</code>.</p>\n\n<pre><code> std::cout << std::endl;\n // is equivalent to:\n std::cout << '\\n' << std::flush;\n</code></pre>\n\n<p>As you see this forces the buffer to be flushed every time. This is very inefficient. So don't do it every time just do it once you have done all your printing. Personally I hardly ever use it. std::cin and std::cout are synced together so that std::cout is flushed before user input is requested so it is hardly ever necessary and the buffers for files are designed to be the size that gives you the most effecient size for flushing to disk.</p>\n\n<pre><code> cout << tail->test.int1 << \" \" << tail->test.string1 << endl;\n</code></pre>\n\n<p>Rewrite the loop as:</p>\n\n<pre><code> for(TestPtr printLoop = head; printLoop != NULL; printLoop = printLoop->next)\n {\n std::cout << printLoop->test << '\\n';\n // ^^^^^^^^^^^^^^^\n // Note: it is not TestList job to know how to print a Test\n // You should just ask the stream to print it.\n // The the Test object should know how to print itself.\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:08:32.320",
"Id": "46388",
"ParentId": "46362",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46366",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:19:08.310",
"Id": "46362",
"Score": "4",
"Tags": [
"c++",
"linked-list"
],
"Title": "3-class linked list"
} | 46362 |
<p>This post is a follow-up to <a href="https://codereview.stackexchange.com/questions/46310/when-should-i-consider-the-number-of-my-method-arguments-too-big">Simple Pong game</a></p>
<p>I took the some advice from the previous post and I'm almost done with cleaning up the code. I didn't make any wrapper classes, because my game is already waaaay overkill for this assignment, but I did add more methods and fixed naming.</p>
<p>Are there any rules regarding method order, like alphabetical, or in order of appearance/usage?</p>
<p>I also need to put comments to my code, because that's what my teacher wants me to do for this assignment. I am not sure how should I comment the code. Is it enough to just put one or two sentences for each method used, or should I describe every variable/group of variables, every import etc?</p>
<p>Also, please tell me what else should I do to clean my code and what did I do wrong.</p>
<pre><code>import java.awt.Color;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.util.Random;
import acm.graphics.GImage;
import acm.graphics.GLabel;
import acm.graphics.GObject;
import acm.graphics.GOval;
import acm.graphics.GRect;
import acm.program.GraphicsProgram;
/* TO DO LIST
* ------------------
* Corner Bounce
*
*
*
*
*/
@SuppressWarnings("serial")
public class Pong extends GraphicsProgram {
private static final double PAUSE = 1000 / 96.0;
public Random rand = new Random();
public double mouseY;
public boolean AI_GODMODE = false;
// ball
private static final double BALL_SIZE = 20;
private static final double SPEED = 5;
public double ballHorizontalSpeed = SPEED * 1.5;
public double ballVerticalSpeed = SPEED;
public double startX;
public double startY;
// paddle
private static int HEIGHT = 150;
private static int WIDTH = 15;
private static int COUNTER = 0;
public static int AI_SPEED = 9; // AI difficulty 0-20
// label
private float TRANSPARENCY = 0.0f;
public int AI_SCORE = 0;
public int PLAYER_SCORE = 0;
// counters
private static final int PADDING = 10;
private static final int MODIFIER = 3;
public static void main(String[] args) {
Pong p = new Pong();
p.run();
}
public void run() {
addMouseListeners();
// counters setup
GLabel counter = new GLabel(String.valueOf(COUNTER));
GLabel aiScore = new GLabel(String.valueOf(AI_SCORE));
GLabel playerScore = new GLabel(String.valueOf(COUNTER));
counter.setFont("Impact-600");
aiScore.setFont("Impact-100");
playerScore.setFont("Impact-100");
Color labelC = new Color(0, 0.0f, 0.0f, TRANSPARENCY);
Color scoreC = new Color(0, 0.0f, 0.0f, 0.1f);
counter.setColor(labelC);
aiScore.setColor(scoreC);
playerScore.setColor(scoreC);
counter.setLocation(getWidth() / 2 - counter.getWidth() / 2,
getHeight() / 2 + counter.getHeight() / 3.2);
counter.sendToFront();
// make objects
GImage paddleLeftTexture = createTexture("texture.png", WIDTH + 1,
HEIGHT + 1);
GImage paddleRightTexture = createTexture("texture2.png", WIDTH + 1,
HEIGHT + 1);
GImage ballTexture = createTexture("ballTexture.png", (int) BALL_SIZE,
(int) BALL_SIZE);
GImage greenFlash = createTexture("greenFlash.png", 100, 300);
GImage blueFlash = createTexture("blueFlash.png", 100, 300);
GOval ball = makeBall();
GRect paddleLeft = makePaddle();
GRect paddleRight = makePaddle();
greenFlash.setLocation(-200, 0);
blueFlash.setLocation(-200, 0);
// generate GUI
drawGraphics(ball, paddleLeftTexture, paddleRightTexture, ballTexture,
greenFlash, blueFlash, counter, paddleLeft, paddleRight,
aiScore, playerScore);
// game start
bounce(labelC, aiScore, playerScore, counter, ball, paddleLeft,
paddleRight, paddleLeftTexture, paddleRightTexture,
ballTexture, greenFlash, blueFlash);
}
public void bounce(Color labelC, GLabel aiScore, GLabel playerScore,
GLabel counter, GOval ball, GRect paddleLeft, GRect paddleRight,
GImage paddleLeftTexture, GImage paddleRightTexture,
GImage ballTexture, GImage greenFlash, GImage blueFlash) {
preGameSetup(ball, paddleRight, paddleRightTexture, counter);
updateAiScore(aiScore);
updatePlayerScore(playerScore);
while (true) {
moveBall(ballHorizontalSpeed, ballVerticalSpeed, ball, ballTexture);
movePlayerPaddle(paddleLeft, paddleLeftTexture);
moveAiPaddle(ball, paddleRight, paddleRightTexture);
detectHit(ball, paddleRight, paddleLeft, counter, labelC);
if (TRANSPARENCY >= 0.0f) {
TRANSPARENCY -= TRANSPARENCY / 100f;
}
labelC = new Color(0, 0.0f, 0.0f, TRANSPARENCY);
counter.setColor(labelC);
if (detectBallOffScreen(ball)) {
ballOffScreen(ball, ballTexture, aiScore, playerScore,
greenFlash, blueFlash);
COUNTER = 0;
bounce(labelC, aiScore, playerScore, counter, ball, paddleLeft,
paddleRight, paddleLeftTexture, paddleRightTexture,
ballTexture, greenFlash, blueFlash);
}
pause(PAUSE);
}
}
public static GRect makePaddle() {
GRect result = new GRect(0, 0, WIDTH, HEIGHT);
result.setFilled(true);
result.setColor(Color.BLACK);
return result;
}
public static GOval makeBall() {
GOval result = new GOval(150, 100, BALL_SIZE, BALL_SIZE);
result.setFilled(true);
result.setColor(Color.WHITE);
return result;
}
private GImage createTexture(String importedImage, int width, int height) {
Image importResult = getImage(getCodeBase(), importedImage);
GImage textureResult = new GImage(importResult);
textureResult.setSize(width, height);
return textureResult;
}
public void mouseMoved(MouseEvent e) {
mouseY = e.getY();
}
private boolean ballHitBottom(GOval ball) {
double bottomY = ball.getY() + ball.getHeight();
return bottomY >= getHeight();
}
private boolean ballHitTop(GOval ball) {
double topY = ball.getY();
return topY <= 0;
}
private boolean ballHitPaddleRight(GOval ball, GRect paddle) {
double rightX = ball.getX() + ball.getWidth();
double rightY = ball.getY() + ball.getHeight() / 2;
double paddlePosX = paddle.getX();
double paddlePosY = paddle.getY();
if (rightX >= paddlePosX && rightY >= paddlePosY
&& rightY <= paddlePosY + paddle.getHeight())
return true;
else
return false;
}
private boolean detectBallOffScreen(GOval ball) {
if (ball.getX() < 2*WIDTH - BALL_SIZE || ball.getX() > getWidth() - 2*WIDTH)
return true;
else
return false;
}
private boolean ballHitPaddleLeft(GOval ball, GRect paddle) {
double leftX = ball.getX();
double leftY = ball.getY();
double paddlePosX = paddle.getX() + WIDTH;
double paddlePosY = paddle.getY();
if (leftX <= paddlePosX && leftY >= paddlePosY
&& leftY <= paddlePosY + paddle.getHeight())
return true;
else
return false;
}
/*
private boolean ballHitPaddleBorder(GOval ball, GRect paddle) {
;
if (ball.getX() > paddle.getX() - BALL_SIZE
&& ball.getX() < paddle.getX() + WIDTH
&& ball.getY() > paddle.getY() && ball.getY() < paddle.getY() + ballVerticalSpeed)
return true;
else if (ball.getX() > paddle.getX() - BALL_SIZE
&& ball.getX() < paddle.getX() + WIDTH
&& ball.getY() > paddle.getY() + HEIGHT && ball.getY() < paddle.getY() + HEIGHT - ballVerticalSpeed)
return true;
else
return false;
}
*/
private void preGameSetup(GObject ball, GObject paddleRight,
GObject paddleRightTexture, GLabel counter) {
startX = rand.nextInt((int) (getWidth() * 0.8))
+ (int) (0.1 * getWidth()); // zapobiega pojawieniu się piłki po
// lewej stronie lewej paletki
startY = rand.nextInt(getHeight());
ball.setLocation(startX, startY);
paddleRightTexture.setLocation(getWidth() - 3 * WIDTH, startY - HEIGHT
/ 2);
paddleRight.setLocation(getWidth() - 3 * WIDTH, startY - HEIGHT / 2);
paddleRightTexture.sendToFront();
counter.setLabel(String.valueOf(COUNTER));
counter.setLocation(getWidth() / 2 - counter.getWidth() / 2,
getHeight() / 2 + counter.getHeight() / 3.2);
ballHorizontalSpeed = SPEED * 1.5;
ballVerticalSpeed = SPEED;
}
private void updateAiScore(GLabel aiScore) {
aiScore.setLabel(String.valueOf(AI_SCORE));
aiScore.setLocation(getWidth() - aiScore.getWidth() - MODIFIER * WIDTH
- 10, getHeight() - 10);
}
private void updatePlayerScore(GLabel playerScore) {
playerScore.setLabel(String.valueOf(PLAYER_SCORE));
playerScore.setLocation(MODIFIER * WIDTH + 10, getHeight() - 10);
}
private void drawGraphics(GObject ball, GObject paddleLeftTexture,
GObject paddleRightTexture, GObject ballTexture,
GObject greenFlash, GObject blueFlash, GObject counter,
GObject paddleLeft, GObject paddleRight, GObject aiScore,
GObject playerScore) {
add(ball);
add(paddleLeftTexture);
add(paddleRightTexture);
add(ballTexture);
add(greenFlash);
add(blueFlash);
add(counter);
add(paddleLeft);
add(paddleRight);
add(aiScore);
add(playerScore);
}
private void detectHit(GOval ball, GRect paddleRight, GRect paddleLeft,
GLabel counter, Color labelC) {
if (ballHitBottom(ball) && ballVerticalSpeed >= 0) {
ballVerticalSpeed *= -1;
}
if (ballHitTop(ball) && ballVerticalSpeed <= 0) {
ballVerticalSpeed *= -1;
}
if (ballHitPaddleRight(ball, paddleRight)) {
ballHorizontalSpeed *= -1;
}
if (ballHitPaddleLeft(ball, paddleLeft)) {
ballHorizontalSpeed *= -1;
COUNTER++;
counter.setLabel(String.valueOf(COUNTER));
counter.setLocation(getWidth() / 2 - counter.getWidth() / 2,
getHeight() / 2 + counter.getHeight() / 3.2);
TRANSPARENCY = 0.1f;
labelC = new Color(0, 0.0f, 0.0f, TRANSPARENCY);
counter.setColor(labelC);
boolean bool = rand.nextBoolean();
if (bool)
if (ballHorizontalSpeed > 0)
ballHorizontalSpeed += 1;
else
ballHorizontalSpeed -= 1;
else if (ballVerticalSpeed > 0)
ballVerticalSpeed += 0.5;
else
ballVerticalSpeed -= 0.5;
}
/*
if(ballHitPaddleBorder(ball, paddleLeft)){
ballVerticalSpeed *= -1;
}
if(ballHitPaddleBorder(ball, paddleRight)){
ballVerticalSpeed *= -1;
}
*/
}
private void ballOffScreen(GOval ball, GObject ballTexture, GLabel aiScore,
GLabel playerScore, GObject greenFlash, GObject blueFlash) {
if (ball.getX() < 2*WIDTH - BALL_SIZE) { // left
double pos = ball.getY() - greenFlash.getHeight() / 2;
ballTexture.move(-ballTexture.getWidth()*2, 0);
AI_SCORE += COUNTER;
updateAiScore(aiScore);
for (int i = 20; i < 100; i += 5) {
greenFlash.setLocation(-i, pos);
pause(25);
}
} else { // right
double pos = ball.getY() - blueFlash.getHeight() / 2;
ballTexture.move(ballTexture.getWidth()*2, 0);
PLAYER_SCORE += COUNTER;
updatePlayerScore(playerScore);
for (int i = 20; i < 100; i += 5) {
blueFlash.setLocation(getWidth() - blueFlash.getWidth() + i,
pos);
pause(25);
}
}
}
private void moveBall(double ballHorizontalSpeed, double ballVerticalSpeed,
GObject ball, GObject ballTexture) {
ball.move(ballHorizontalSpeed, ballVerticalSpeed);
ballTexture.setLocation(ball.getX(), ball.getY());
ballTexture.sendToFront();
}
private void movePlayerPaddle(GObject paddleLeft, GObject paddleLeftTexture) {
if (mouseY < getHeight() - HEIGHT) { // Player
paddleLeft.setLocation(2 * WIDTH, mouseY);
paddleLeftTexture.setLocation(2 * WIDTH, mouseY);
paddleLeftTexture.sendToFront();
} else {
paddleLeft.setLocation(2 * WIDTH, getHeight() - HEIGHT);
paddleLeftTexture.setLocation(2 * WIDTH, getHeight() - HEIGHT);
paddleLeftTexture.sendToFront();
}
}
private void moveAiPaddle(GOval ball, GRect paddleRight,
GImage paddleRightTexture) {
if (AI_GODMODE == true) {
if (ball.getY() < getHeight() - HEIGHT / 2
&& ball.getY() > HEIGHT / 2) {
paddleRight.setLocation(getWidth() - 3 * WIDTH, ball.getY()
- HEIGHT / 2);
paddleRightTexture.setLocation(getWidth() - 3 * WIDTH,
ball.getY() - HEIGHT / 2);
paddleRightTexture.sendToFront();
} else if (ball.getY() <= HEIGHT / 2) {
paddleRight.setLocation(getWidth() - 3 * WIDTH, 0);
paddleRightTexture.setLocation(getWidth() - 3 * WIDTH, -0);
paddleRightTexture.sendToFront();
} else {
paddleRight.setLocation(getWidth() - 3 * WIDTH, getHeight()
- HEIGHT);
paddleRightTexture.setLocation(getWidth() - 3 * WIDTH,
getHeight() - HEIGHT);
paddleRightTexture.sendToFront();
}
} else { // end godMode if
double targetY = ball.getY() + BALL_SIZE / 2;
if (targetY < getHeight() - HEIGHT / 2 && targetY > HEIGHT / 2) {
if (targetY < paddleRight.getY() + HEIGHT / 2) {
paddleRight.move(0, -AI_SPEED);
paddleRightTexture.move(0, -AI_SPEED);
} else if (targetY > paddleRight.getY() + HEIGHT / 2) {
paddleRight.move(0, AI_SPEED);
paddleRightTexture.move(0, AI_SPEED);
}
} // end normalMode if
} // end modeSelector if
} // end moveAiPaddle void
} // end class
</code></pre>
<p>Part of the code is not working properly yet, so I put it in comment <code>/* [...] */</code>.</p>
| [] | [
{
"body": "<p>I don't know Java, but I can tell you that in the first /* ... <em>/ section, both if statements are the same.\nAlso, in the second /</em> ... */ section, rather than having 2 if's, just say</p>\n\n<pre><code>if((firstifcondition) OR (secondifcondition))\n{\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:18:15.990",
"Id": "81000",
"Score": "0",
"body": "There is a slight difference in `if` statements, on Y axis are is `+ HEIGHT` in the second one"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T11:15:51.580",
"Id": "46364",
"ParentId": "46363",
"Score": "2"
}
},
{
"body": "<p>As you noticed: it's hard to force comments when the code is written well. Once you get rid of magic values, create descriptive names for both variables and methods and make sure each method does one thing you have basically reached a so-called <em>self-documenting code</em>.</p>\n\n<p>And that's good: this is the kind of code you want to reach. However, teachers are teachers and they won't always recognize your awesomeness. </p>\n\n<p>Luckily for you there are two main categories of commenting. </p>\n\n<p>Many new programmers comment the <em>what</em>: <strong>\"what does the code do?\"</strong>. These are very uninteresting comments, an example could be this:</p>\n\n<pre><code>// In case the mouse moved\npublic void mouseMoved(MouseEvent e) {\n mouseY = e.getY(); // Update the mouse's Y-position\n}\n</code></pre>\n\n<p>These type of comments just reiterate what we can already read very clearly from the code itself (see: <em>self-documenting code</em>).</p>\n\n<p>The other type of comments elaborate on the <em>why</em>. These are comments that explain your reasoning behind a bit of code, something that is a lot harder to express in code.</p>\n\n<p>Take for example this piece of code:</p>\n\n<pre><code>private void updatePlayerScore(GLabel playerScore) {\n playerScore.setLabel(String.valueOf(PLAYER_SCORE));\n playerScore.setLocation(MODIFIER * WIDTH + 10, getHeight() - 10);\n}\n</code></pre>\n\n<p>When I read this, I ask myself the question \"Why did the location of that score get changed?\". This is an excellent opportunity for you to add a comment why that is:</p>\n\n<pre><code>// Change location because the playfield changed size\nprivate void updatePlayerScore(GLabel playerScore) {\n playerScore.setLabel(String.valueOf(PLAYER_SCORE));\n playerScore.setLocation(MODIFIER * WIDTH + 10, getHeight() - 10);\n}\n</code></pre>\n\n<p>Now I will immediately know what your intentions were and the general idea behind your approach is clearer. I'm certain your teachers will appreciate such informative commenting when they have to look through a multitude of assignments, many which will not have gone through a review.</p>\n\n<h1>Member order</h1>\n\n<p>Regarding your edit on method order (which I changed to member order to get some other things as well): usually I would point you to the <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\">Java Code Conventions</a> but appearantly they all give a 404 right now. However from the top of my head, this is the order of which a class' members should appear:</p>\n\n<ul>\n<li>Constants</li>\n<li>Static variables</li>\n<li>Instance variables</li>\n<li>Static constructor</li>\n<li>Initializer block</li>\n<li>Constructor</li>\n<li>Methods </li>\n</ul>\n\n<p>The actual order of the content of each type is not important (except variables that use another variables: they have to be defined in the right order).</p>\n\n<h1>Sidenotes</h1>\n\n<p>Just to remark a few other things:</p>\n\n<ul>\n<li>Still some magic values left at the bottom of the file</li>\n<li>Many <code>public</code> variables. Some might be intended like that, but your <code>Random</code> instance shouldn't be amongst them.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T12:58:43.653",
"Id": "81009",
"Score": "0",
"body": "I found some more info regarding order in `5.2.40` here [javastyle.html](http://geosoft.no/development/javastyle.html#Classes%20and%20Interfaces)\n\nAs for magic numbers, I don't need to put `2` into variable when calculating half of height, right? This seems to be the decreasing code readability.\nI have one more random number which I don't know what to do with, it's `3.2` used to align one of the counters. Text label does not align horizontally the same way i did verically (half total - half text size), i got it with trial and error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:07:42.890",
"Id": "81011",
"Score": "0",
"body": "Oh, if that is the reason of `2` then you can leave it as it is. Although I might just extract all these movements into their own methods like `moveDown(GRect)`, but that's it. That `3.2` variable is an excellent opportunity to add a comment!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T12:30:30.250",
"Id": "46369",
"ParentId": "46363",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46369",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T10:54:53.313",
"Id": "46363",
"Score": "7",
"Tags": [
"java",
"game",
"classes",
"animation"
],
"Title": "Cleaning up and commenting on my code for Pong game"
} | 46363 |
<p>How can I make this matrix effect more like the matrix movie?</p>
<pre><code>#include<stdlib.h>
#include<stdio.h>
int main()
{
srand((unsigned) time(0));
int i,j;
system("color 0a");
while(1)
{
i = rand() % 2;
j= rand() % 2;
if(j)
{
printf("%d ", i);
}
else
{
printf(" %d", i);
}
}
return 0;
}
</code></pre>
<p>Here is how it looks like:</p>
<p><img src="https://i.stack.imgur.com/GNcRW.png" alt="matrix"></p>
<p>Of course it is better if it was moving but that's all what I can show.</p>
<p>Also it takes a notable time to compile, is there anything wrong I'm doing?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:18:55.373",
"Id": "81037",
"Score": "0",
"body": "How is it not like the movie... what are you trying to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:53:36.023",
"Id": "81055",
"Score": "0",
"body": "nb - a google search of \"matrix animation javascript\" will turn up a number of good examples in javascript. The key is to index the display to place the character at a given x, y to achieve the \"rain\" effect."
}
] | [
{
"body": "<p>If you are talking optimization (not sure you are) then one clear change is to remove printf -- printf is very slow. You are only displaying <code>0</code>, <code>1</code>, and <code></code>.</p>\n\n<p>putc is much faster -- it does not have to parse for formatting. If you change the code to use putc instead of printf you should see a dramatic speed boost.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:57:52.223",
"Id": "81056",
"Score": "1",
"body": "You're wrong. I mean, there is no need to turn `print` into `putchar`. Indeed, the compiler will do that automatically if needed, even with no optimization flag turned on.\nChecked on gcc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:43:18.157",
"Id": "81106",
"Score": "0",
"body": "@no1 - The `printf` (not `print`) optimization only happens for string literals, `%s` and `%c`. None of which is true for this example which is a `%d`. This is why awashburn's answer requires the `ASCII_NUMBER_OFFSET` define. I'm not wrong, you are. More info: http://www.ciselant.de/projects/gcc_printf/gcc_printf.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T10:00:57.373",
"Id": "81131",
"Score": "0",
"body": "There is no need to use that ugly macro, since you can directly 1) convert to char 2) add 0x30 - '0'.\nHence, either you call `printf(\"%c\", n)` or `putchar(n + 0x30)` will be equivalent. Good to point out, though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:21:17.720",
"Id": "46377",
"ParentId": "46370",
"Score": "1"
}
},
{
"body": "<h2>What You Have Now:</h2>\n\n<p>You code is simple and concise. That in and of itself can be a desirable quality. I think we can make the code a little bit more concise while gaining some runtime efficiency.</p>\n\n<p>Some changes I would make:</p>\n\n<p><strong>Change</strong> <code>srand((unsigned) time(0));</code> <em>to</em> <code>srand(time(NULL));</code></p>\n\n<ul>\n<li>While both are correct, this is how I have seen seeds set more often, hence it is the idiomatic approach</li>\n</ul>\n\n<p><strong>Change</strong> <code>return 0</code> <em>to</em> <code>return EXIT_SUCCESS</code></p>\n\n<ul>\n<li>Exit codes are included in <code>stdlib</code>, since you already using that library, you should also use the provided exit codes.</li>\n</ul>\n\n<p><strong>Change</strong> <code>rand()%2</code> <em>to</em> <code>rand()&1</code></p>\n\n<ul>\n<li>The <a href=\"http://en.wikipedia.org/wiki/Modulo_operation\" rel=\"nofollow\">modulo operator</a> (<code>%</code>) can be very inefficient on some architectures. Since you are only using <code>rand()</code> to get binary values, we can much more efficiently use the bitwise and operator (<code>&</code>) to get a 1 if the number is odd and a 0 if the number is even.</li>\n</ul>\n\n<p><strong>Change</strong> your while loop to remove intermediate variables:</p>\n\n<pre><code>while(1) {\n if(rand() & 1)\n printf(\"%d \", rand() & 1);\n else\n printf(\" %d\", rand() & 1);\n}\n</code></pre>\n\n<p>All together I think you could simplify your code to this:</p>\n\n<pre><code>#include<stdlib.h>\n#include<stdio.h>\nint main() {\nsrand(time(NULL));\nsystem(\"color 0a\");\n\nwhile(1) {\n if(rand() & 1)\n printf(\"%d \", rand() & 1);\n else\n printf(\" %d\", rand() & 1);\n}\n\nreturn EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>This is a pretty small and eloquent code for generating a matrix style output. If your happy with this you can stop right here.</p>\n\n<hr>\n\n<p>However, it should be pointed out that <a href=\"http://linux.die.net/man/3/printf\" rel=\"nofollow\"><code>printf</code></a> is a little heavy handed for just printing spaces, ones, and zeros. You could utilize <a href=\"http://linux.die.net/man/3/putchar\" rel=\"nofollow\"><code>putchar</code></a> which will, unsurprisingly, put a character to <code>STDOUT</code>.</p>\n\n<pre><code>while(1) {\n if(rand() & 1) {\n putchar(48 + (rand()&1))\n putchar(' ');\n }\n else {\n putchar(' ')\n putchar(48 + (rand()&1));\n }\n}\n</code></pre>\n\n<p>Note that now we have a <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow\">Magic Number</a> <strong>48</strong> in out code, that is no good! Let's let the preprocessor help us make the code a little bit more readable:</p>\n\n<pre><code>#define ASCII_NUMBER_OFFSET 48\nwhile(1) {\n if(rand() & 1) {\n putchar(ASCII_NUMBER_OFFSET + (rand()&1));\n putchar(' ');\n }\n else {\n putchar(' ');\n putchar(ASCII_NUMBER_OFFSET + (rand()&1));\n }\n}\n</code></pre>\n\n<p>Next is a matter of personal preference. I personally don't like 2 line <code>if</code> statements. If the <code>if</code> statement has 3 lines, it should probably be abstracted into a separate method, if it has one line, that’s perfect, but if we have 2 lines... that's murky water.</p>\n\n<p>We could use the <a href=\"http://en.wikipedia.org/wiki/Comma_operator\" rel=\"nofollow\">comma operator</a> to clean up the line a little: </p>\n\n<pre><code>#define ASCII_NUMBER_OFFSET 48\nwhile(1) {\n if(rand() & 1)\n putchar(ASCII_NUMBER_OFFSET + (rand()&2)), putchar(' ');\n else\n putchar(' '), putchar(ASCII_NUMBER_OFFSET + (rand()&1));\n}\n</code></pre>\n\n<p>Using the comma operator is a matter of preference. I think that there are times that it is perfectly clear & reasonable to use it, others say the comma operator should never be used because it is too opaque. While that code is more compact, I don't think it helps readability or efficiency.</p>\n\n<p>Lets try abstraction that into a method instead and see how that looks:</p>\n\n<pre><code>while(1) {\n if(rand() & 1)\n printLeft();\n else\n printRight();\n}\n.\n.\n.\n#define ASCII_NUMBER_OFFSET 48\nvoid printLeft() {\n putchar(' ');\n putchar(ASCII_NUMBER_OFFSET + (rand()&1));\n}\n\nvoid printRight() {\n putchar(ASCII_NUMBER_OFFSET + (rand()&1));\n putchar(' ');\n}\n</code></pre>\n\n<p>That makes the while loop look better but the methods <em>might</em> incur some performance cost. Since your tag <code>Optimization</code> implies that you care most about runtime efficiency and not readability/maintainability lets try something else.</p>\n\n<p>You will notice in your all the code examples above, there is some repetition in the while loop. In all the cases we have 2 statements printing the one or zero. Repetition is often a good thing to focus on because it can alert you to things that can be improved. There is a mantra of <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">Don't Repeat Yourself</a> (DRY) in programming which is designed to help programmers locate inefficiencies and refactor their code for better readability & efficency.</p>\n\n<p>Consider this loop:</p>\n\n<pre><code>int b;\nwhile(1) {\n if(b = rand() & 1)\n putchar(' ');\n putchar(ASCII_NUMBER_OFFSET + (rand() & 1));\n if(!b)\n putchar(' ');\n}\n</code></pre>\n\n<p>Here we have a single binary number printing statement but conditionally print a space before or after the number. From a runtime efficiency perspective this is probably optimal (though I have not done any benchmarking). </p>\n\n<p>If we put this all together we have the following:</p>\n\n<pre><code>#include<stdlib.h>\n#include<stdio.h>\n#define ASCII_NUMBER_OFFSET 48\n\nint main() {\nint b;\nsrand(time(NULL));\nsystem(\"color 0a\");\n\nwhile(1) {\n if(b = (rand() & 1))\n putchar(' ');\n putchar(ASCII_NUMBER_OFFSET + (rand() & 1));\n if(!b)\n putchar(' ');\n}\n\nreturn EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>I hope this has given you a lot of different angles to view you code from and given you the tools to decide what you value when improving this code, readability or runtime efficiency. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:52:54.200",
"Id": "81054",
"Score": "0",
"body": "good call, I forgot about that..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T21:07:21.363",
"Id": "81086",
"Score": "1",
"body": "\"Change `return 0` to `return EXIT_SUCCESS`\" - Just get rid of the return completely, thanks to C99 & C11 §5.1.2.2(3); your parameters should be declared as `void`, if you don't take anything in (for example: `main(void)`); you should always initialize your variable on creation; and if you only have one statement in a test conditional, you should mimic [this style](http://programmers.stackexchange.com/a/16530/94014) to prevent bugs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T21:23:53.187",
"Id": "81087",
"Score": "0",
"body": "Also, you should make a note to *not* use `system()`, and instead use [ANSI escape codes](http://stackoverflow.com/questions/3219393/stdlib-and-colored-output-in-c). All modern terminals implement them, and they will speed up the code. And you forgot to `#include <time.h>` when you used `time()`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:16:44.617",
"Id": "46382",
"ParentId": "46370",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46382",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:23:26.930",
"Id": "46370",
"Score": "4",
"Tags": [
"optimization",
"c"
],
"Title": "Matrix falling effect"
} | 46370 |
<p>Recently I built a map with custom markers (pins) and a sorting function to display each by type (Member, Supplier, Prospect, New Member). </p>
<p>The HTML (check boxes wired up with <code>sort()</code> function): </p>
<pre><code><input type="checkbox" value="Supplier" onclick="sort()" id="switch2" />
<label for="switch2">Suppliers</label>
</code></pre>
<p>The JavaScript:</p>
<pre><code>var markersArray = [];
// data schema ['Company Name',"Address",Latitude,Longitude,"Type"]
var data = [
['Company A',"Address",Latitude,Longitude,"Member"],
['Company B',"Address",Latitude,Longitude,"Supplier"],
['Company C',"Address",Latitude,Longitude,"Prospect"],
];
function initialize(data) {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(40, -90)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create the legend with content
var legend = document.createElement('div');
legend.id = 'legend';
var content = [];
content.push('<h3>Legend</h3>');
content.push('<p><div class="legIcon"> <img src="pin_blue.png" alt="icon color" /> </div>Members</p>');
content.push('<p><div class="legIcon"> <img src="pin_red.png" alt="icon color" /> </div>Suppliers</p>');
content.push('<p><div class="legIcon"> <img src="pin_purple.png" alt="icon color" /> </div>New Members</p>');
content.push('<p><div class="legIcon"> <img src="pin_green.png" alt="icon color" /> </div>Prospects</p>');
legend.innerHTML = content.join('');
legend.index = 1;
// call the legend
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
setMarkers(map, data);
}
function setMarkers(map, locations) {
if (locations == undefined) {
locations = data;
return initialize(locations);
}
for (var i = locations.length - 1; i >= 0; i--) {
var company = locations[i],
pinColor = '';
var myLatLng = new google.maps.LatLng(company[2], company[3]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: company[0],
type: company[4]
});
markersArray.push(marker);
if ( marker.type === 'Member' ) { pinColor = 'blue' }
else if ( marker.type === 'New') { pinColor = 'purple' }
else if ( marker.type === 'Supplier') { pinColor = 'red' }
else { pinColor = 'green' }
var image = {
url: 'pin_' + pinColor + '.png',
size: new google.maps.Size(100, 100),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(20, 40)
};
};
}
// initialize map with empty array
google.maps.event.addDomListener(window, 'load', function (data) { initialize([]) });
// standalone functions
function clearOverlays () {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function resetPins () {
clearOverlays();
}
// sort and collect with sliding buttons (checkboxes)
function sort () {
var newData = [];
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
}
// clear the unchecked
else {
clearOverlays();
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// call the boxes
var checkedBoxes = getCheckedBoxes("switch");
for (var i = 0; i < checkedBoxes.length; i++) {
data.forEach(function (d) {
if ( d[4] === checkedBoxes[i] ) {
newData.push(d);
};
});
}
if (newData.length > 0) {
return initialize(newData);
}
else {
return initialize(data);
}
}
</code></pre>
<p>I have not written a ton of vanilla JavaScript, so I would like some advice on how to clean this up. The obvious: some loops count down, other up, there are various <code>if</code>/<code>else</code> statements that I feel may be superfluous, using <code>.forEach</code> inside a <code>for</code> loop. </p>
<p>Curiously, when the code runs, it skips the first element of data when assigning the custom pin as .png. Why does this code not hit the first element in the array?</p>
| [] | [
{
"body": "<p>Let's be frank - this code is a mess.</p>\n\n<ul>\n<li><p>A bunch of global variables and functions. That's never good. You should at least wrap these inside a container function. Or better - turn it into an object.</p></li>\n<li><p>In the middle of the function definitions there's suddenly call to <code>google.maps.event.addDomListener()</code>. Don't mix the definitions and code that does something. Bring all the initialization into one area.</p></li>\n<li><p>You knew already that the backwards for-loop is troublesome. You should have fixed it before submitting. Don't submit code that you know is poor. </p></li>\n<li><p>But when I look at the end of this for-loop... WTF? You are creating an <code>image</code> object and then you just throw it away. Is this code unfinished?</p></li>\n<li><p>For some reason the <code>getCheckedBoxes</code> function is defined inside <code>sort</code> function. Why?</p></li>\n<li><p>Inside <code>clearOverlays</code> you reset the <code>markersArray</code> by doing <code>markersArray.length = 0</code>. That's not a proper way to reset an array. Instead just assign an empty array to replace the old one: <code>markersArray = []</code>.</p></li>\n<li><p><code>resetPins</code> is just an alias to <code>clearOverlays</code>. Besides it's not used. Throw away the dead code.</p></li>\n<li><p>The <code>sort</code> function doesn't seem to be doing any sorting. Don't call it <code>sort</code> if it just switches groups of markers on and off.</p></li>\n<li><p>Too many other issues to mention...</p></li>\n</ul>\n\n<p>Most importantly, try to care about your code. If you put your code out for others to see (by posting it here), try to first make it as good as you possibly can. Remove dead code. Fix the problems that you know about. Post a complete example, not half-finished one. Structure it so that it's as easy to read and understand as possible. Run it through JSHint and fix all the warnings, so you that people will not need to point out the mistakes that a stupid machine could have told you about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:14:07.207",
"Id": "81042",
"Score": "0",
"body": "Thanks Rene. Yes, it is unfinished, I am refactoring now and appreciate your guidance on improving the code. \"Or better - turn it into an object.\" How would this look?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:23:53.803",
"Id": "81045",
"Score": "0",
"body": "For Loops: I left both styles in to evoke discussion on which is most suitable. After turning to this: http://stackoverflow.com/questions/1340589/javascript-are-loops-really-faster-in-reverse its clear there is no clear answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:14:14.063",
"Id": "81060",
"Score": "1",
"body": "By turning it into an object I meant writing it all in object-oriented style. You would basically turn it into a class, though as there are no real classes in JavaScript, that would mean creating a constructor function and adding the other functions as methods in its prototype. More on this topic: [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:28:27.807",
"Id": "81062",
"Score": "1",
"body": "Regarding the backwards loop: (1) Only optimize when there's an actual bottleneck, otherwise strive for most readable code; (2) don't rely on micro-benchmarks, measure the difference with your own actual code. Most likely this code doesn't really have to be blazing fast, so you're much better off using `Array.forEach()` and other methods that better convey the intention of your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:07:53.347",
"Id": "81174",
"Score": "0",
"body": "\"You are creating an image object and then you just throw it away.\" Could you elaborate on this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:25:25.957",
"Id": "81199",
"Score": "0",
"body": "Inside setMarkers() you define `var image` and then the loop and function end and the image variable is used nowhere."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:15:59.597",
"Id": "46376",
"ParentId": "46371",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46376",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:04:32.530",
"Id": "46371",
"Score": "3",
"Tags": [
"javascript",
"html",
"sorting",
"google-maps"
],
"Title": "Google Maps JavaScript API v3: Sorting Markers with Check Boxes"
} | 46371 |
<p><strong>MonoGame</strong> is an Open Source implementation of the Microsoft XNA 4 Framework. Our goal is to allow XNA developers on Xbox 360, Windows & Windows Phone to port their games to the iOS, Android, Mac OS X, Linux and Windows 8 Metro. PlayStation Mobile, Raspberry PI, and PlayStation 4 platforms are currently in progress.</p>
<p>MonoGame was started to allow users to port their XboX games to other consoles and operating systems, now that Microsoft has dropped support for XNA MonoGame is the only current code for programming with C#.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:39:31.640",
"Id": "46372",
"Score": "0",
"Tags": null,
"Title": null
} | 46372 |
MonoGame is an Open Source implementation of the Microsoft XNA 4 Framework. Our goal is to allow XNA developers on Xbox 360, Windows & Windows Phone to port their games to the iOS, Android, Mac OS X, Linux and Windows 8 Metro. PlayStation Mobile, Raspberry PI, and PlayStation 4 platforms are currently in progress. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:39:31.640",
"Id": "46373",
"Score": "0",
"Tags": null,
"Title": null
} | 46373 |
<p>We are following passive controller approach and when user clicks on submit, server side validations are fired. There are many other fields on the screen that needs to be validated.</p>
<p>I would like to get feedback about the following approach.</p>
<ol>
<li>Is it ok to have validations in Presenter.</li>
<li>As there are many fields in UI, <code>PerformServerValidations()</code> method is getting big. Is there any way I could refactor it.</li>
<li><p>Intention behind declaring <code>PerformServerValidations()</code> as public and returning a IList is to be able to test it. Is it a good approach to take? </p>
<pre><code>[TestMethod]
public void Presenter_PerformServerValidations_ValidateFromCustomerId_ExpectFalseForInvalidNumber()
{
//creating presenter
presenter.View.Stub(x=>x.FromCustomerId).Return("one two three");
var errorCodes = presenter.PerformServerValidations();
Assert.IsTrue(errorCodes.Contains("ERR_InvalidFromCustomerId"));
}
</code></pre></li>
</ol>
<p><strong>Presenter.cs</strong></p>
<pre><code>public void OnSubmit()
{
var serverValidationErrors = PerformServerValidations();
this.View.ServerErrors = serverValidationErrors ; // View.ServerErrors will loop over the list and sets validator's IsValid property to false
if(!serverValidationErrors.Any())
{
BindCustomers();
}
}
public IList<string> PerformServerValidations()
{
var errorCodes = new List<string>();
int parsedFromCustomerId;
int parsedToCustomerId;
bool isValidFromCustomerId = int.TryParse(this.View.FromCustomerId, out
parsedFromCustomerId);
bool isValidToCustomerId = int.TryParse(this.View.ToCustomerId, out parsedToCustomerId);
if(!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !isValidFromCustomerId)
{
errorCodes.Add("ERR_InvalidFromCustomerId");
}
if(!string.IsNullOrWhiteSpace(this.View.ToCustomerId) && !isValidToCustomerId)
{
errorCodes.Add("ERR_InvalidToCustomerId");
}
if((!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !string.IsNullOrWhiteSpace(this.View.FromCustomerId) && (isValidFromCustomerId && isValidFromCustomerId))
{
if(parsedFromCustomerId > parsedFromCustomerId)
{
errorCodes.Add("ERR_InvalidCustomerIdRange");
}
}
//There are many other fields to be validated
return errorCodes;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:25:48.630",
"Id": "81046",
"Score": "1",
"body": "please don't make the changes in the code, it invalidates the answers and makes it hard for someone new to the question follow along"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:26:40.197",
"Id": "81047",
"Score": "0",
"body": "add an `Edit:` to the question and post the correct code. when everything is fixed you could also post a new question as well..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:32:11.857",
"Id": "81052",
"Score": "0",
"body": "you are welcome. if you have questions about how Code Review works just ask any of us in [The Second Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) and we will be more than happy to help you out. all the new questions are posted there by Stack Exchange as well."
}
] | [
{
"body": "<p>I think you have a typo in the last outside if statement, I assume you meant two different variables when you wrote this: </p>\n\n<pre><code>if((!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !string.IsNullOrWhiteSpace(this.View.FromCustomerId) && (isValidFromCustomerId && isValidFromCustomerId))\n{ \n if(parsedFromCustomerId > parsedFromCustomerId)\n {\n errorCodes.Add(\"ERR_InvalidCustomerIdRange\");\n }\n}\n</code></pre>\n\n<p><code>parsedFromCustomerId</code> will never be greater than <code>parsedFromCustomerId</code></p>\n\n<p>and the obvious one that won't cause a bug but probably won't give you the intended results is</p>\n\n<pre><code> (isValidFromCustomerId && isValidFromCustomerId)\n</code></pre>\n\n<p>I assume you mean to put a different boolean variable in there instead of the same one twice.</p>\n\n<p>this code won't function, correctly. </p>\n\n<p>probably a Typo but you should proofread your code again just to make sure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:19:52.757",
"Id": "46383",
"ParentId": "46378",
"Score": "4"
}
},
{
"body": "<p>I'm not familiar with C#, just a few minor generic notes:</p>\n\n<ol>\n<li><p>I guess you have a typo here, the following is always false:</p>\n\n<blockquote>\n<pre><code>if(parsedFromCustomerId > parsedFromCustomerId) ...\n</code></pre>\n</blockquote></li>\n<li><p>Another one: the first condition is duplicated here (as well as the third one):</p>\n\n<blockquote>\n<pre><code>if((!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !string.IsNullOrWhiteSpace(this.View.FromCustomerId) && (isValidFromCustomerId && isValidFromCustomerId))\n</code></pre>\n</blockquote></li>\n<li><p>I'd put the comment a line before:</p>\n\n<blockquote>\n<pre><code>this.View.ServerErrors = serverValidationErrors ; // View.ServerErrors will loop over the list and sets validator's IsValid property to false\n</code></pre>\n</blockquote>\n\n<p>The following is easier to read since it does not require any horizontal scrolling:</p>\n\n<pre><code>// View.ServerErrors will loop over the list and sets validator's IsValid property to false\nthis.View.ServerErrors = serverValidationErrors ; \n</code></pre></li>\n<li><p><code>!string.IsNullOrWhiteSpace(this.View.FromCustomerId)</code> is also used by the first <code>if</code> statement. I would create an explanatory variable for it:</p>\n\n<pre><code>bool nonEmptyFromCustomerId = !string.IsNullOrWhiteSpace(this.View.FromCustomerId);\nif (nonEmptyFromCustomerId && !isValidFromCustomerId)\n{ \n errorCodes.Add(\"ERR_InvalidFromCustomerId\");\n}\n\n...\n\nif ((nonEmptyFromCustomerId) && ...\n...\n</code></pre>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><p>If you are using the following statements multiple times consider creating a <a href=\"http://xunitpatterns.com/Custom%20Assertion.html#Verification%20Method\" rel=\"nofollow\">custom verification method</a> for it:</p>\n\n<blockquote>\n<pre><code>var errorCodes = presenter.PerformServerValidations();\n\nAssert.IsTrue(errorCodes.Contains(\"ERR_InvalidFromCustomerId\"));\n</code></pre>\n</blockquote>\n\n<p>For example:</p>\n\n<pre><code>public void VerifyValidationErrorCodesContain(Presenter presenter, string expectedErrorCode)\n{\n var errorCodes = presenter.PerformServerValidations();\n Assert.IsTrue(errorCodes.Contains(expectedErrorCode));\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:22:23.477",
"Id": "46384",
"ParentId": "46378",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:42:39.913",
"Id": "46378",
"Score": "4",
"Tags": [
"c#",
"asp.net",
"unit-testing",
"mvp"
],
"Title": "Server side validations and unit testing in MVP"
} | 46378 |
<p>I solved <a href="http://projecteuler.net/problem=1" rel="nofollow">this</a> a while ago. In the moment I solved it I was learning Scheme and, well, I still am. I'm not looking at the best solution (I searched for it and coded it already, in Python), what I want is to improve this code, maintaining the same (brute) approach, so I can learn some best practices and tips in Scheme. Maybe there are some suggestions on how I wrote the routines, for example.</p>
<pre><code>#lang racket
(define (check x) (or (= (modulo x 3) 0)
(= (modulo x 5) 0)))
(define (count-check x) (if (check x)
x
0))
(define (sum-multiples-rec actual limit acc) (if (< actual limit)
(sum-multiples-rec (+ actual 1) limit (+ (count-check actual) acc))
acc))
(define (sum-multiples lower-limit upper-limit) (sum-multiples-rec lower-limit upper-limit 0))
(sum-multiples 0 1000)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:08:49.223",
"Id": "81040",
"Score": "1",
"body": "Not sure how it happened, but it doesn't look like the code is valid right now. I believe you intended something more like: `(define (sum-multiples lower-limit upper-limit) (sum-multiples-rec lower-limit upper-limit 0))`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T13:05:16.840",
"Id": "81139",
"Score": "0",
"body": "Yeah, that's... correct. Man, what a good starting point! =)"
}
] | [
{
"body": "<p>So, any time you want to write a \"helper\" recursive function, the standard way to write that is to use a named <code>let</code>. So here's how I might restructure your program (but keeping the same algorithm):</p>\n\n<pre><code>(define (sum-multiples start end)\n (let loop ((sum 0)\n (i start))\n (cond ((>= i end) sum)\n ((or (zero? (modulo i 3))\n (zero? (modulo i 5)))\n (loop (+ sum i) (add1 i)))\n (else (loop sum (add1 i))))))\n</code></pre>\n\n<p>Named <code>let</code> is a macro, which in this case expands to the same expression as:</p>\n\n<pre><code>(define (sum-multiples start end)\n ((letrec ((loop (lambda (sum i)\n (cond ((>= i end) sum)\n ((or (zero? (modulo i 3))\n (zero? (modulo i 5)))\n (loop (+ sum i) (add1 i)))\n (else (loop sum (add1 i)))))))\n loop)\n 0 start))\n</code></pre>\n\n<p>(I've taken the liberty of using <code>(add1 i)</code> instead of <code>(+ i 1)</code> since you're using Racket.)</p>\n\n<hr>\n\n<p>Here's a version that's even more Rackety, using <code>for/sum</code> to accumulate the sum rather than using a manual loop:</p>\n\n<pre><code>(define (sum-multiples start end)\n (for/sum ((i (range start end)))\n (if (or (zero? (modulo i 3))\n (zero? (modulo i 5)))\n i 0)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:02:32.760",
"Id": "81336",
"Score": "0",
"body": "Thanks for the help, the first code is very interesting. I see in the documentation that a named `let` works as some sort of lambda. I still need to read a little more, though, it's rather confusing for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:22:10.873",
"Id": "81340",
"Score": "0",
"body": "@ArthurChamz Yes, it is a kind of lambda. Let me update the post to detail how it would be expanded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:29:41.853",
"Id": "81346",
"Score": "1",
"body": "Thanks, I still have some things to learn about Scheme, but this is an awesome start!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:55:42.457",
"Id": "46386",
"ParentId": "46379",
"Score": "6"
}
},
{
"body": "<p>As noted in the comment, your code currently looks like it has a (admittedly fairly minor) problem. In <code>sum-multiples</code>, you try to pass <code>actual</code> and <code>limit</code> as parameters to <code>sum-multiples-rec</code>, but those names aren't bound to anything at that point. You need/want something more like:</p>\n\n<pre><code>(define (sum-multiples lower-limit upper-limit) \n (sum-multiples-rec lower-limit upper-limit 0))\n</code></pre>\n\n<p>As far as style goes, the main thing I'd change would be to write your ancillary functions inside of <code>sum-multiples</code>. Right now, <code>sum-multiples-rec</code>, <code>count-check</code> and <code>check</code> are all \"publicly\" visible, but they're unlikely to be of any use except to <code>count-multiples</code>. As such, they should really be \"hidden\" inside it.</p>\n\n<p>As such, your code could end up something like this:</p>\n\n<pre><code>(define (sum-multiples lower-limit upper-limit) \n (define (sum-multiples-rec actual limit acc)\n (define (count-check x) \n (define (check x) (or (= (modulo x 3) 0)\n (= (modulo x 5) 0)))\n (if (check x) \n x \n 0))\n (if (< actual limit)\n (sum-multiples-rec (+ actual 1) limit (+ (count-check actual) acc))\n acc)) \n (sum-multiples-rec lower-limit upper-limit 0))\n</code></pre>\n\n<p>[Indentation probably open to improvement]</p>\n\n<p>So, <code>check</code> is only defined/visible inside of <code>count-check</code>. <code>count-check</code> (in turn) is only defined/visible inside of <code>sum-multiples-rec</code>, and <code>sum-multiples-rec</code> is only defined/visible inside of <code>sum-multiples</code>. If (for example) you try to execute something like <code>(check 3)</code> outside of <code>sum-multiples</code>, you'll get an error like:</p>\n\n<pre><code>check: undefined; cannot reference an identifier before its definition\n</code></pre>\n\n<p>This is pretty much the same general idea as (for example) a class in something like Java or C++ making as many if its members private as possible. Limiting the visibility of names dramatically reduces the chances of a name collision that could result in your calling entirely the wrong function. This is particularly important with names like <code>check</code> that could mean all sorts of different things under different circumstances.</p>\n\n<p>Of course, much like with those other languages, this sort of discipline becomes much more important for larger programs. For a really tiny program, it's not all that big of a deal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:55:33.237",
"Id": "81333",
"Score": "0",
"body": "Again, thanks for pointing out the mistake. I didn't know how to \"encapsulate\" functions in Scheme, thank you very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T16:58:29.027",
"Id": "46387",
"ParentId": "46379",
"Score": "3"
}
},
{
"body": "<p>Better programming practice would be to decompose the problem in such a way that the procedures adhere to the Single Responsibility Principle. In other words, the answer should be obtained by evaluating something like</p>\n\n<pre><code>(sum (filter (multiple-of-any? 3 5) (range 0 1000)))\n</code></pre>\n\n<p>… which reads just like the problem to be solved.</p>\n\n<p>Here's a set of functions that could achieve that. Note that, unlike the functions you've defined (<code>check</code>, <code>count-check</code>, <code>sum-multiples-rec</code>, <code>sum-multiples</code>), which are highly specific to solving Project Euler Problem 1, these functions are flexible and could likely be reused to solve other problems.</p>\n\n<pre><code>(define (sum list)\n (if (eq? list '())\n 0\n (+ (car list) (sum (cdr list)))))\n\n(define (range min max)\n (if (= min max) \n '()\n (cons min (range (+ min 1) max))))\n\n(define (filter pred? list)\n (cond ((eq? list '()) list)\n ((pred? (car list)) (cons (car list) (filter pred? (cdr list))))\n (else (filter pred? (cdr list)))))\n\n(define (multiple-of-any? . divisors)\n (lambda (n) (cond ((eq? divisors '()) #f)\n ((= 0 (modulo n (car divisors))) #t)\n (else ((apply multiple-of-any? (cdr divisors)) n)))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:00:48.637",
"Id": "81148",
"Score": "1",
"body": "In the name of library reuse, I recommend using [SRFI 1](http://srfi.schemers.org/srfi-1/srfi-1.html) for `range` (called [`iota`](http://srfi.schemers.org/srfi-1/srfi-1.html#iota) in SRFI 1) and [`filter`](http://srfi.schemers.org/srfi-1/srfi-1.html#filter). `sum` is easily defined using `(apply + lst)` or `(reduce + 0 lst)` ([`reduce`](http://srfi.schemers.org/srfi-1/srfi-1.html#reduce) is in SRFI 1). This way, you can get rid of all the manual loops."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:01:59.747",
"Id": "81149",
"Score": "1",
"body": "And of course, instead of the manual loop in `multiple-of-any?`, simply use SRFI 1's [`any`](http://srfi.schemers.org/srfi-1/srfi-1.html#any). Also, since this is a Racket question, you can load SRFI 1 using `(require srfi/1)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:06:44.303",
"Id": "81337",
"Score": "0",
"body": "Mmm, it is much more flexible than my approach. What does `'()` mean, which I see many times in the code? There are some things I don't get about the code, but this is used many times..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:26:59.967",
"Id": "81343",
"Score": "0",
"body": "@ArthurChamz `'()` is an expression that returns the literal datum for an empty list, in the same way that `'(foo)` is an expression that returns the literal datum for a list that contains the symbol `foo` as its sole element. There are other expressions that also return an empty list, such as `(list)`, but `'()` is the most common way to write it in Scheme."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:35:06.247",
"Id": "81365",
"Score": "0",
"body": "@ChrisJester-Young [`any`](http://srfi.schemers.org/srfi-1/srfi-1.html#any) doesn't help. I need to test if any of the _divisors_ work, i.e. test several _predicates_."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:40:27.720",
"Id": "81367",
"Score": "1",
"body": "@200_success Sure it works: `(define (multiple-of-any? . divisors) (lambda (n) (any (lambda (i) (zero? (modulo n i))) divisors)))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:53:33.773",
"Id": "81371",
"Score": "0",
"body": "Alternatively, you can use Racket's `ormap`, which does pretty much the same thing as SRFI 1's `any`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T08:38:47.043",
"Id": "46438",
"ParentId": "46379",
"Score": "6"
}
},
{
"body": "<p>The approach you have taken is to check each number between 0 and 1000 to see if it is a multiple of either 3 or 5, and if so, add it to the accumulator.</p>\n\n<p>A more straightforward solution is to use the <a href=\"http://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle\" rel=\"nofollow\">Inclusion-Exclusion Principle</a>. Add the multiples of 3 and the multiples of 5. Since the multiples of 15 are double-counted, subtract the multiples of 15.</p>\n\n<pre><code>(define (sum list)\n (if (eq? list '())\n 0\n (+ (car list) (sum (cdr list)))))\n\n(define (multiples min max step)\n (if (>= min max)\n '()\n (cons min (multiples (+ min step) max step))))\n\n(- (+ (sum (multiples 0 1000 3))\n (sum (multiples 0 1000 5)))\n (sum (multiples 0 1000 15)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:18:44.857",
"Id": "81152",
"Score": "1",
"body": "Here, of course, `multiples` can be replaced by SRFI 1's `iota` too. :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T10:08:57.847",
"Id": "46442",
"ParentId": "46379",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46386",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:45:14.880",
"Id": "46379",
"Score": "6",
"Tags": [
"beginner",
"scheme",
"programming-challenge",
"racket"
],
"Title": "Project Euler 1 (sum of multiples of 3 or 5 under 1000)"
} | 46379 |
<p>I am creating a class to be the end all defacto class for handling unit conversions. This is particularly difficult in my company's industry where imperial architectural strings are used as units. I wanted this class to be perfect in just about every way as it is the class that we will be giving our summer interns as the best example of how to write a class. By posting it here, I wanted to make sure that it is the best example! </p>
<p>The references to the <code>DimensionConverter</code> class is to a private class built just for this purpose. (I would like it reviewed as well... but I don't know how to post two classes appropriately here on Code Review.)</p>
<p>What else could I possibly improve about the way this class is written in the context of readability, ease of maintenance, and logical design?</p>
<pre><code>namespace TypeLibrary
{
/// <summary>
/// Class used for storing dimensions that may need to be accessed in a different measurement system
/// Will accept anything as input
/// <example>
/// decimal inches into AutoCAD notation
///
/// double inches = 14.1875
/// Dimension dm = new Dimension( inches, DimensionTypes.Inch);
///
/// Print(dm.Architectural)
///
/// ========Output==========
/// 1'2 3/16"
///
/// </example>
/// </summary>
public class Dimension
{
#region internal variables
//internal Dimension type is set to milimeter to cause the least amount of rounding error when performing calculations.
const DimensionTypes internalUnitType = DimensionTypes.Millimeter;
//dimension value
private double internalDecimalUnit = 0.0;
#endregion
#region Constructors
/// <summary>
/// Accepts any string value for input.
/// </summary>
public Dimension(string passedArchitecturalString)
{
storeArchitecturalStringAsInternalUnit(passedArchitecturalString);
}
/// <summary>
/// Accepts any type of value for input. This allows for less complexity in building applications
/// </summary>
public Dimension(double passedInput, DimensionTypes passedDimensionType)
{
internalDecimalUnit = DimensionConverter.ConvertDimension(passedDimensionType, passedInput, internalUnitType);
}
/// <summary>
/// Copy Constructor
/// </summary>
public Dimension(Dimension passedDimension)
{
this.internalDecimalUnit = passedDimension.internalDecimalUnit;
}
#endregion
#region Properties
public double Sixteenths
{
get { return retrieveAsExternalUnit(DimensionTypes.Sixteenth); }
set { storeAsInternalUnit(DimensionTypes.Sixteenth, value); }
}
public double ThirtySeconds
{
get { return retrieveAsExternalUnit(DimensionTypes.ThirtySecond); }
set { storeAsInternalUnit(DimensionTypes.ThirtySecond, value); }
}
public double Inches
{
get { return retrieveAsExternalUnit(DimensionTypes.Inch); }
set { storeAsInternalUnit(DimensionTypes.Inch, value); }
}
public double Feet
{
get { return retrieveAsExternalUnit(DimensionTypes.Foot); }
set { storeAsInternalUnit(DimensionTypes.Foot, value); }
}
public double Yards
{
get { return retrieveAsExternalUnit(DimensionTypes.Yard); }
set { storeAsInternalUnit(DimensionTypes.Yard, value); }
}
public double Miles
{
get { return retrieveAsExternalUnit(DimensionTypes.Mile); }
set { storeAsInternalUnit(DimensionTypes.Mile, value); }
}
public double Millimeters
{
get { return retrieveAsExternalUnit(DimensionTypes.Millimeter); }
set { storeAsInternalUnit(DimensionTypes.Millimeter, value); }
}
public double Centimeters
{
get { return retrieveAsExternalUnit(DimensionTypes.Centimeter); }
set { storeAsInternalUnit(DimensionTypes.Centimeter, value); }
}
public double Meters
{
get { return retrieveAsExternalUnit(DimensionTypes.Meter); }
set { storeAsInternalUnit(DimensionTypes.Meter, value); }
}
public double Kilometers
{
get { return retrieveAsExternalUnit(DimensionTypes.Kilometer); }
set { storeAsInternalUnit(DimensionTypes.Kilometer, value); }
}
/// <summary>
/// Returns the dimension as a string in AutoCAD notation with sixteenths of an inch percision
/// </summary>
public string Architectural
{
get { return retrieveInternalUnitAsArchitecturalString(); }
set {storeArchitecturalStringAsInternalUnit(value); }
}
#endregion
#region helper methods
private void storeAsInternalUnit(DimensionTypes fromDimensionType, double passedValue)
{
internalDecimalUnit = DimensionConverter.ConvertDimension( DimensionTypes.Kilometer, passedValue, internalUnitType);
}
private void storeArchitecturalStringAsInternalUnit(string passedArchitecturalString)
{
internalDecimalUnit = DimensionConverter.ConvertArchitecturalStringToDecimalDimension(internalUnitType, passedArchitecturalString);
}
private double retrieveAsExternalUnit(DimensionTypes toDimensionType)
{
return DimensionConverter.ConvertDimension(internalUnitType, internalDecimalUnit, toDimensionType);
}
private string retrieveInternalUnitAsArchitecturalString()
{
return DimensionConverter.ConvertDecimalDimensionToArchitecturalString(internalUnitType, internalDecimalUnit);
}
#endregion
#region Overloaded Operators
/* You may notice that we do not overload the increment and decrement operators.
* This is because the user of this library
* does not know what is being internally stored. We could have allowed a parameter
* into a custom operater and method of our own, but that would have added unnecessary
* complexity.
*/
public static Dimension operator +(Dimension d1, Dimension d2)
{
//add the two dimensions together
//return a new dimension with the new value
return new Dimension((d1.internalDecimalUnit + d2.internalDecimalUnit), internalUnitType);
}
public static Dimension operator -(Dimension d1, Dimension d2)
{
//subtract the two dimensions
//return a new dimension with the new value
return new Dimension((d1.internalDecimalUnit - d2.internalDecimalUnit), internalUnitType);
}
public static Dimension operator *(Dimension d1, Dimension d2)
{
//multiply the two dimensions
//return a new dimension with the new value
return new Dimension((d1.internalDecimalUnit * d2.internalDecimalUnit), internalUnitType);
}
public static Dimension operator /(Dimension d1, Dimension d2)
{
//divide the two dimensions
//return a new dimension with the new value
return new Dimension((d1.internalDecimalUnit / d2.internalDecimalUnit), internalUnitType);
}
public static Dimension operator %(Dimension d1, Dimension d2)
{
//Modulous the two dimensions
//return a new dimension with the new value
return new Dimension((d1.internalDecimalUnit % d2.internalDecimalUnit), internalUnitType);
}
public static bool operator ==(Dimension d1, Dimension d2)
{
//compare the two dimensions for equality
//return a bool based on their relative values
if (d1.internalDecimalUnit == d2.internalDecimalUnit)
{
return true;
}
else
{
return false;
}
}
public static bool operator !=(Dimension d1, Dimension d2)
{
//compare the two dimensions for equality
//return a bool based on their relative values
if (d1.internalDecimalUnit != d2.internalDecimalUnit)
{
return true;
}
else
{
return false;
}
}
public static bool operator >(Dimension d1, Dimension d2)
{
//compare the two dimensions together
//return a bool based on their relative values
if (d1.internalDecimalUnit > d2.internalDecimalUnit)
{
return true;
}
else
{
return false;
}
}
public static bool operator <(Dimension d1, Dimension d2)
{
//compare the two dimensions together
//return a bool based on their relative values
if (d1.internalDecimalUnit < d2.internalDecimalUnit)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// This override determines how this object is inserted into hashtables.
/// </summary>
/// <returns>same hashcode as any double would</returns>
public override int GetHashCode()
{
return internalDecimalUnit.GetHashCode();
}
public override string ToString()
{
throw new NotImplementedException("The Dimension class does not know what type of unit it contains, (Because it should be thought of containing all unit types) Call dimension.[unit].Tostring() instead");
}
#endregion
}
}
</code></pre>
<p>The second class that does the real work</p>
<pre><code>namespace TypeLibrary
{
/// <summary>
/// Contains all dimension conversion tools
/// </summary>
internal static class DimensionConverter
{
#region private functions
/// <summary>
/// Converts any possible type of Architectual String into Millimeters
/// <remarks>Throws FormatException on bad input</remarks>
/// </summary>
/// <param name="arch">the input string</param>
/// <returns>decimal Millimeters</returns>
private static Double ConvertArchitectualStringtoMillimeters(String arch)
{
// for details on where this solution came from, check here: http://stackoverflow.com/questions/22794466/parsing-all-possible-types-of-varying-architectural-dimension-input
// answer by Trygve Flathen: http://stackoverflow.com/users/2795177/trygve-flathen
String expr = "^\\s*(?<minus>-)?\\s*(((?<feet>\\d+)(?<inch>\\d{2})(?<sixt>\\d{2}))|((?<feet>[\\d.]+)')?[\\s-]*((?<inch>\\d+)?[\\s-]*((?<numer>\\d+)/(?<denom>\\d+))?\")?)\\s*$";
Match m = new Regex(expr).Match(arch);
if (!m.Success || arch.Trim() == "" || arch.Trim() == "\"")
{
FormatException exception = new FormatException("Input was not a valid architectural string");
ExceptionHandler.ProcessException(exception);
throw exception;
}
Int32 sign = m.Groups["minus"].Success ? -1 : 1;
Double feet = m.Groups["feet"].Success ? Convert.ToDouble(m.Groups["feet"].Value) : 0;
Int32 inch = m.Groups["inch"].Success ? Convert.ToInt32(m.Groups["inch"].Value) : 0;
Int32 sixt = m.Groups["sixt"].Success ? Convert.ToInt32(m.Groups["sixt"].Value) : 0;
Int32 numer = m.Groups["numer"].Success ? Convert.ToInt32(m.Groups["numer"].Value) : 0;
Int32 denom = m.Groups["denom"].Success ? Convert.ToInt32(m.Groups["denom"].Value) : 1;
double result = sign * (feet * 12 + inch + sixt / 16.0 + numer / Convert.ToDouble(denom));
return ConvertDimension(DimensionType.Millimeter, result, DimensionType.Inch);
}
/// <summary>
/// Returns a string formatted in a standard AutoCAD format
/// </summary>
/// <param name="num"> the number being converted into a string</param>
/// <returns></returns>
private static string ConvertMillimetersToArchitecturalString(double num, int precision = 16)
{
//Convert into inches before proceeding
num = ConvertDimension(DimensionType.Inch, num, DimensionType.Millimeter);
string functionReturnValue = "";
int feet = 0;
int inches = 0;
string FeetString = "";
string InchesString = "";
int numerator = 0;
string sign = "";
string fractionString = "";
//detect need for sign
if (num < 0)
{
sign = "-";
num = num * -1;
}
feet = Convert.ToInt32(num / 12);
num = num - (feet * 12);
inches = Convert.ToInt32(num);
num = num - inches;
numerator = Convert.ToInt32(num * precision);
if (numerator >= 32)
{
numerator = numerator - precision;
inches = inches + 1;
}
fractionString = numerator + "/" + precision.ToString() + "\"";
if (feet == 0)
{
FeetString = "";
}
else
{
FeetString = Convert.ToString(feet);
}
if (inches == 0)
{
InchesString = "";
}
else
{
InchesString = Convert.ToString(inches);
}
if (string.IsNullOrEmpty(sign) & string.IsNullOrEmpty(FeetString))
{
functionReturnValue = (InchesString + " " + fractionString).Trim();
}
else
{
functionReturnValue = (sign + FeetString + "' " + InchesString + " " + fractionString).Trim();
}
return functionReturnValue;
}
#endregion
#region public functions
/// <summary>
/// Converts any dimension into another
/// </summary>
/// <param name="typeConvertingTo">input unit type</param>
/// <param name="typeConvertingFrom">desired output unit type</param>
/// <returns>converted dimension</returns>
public static double ConvertDimension(DimensionType typeConvertingFrom, double passedValue, DimensionType typeConvertingTo)
{
double returnDouble = 0.0;
double internalDecimalMillimeters = 0.0;
//first convert value passedValue to inches
switch (typeConvertingFrom)
{
case DimensionType.ThirtySecond:
internalDecimalMillimeters = (passedValue / 32) * 0.0393701;
break;
case DimensionType.Sixteenth:
internalDecimalMillimeters = (passedValue / 16) * 0.0393701;
break;
case DimensionType.Inch:
internalDecimalMillimeters = passedValue * 25.4;
break;
case DimensionType.Foot:
internalDecimalMillimeters = passedValue * 304.8;
break;
case DimensionType.Yard:
internalDecimalMillimeters = passedValue * 914.4;
break;
case DimensionType.Mile:
internalDecimalMillimeters = passedValue * 1609344;
break;
case DimensionType.Millimeter:
internalDecimalMillimeters = passedValue;
break;
case DimensionType.Centimeter:
internalDecimalMillimeters = passedValue * 10;
break;
case DimensionType.Meter:
internalDecimalMillimeters = passedValue * 1000;
break;
case DimensionType.Kilometer:
internalDecimalMillimeters = passedValue * 1000000;
break;
}
//Now convert the value from inches to the desired output
switch (typeConvertingTo)
{
case DimensionType.ThirtySecond:
returnDouble = (internalDecimalMillimeters / 0.0393701) * 32;
break;
case DimensionType.Sixteenth:
returnDouble = (internalDecimalMillimeters / 0.0393701) * 16;
break;
case DimensionType.Inch:
returnDouble = internalDecimalMillimeters / 25.4;
break;
case DimensionType.Foot:
returnDouble = internalDecimalMillimeters / 304.8;
break;
case DimensionType.Yard:
returnDouble = internalDecimalMillimeters / 914.4;
break;
case DimensionType.Mile:
returnDouble = internalDecimalMillimeters / 1609344;
break;
case DimensionType.Millimeter:
returnDouble = internalDecimalMillimeters;
break;
case DimensionType.Centimeter:
returnDouble = internalDecimalMillimeters / 10;
break;
case DimensionType.Meter:
returnDouble = internalDecimalMillimeters / 1000;
break;
case DimensionType.Kilometer:
returnDouble = internalDecimalMillimeters / 1000000;
break;
}
return returnDouble;
}
/// <summary>
/// Converts Architectural strings into a decimal unit
/// </summary>
public static double ConvertArchitecturalStringToDecimalDimension(DimensionType typeConvertingTo, string passedValue)
{
double internalDecimalMillimeters = 0.0;
//first convert value passedValue to millimeters
internalDecimalMillimeters = ConvertArchitectualStringtoMillimeters(passedValue);
//Now convert the value from millimeters to the desired output
double result = ConvertDimension(DimensionType.Millimeter, internalDecimalMillimeters, typeConvertingTo);
return result;
}
/// <summary>
/// Converts any dimension into an architectural string representation
/// </summary>
/// <param name="typeConvertingFrom">desired output unit type</param>
/// <returns>converted dimension</returns>
public static string ConvertDecimalDimensionToArchitecturalString(DimensionType typeConvertingFrom, double passedValue)
{
double internalDecimalMillimeters = 0.0;
//first convert value passedValue to millimeters
ConvertDimension(DimensionType.Millimeter, passedValue, typeConvertingFrom);
//Now convert the value from inches to the desired output
return ConvertMillimetersToArchitecturalString(internalDecimalMillimeters);
}
#endregion
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>I have made some of the suggested changes from below. And I have written my UnitTests and come up with a few more questions. </p>
<p>Some people have suggested that helper classes like my <code>DimensionConverter</code> class are <a href="http://blogs.msdn.com/b/nickmalik/archive/2005/09/06/461404.aspx" rel="nofollow">evil</a>. should I combine the utility class with the dimension class and if so how?</p>
<p>Also what improvements should I make to my tests if I am assuming everything in DimensionConverter will be private to only the Dimension class?</p>
<p>UnitTests for the Dimension Class:</p>
<pre><code>[TestClass]
public class DimensionTests
{
/// <summary>
/// Tests the architectural string constructor and the regular dimension constructor
/// </summary>
[TestMethod]
public void Dimensions_Constructors()
{
// arrange & act
//numeric value constructor
Dimension inchDimension = new Dimension(DimensionType.Inch, 14.1875);
//architectural string constructor
Dimension architecturalDimension = new Dimension("1' 2 3/16\"");
//copy constructor
Dimension copiedDimension = new Dimension(architecturalDimension);
// assert
inchDimension.Millimeters.Should().Be(architecturalDimension.Millimeters);
copiedDimension.ShouldBeEquivalentTo(architecturalDimension);
}
/// <summary>
/// Tests mathmatical operators we will test the properties at the same time.
/// </summary>
[TestMethod]
public void Dimensions_Math_Operators()
{
// arrange
Dimension inchDimension = new Dimension(DimensionType.Inch, 14.1875);
Dimension architecturalDimension = new Dimension("1'2 3/16\"");
// act
Dimension subtractionDimension = inchDimension - architecturalDimension;
Dimension additionDimension = inchDimension + architecturalDimension;
// assert
subtractionDimension.Feet.Should().BeApproximately(0, .00000001, "Doubles math should get us at least this close");
additionDimension.Millimeters.Should().BeApproximately(720.725, .00000001, "Doubles math should get us at least this close");
additionDimension.Architectural.ShouldBeEquivalentTo("2'4 6/16\"");
}
/// <summary>
/// Tests Architectural string inputs.
/// </summary>
[TestMethod]
public void Dimensions_Architectural_Constructor()
{
// arrange
Dimension dimension1 = new Dimension("1'2 3/16\"");
Dimension dimension2 = new Dimension("1'");
Dimension dimension3 = new Dimension("1'2\"");
Dimension dimension4 = new Dimension("2 3/16\"");
Dimension dimension5 = new Dimension("1'2-3/16\"");
Dimension dimension6 = new Dimension("3/16\"");
Dimension dimension7 = new Dimension("121103");
Dimension dimension8 = new Dimension("-1'2\"");
// assert
dimension1.Architectural.ShouldBeEquivalentTo("1'2 3/16\"");
dimension2.Architectural.ShouldBeEquivalentTo("1'");
dimension3.Architectural.ShouldBeEquivalentTo("1'2\"");
dimension4.Architectural.ShouldBeEquivalentTo("2 3/16\"");
dimension5.Architectural.ShouldBeEquivalentTo("1'2 3/16\"");
dimension6.Architectural.ShouldBeEquivalentTo("3/16\"");
dimension7.Architectural.ShouldBeEquivalentTo("12'11 3/16\"");
dimension8.Architectural.ShouldBeEquivalentTo("-1'2\"");
}
/// <summary>
/// Tests all equality operators
/// </summary>
[TestMethod]
public void Dimensions_Equality_Operators()
{
// arrange
Dimension biggerDimension = new Dimension(DimensionType.Inch, 14.1875);
Dimension smallerDimension = new Dimension("1' 2 1/16\"");
Dimension equivalentbiggerDimension = new Dimension(DimensionType.Millimeter, 360.3625);
// assert
(smallerDimension < biggerDimension).Should().Be(true);
(biggerDimension < smallerDimension).Should().Be(false);
(biggerDimension > smallerDimension).Should().Be(true);
(smallerDimension > biggerDimension).Should().Be(false);
(equivalentbiggerDimension == biggerDimension).Should().Be(true);
(equivalentbiggerDimension == smallerDimension).Should().Be(false);
(equivalentbiggerDimension != smallerDimension).Should().Be(true);
(equivalentbiggerDimension != biggerDimension).Should().Be(false);
}
/// <summary>
/// Tests GetHashCodeOperation
/// </summary>
[TestMethod]
public void Dimensions_GetHashCode()
{
// arrange
Dimension dimension = new Dimension(DimensionType.Millimeter, 14.1875);
double number = 14.1875;
// act
int dimensionHashCode = dimension.GetHashCode();
int hashCode = number.GetHashCode();
// assert
hashCode.ShouldBeEquivalentTo(dimensionHashCode);
}
/// <summary>
/// Tests toString failure
/// </summary>
[TestMethod]
[ExpectedException(typeof(NotImplementedException))]
public void Dimensions_ToString()
{
// arrange
Dimension dimension = new Dimension(DimensionType.Millimeter, 14.1875);
// act
dimension.ToString();
}
/// <summary>
/// Tests CompareTo implementation
/// </summary>
[TestMethod]
public void Dimensions_CompareTo()
{
// arrange
Dimension smallDimension = new Dimension(DimensionType.Millimeter, 1);
Dimension mediumDimension = new Dimension(DimensionType.Foot, 1);
Dimension largeDimension = new Dimension(DimensionType.Kilometer, 1);
List<Dimension> dimensions = new List<Dimension>();
dimensions.Add(smallDimension);
dimensions.Add(largeDimension);
dimensions.Add(mediumDimension);
// act
dimensions.Sort();
// assert
dimensions[0].ShouldBeEquivalentTo(smallDimension);
dimensions[1].ShouldBeEquivalentTo(mediumDimension);
dimensions[2].ShouldBeEquivalentTo(largeDimension);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:09:04.270",
"Id": "81064",
"Score": "0",
"body": "I think that unit conversions are not what your interns are going to write every day, so I'm not sure it's a good example. For example, how many classes overload arithmetic operators?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:13:45.153",
"Id": "81065",
"Score": "0",
"body": "Strangely yes they will be writing a good many conversion tools where they will be converting output from one program to the desired input of others"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:59:25.913",
"Id": "81072",
"Score": "0",
"body": "If you want to post two classes, just post them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:09:52.213",
"Id": "81077",
"Score": "0",
"body": "Ok I will edit it in. Should I change my code as I fix the errors or leave it as is for future viewers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:24:30.650",
"Id": "81079",
"Score": "0",
"body": "No, you shouldn't, because that would invalidate existing answers. For more details, see [this meta discussion](http://meta.codereview.stackexchange.com/q/1033/2041)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:51:45.033",
"Id": "81157",
"Score": "0",
"body": "When defining the purpose of a class, the most important thing is the use cases. In code, identify that as how the class gets called. How would you like to USE this thing. That's better than to start writing code. I will put proposals down in my answer."
}
] | [
{
"body": "<p>One obvious starting point: replace your code like this:</p>\n\n<pre><code> public static bool operator ==(Dimension d1, Dimension d2)\n {\n //compare the two dimensions for equality\n //return a bool based on their relative values\n if (d1.internalDecimalUnit == d2.internalDecimalUnit) \n {\n return true;\n }\n else\n {\n return false;\n }\n</code></pre>\n\n<p>...with the much simpler, more readable:</p>\n\n<pre><code> return (d1.internalDecimalUnit == d2.internalDecimalUnit);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:17:46.163",
"Id": "81066",
"Score": "0",
"body": "should I be overriding the .equals function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:39:28.033",
"Id": "81136",
"Score": "0",
"body": "ON the readability of return (d1.internalDecimalUnit == d2.internalDecimalUnit), its not bad, but its not handy for setting break points in a debugger. What you then get is people rewriting code back to if statements while they are debugging, which can result in errors."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:50:36.177",
"Id": "46392",
"ParentId": "46390",
"Score": "7"
}
},
{
"body": "<p>I'm tempted to call your <code>==</code> operator a perfect example of how not to do it: The concept of equality of floating-point numbers in the first place is somewhat of a poor concept in that e.g. IEEE definitions don't create behavior matching naive expectations---who would have known that <code>x*(1.0/x)</code> and <code>1.0</code> are often not equal (for very many values of <code>x</code>)?</p>\n\n<p>Hence having such an operator without a documentation layer above the code that clearly defines what it is supposed to do or not to do is almost guaranteed to eventually create buggy code due to unfulfilled expectations, considering that even just converting units and immediately converting the result back will in many cases not result in a value equal to the starting value. The main problem here is that in the context of engineering measurements, equality could even more likely be seen as \"essentially equal within engineering tolerances\" than it already could be in the general use of floating numbers. I wouldn't even be surprised if in some context some intern naively expects it to mean \"close enough to substitute a non-precision 4.8mm metric part with a 3/16in (nominally 4.76mm) imperial part.\" And maybe adjusts the code to improve it with regard to that interpretation, messing with some ball bearing engineer's assertion to check that his 2.49mm axle is really different from the 2.51mm bore hole for it. There you have your maintainability problem, complete with interns.</p>\n\n<p>So what can one do to avoid this situation? I think the best one can hope for is to make users of the library aware of the problem, ideally in whatever becomes the preferred documentation, and (as last resort against people changing the code rather than their expectations) as comments in the code itself. As one (out of many) possibly approaches, I suggest the following \"code\" changes of the comments inside your <code>==</code> operator:</p>\n\n<pre><code>//compare the two dimensions for **floating-point** equality\n//return a bool based on their relative values\n//\n//this is not helpful to determine if dimensions match within rounding accuracy\n//(or within any other tolerance), and hence is rarely useful;\n//\n//see Microsoft (http://msdn.microsoft.com/en-us/library/dd183752.aspx):\n//\"Equality comparisons of floating point values (double and float) are problematic\n//because of the imprecision of floating point arithmetic on binary computers.\"\n//\n//a partial solution, decimal floating-point arithmetic,\n//is **NOT** used in this library.\n//\n//for most applications, consider explicitly using these alternatives:\n// equality within an absolute tolerance tol: (abs(d1-d2) < tol)\n// equality within a relative tolerance tol: (abs(d1-d2) < 0.5*tol*(abs(d1)+abs(d2))\n// exact binary equality: (d1.GetHashCode() == d2.GetHashCode())\n</code></pre>\n\n<p>Of course a better solution would be to stop any problematic use before it gets to the point that someone digs into the source code to get to the bottom of it. I'm not sure how to do it (other than to improve the suggested comments to show up in documentation as well). You could indeed consider not having this operator in the first place, as svick suggests in his answer. That would be better than to sneakily, at run time, decide that this operator is undefined and never to return normally!</p>\n\n<p>But whether having or not having the equality operator is better may depend on who uses it. I view having it much like I view an airplane having a particularly dangerous stall behavior: Such a plane would be very safe in the hands of a well-trained and alert pilot (who knows how to deal with it and that it is more likely than not that he will never want to make use of this \"feature\"), and arguably better than the alternative of one with such benign edge behavior that the more human among its pilots just cannot be convinced to pay much attention to its manual at all and may well end up less safe than they would otherwise be. So the best recommendation about keeping or not keeping the <code>==</code> operator probably depends on whether you want to write the perfect library for a circle of users having to go through extensive training, or for just anyone, including those interns maybe not previously familiar with either floating-point arithmetic in general or C# and your library in particular.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:51:11.780",
"Id": "81069",
"Score": "0",
"body": "Great and helpful insight. What is the best of my options? delete it or replace the internal unit with the smallest thing possible and make the == true to so many significant digits? or something else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:54:02.283",
"Id": "81070",
"Score": "1",
"body": "Since `==` is a good thing to provide (despite the dangers), I can't come up with a better answer than to clearly define what you want it to do (i.e. IEEE or something more special). I suppose I would be tempted to define it as IEEE (or C#) equality, and either provide some other method along the lines of `bool equalsWithinTolerances(Dimension x, Dimension tol)` or else point out in the doc that equivalent code is the more common use case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:36:24.400",
"Id": "46396",
"ParentId": "46390",
"Score": "7"
}
},
{
"body": "<pre><code>#region internal variables\n</code></pre>\n\n<p>This is confusing, since the variables (or, more precisely, fields), are not <code>internal</code>, they are <code>private</code>.</p>\n\n<hr>\n\n<pre><code>DimensionTypes\n</code></pre>\n\n<p>That's a bad name. A value of that type represents a single “dimension type”, so the type should be called accordingly: <code>DimensionType</code>. Also, wouldn't something like <code>DimensionUnit</code> be even better?</p>\n\n<hr>\n\n<pre><code>//internal Dimension type is set to milimeter to cause the least amount of rounding error when performing calculations.\nconst DimensionTypes internalUnitType = DimensionTypes.Millimeter;\n\n//dimension value\nprivate double internalDecimalUnit = 0.0;\n</code></pre>\n\n<p>You should decide whether to always type the <code>private</code> modified or never and stick with that, not write it for some members and omit it for others.</p>\n\n<p>Also, <code>internalDecimalUnit</code> is quite confusing name, which you seem to be acknowledging by adding a comment that describes it in another way.</p>\n\n<p>I don't see any advantage in having all <code>private</code> fields prefixed with <code>internal</code> (and again, it's also confusing, since they aren't really <code>internal</code>). If you want some prefix for fields, <code>_</code> and <code>m_</code> are common choices.</p>\n\n<p>And the <code>decimalUnit</code> part is confusing too: it doesn't describe any unit, it describes a value. And I don't specifying that it's “decimal” makes much sense: either say explicitly which unit it is, or don't say it at all (see also below about changing the unit).</p>\n\n<p>And it seems like the code is prepared if you want to change the unit type. But you also mark it as <code>const</code>, indicating that it will <em>never</em> change.</p>\n\n<p>One more thing: the comment above <code>internalUnitType</code> seems to imply that you get the least amount of rounding errors with smaller units and thus larger numbers. But that's not how <code>double</code> works: unless you get close to its limits (approximately 10<sup>-300</sup> and 10<sup>300</sup>), the precision is always the same (around 15 decimal digits).</p>\n\n<p>If you are really serious about rounding errors (you probably don't need to be, 15 digits is quite a lot), you would try to avoid conversions if possible. The most precise way to add two numbers in feet and print out the result in feet again is to perform all computations in feet, not convert to millimeters, add them, and then convert them back.</p>\n\n<hr>\n\n<pre><code>/// <summary>\n/// Accepts any string value for input.\n/// </summary>\npublic Dimension(string passedArchitecturalString)\n{\n storeArchitecturalStringAsInternalUnit(passedArchitecturalString);\n}\n</code></pre>\n\n<p>You don't have to specify <code>passed</code> on all parameters.</p>\n\n<p>Also, does this constructor really accept <em>any</em> string value (e.g. <code>\"nějaká hodnota\"</code>)? Or does it accept only values in some specific format? (Is that what “architectural string” is supposed to mean?)</p>\n\n<p>And I think that the field should be actually assigned in the constructor, not in the helper method (in that case, the helper method would <em>return</em> the value to assign). But I can see the value in this approach too (less repetition).</p>\n\n<hr>\n\n<pre><code>public double Sixteenths\n{\n get { return retrieveAsExternalUnit(DimensionTypes.Sixteenth); }\n set { storeAsInternalUnit(DimensionTypes.Sixteenth, value); }\n}\n</code></pre>\n\n<p>I think this type would be better as immutable, i.e. it shouldn't have any setters. If you compare the following snippets, then I think the second one is better, even if it's longer:</p>\n\n<pre><code>desk.Length.Inches = 20;\ndesk.Length = Dimension.Inches(20);\n</code></pre>\n\n<p>Also, mutability causes big problems with dictionaries: if you use a <code>Dimension</code> as a key in a dictionary and then change its value, the dictionary won't work correctly anymore.</p>\n\n<hr>\n\n<pre><code>public static bool operator ==(Dimension d1, Dimension d2)\npublic static bool operator !=(Dimension d1, Dimension d2)\npublic static bool operator >(Dimension d1, Dimension d2)\npublic static bool operator <(Dimension d1, Dimension d2)\npublic override int GetHashCode()\n</code></pre>\n\n<p>If you overload <code>==</code>, you really should also override <code>Equals()</code> and ideally also implement <code>IEquatable<Dimension></code>. I'm actually surprised that overriding <code>GetHashCode()</code> without overriding <code>Equals()</code> compiles.</p>\n\n<p>But keep pyramids' answer in mind and consider removing <code>==</code> completely.</p>\n\n<p>Similarly, if you overload <code>></code>, consider also implementing <code>IComparable<Dimension></code>.</p>\n\n<hr>\n\n<pre><code>//compare the two dimensions together\n//return a bool based on their relative values\n</code></pre>\n\n<p>Comments like this are pretty useless, there is certainly no need to repeat it over and over.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:03:54.327",
"Id": "81075",
"Score": "0",
"body": "Fantastic comments, thanks so much. With your shortened `public static bool operator ==(Dimension d1, Dimension d2)` how does the compiler know to compare the private double internalDecimalUnit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:22:04.943",
"Id": "81078",
"Score": "0",
"body": "@jth41 I just included the method signatures in my answer, because I didn't need their bodies for that point. But you of course still have to write them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:25:47.417",
"Id": "81080",
"Score": "0",
"body": "Ok gotcha. I was very confused for a moment. VS does a lot for you, but that would be rediculous"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:31:20.060",
"Id": "46402",
"ParentId": "46390",
"Score": "4"
}
},
{
"body": "<p><strong>Verbosity</strong><br>\nVerbosity can be a good thing in code. The method name explains what the method does. Too much verbosity, though, can make your code tiring to read, as well as less memorable. For example - <code>passedArchitecturalString</code> - why call it <code>passed</code>? we know it is passed, it is an argument. Same for <code>String</code> - we know it is a string. Simply calling <code>architectural</code> would have conveyed the same information, and be a lot more memorable. <code>internalDecimalUnit</code> - again, we know it is internal, and it is actually <em>not</em> Decimal (it is <code>double</code>), I believe <code>value</code> would have been enough here, perhaps <code>intrinsicValue</code> if you want to be explicit.</p>\n\n<p><strong>Commentary</strong><br>\nComments have had their day when they were considered crucial to code readability. Nowadays, though, they have lost their shine a bit, and sometimes considered as a <a href=\"http://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">code smell</a>. The main problem with comments, is that they tend to be forgotten as the code progresses, and often start making no sense, as they are not synchronized with the code. Another problem with them is that most programmers <em>skip</em> comments, and never actually read them.<br>\nSome of your comments are good (like for <code>internalUnitType</code>), but some are absolutely redundant (like for the copy constructor, or for the architectural constructor), and some just make the code harder to read rather than easier to read like the comments inside your operator overloadings.</p>\n\n<p><strong>Code consistency</strong><br>\nIt is a matter of style whether you want to address your internal members with the <code>this.</code> prefix, but once you make the choice, be consistent.</p>\n\n<p><strong>When helpers don't help</strong><br>\nYour helper methods are one-liner delegations. This seems a bit redundant, since they don't reduce code complexity, nor enhance readability. They may even introduce bugs (let's see if you can find the bug in <code>storeAsInternalUnit</code>)</p>\n\n<blockquote class=\"spoiler\">\n <p> It always converts to Kilometers</p>\n</blockquote>\n\n<p>Also, some helpers have only a single use, which makes them even more a waste of space. I would think that, for example, the following constructor code is more readable than yours, and saves you a method:</p>\n\n<pre><code>public Dimension(string architectural)\n{\n Architectural = architectural;\n}\n</code></pre>\n\n<p><strong>The Immutables</strong><br>\nYou decided not to override <code>Equals</code>, which is fine, but you <em>did</em> override <code>GetHashCode</code>. <code>GetHashCode</code> is rarely used in user code, but mainly in containers which use hashing to store/retrieve elements. Overriding this method might break your code in these cases, since your <code>Dimension</code> is not immutable, and changing one's value while it is in a container, will make it 'disappear' from any such container he might be in.<br>\nEither make your class immutable, or delete this method. And if you decide to keep it, consider overriding <code>Equals</code> as well, they look so much better together...</p>\n\n<p><strong>String it!</strong><br>\nYou opted to not implement <code>ToString</code> in your code. This is problematic, since in many places in your user code, he may want to use traces or debug logs, and your decision to throw an error there will unnecessarily break their code. You might expect them to call <code>dimension.[unit].ToString()</code>, but what if they log a <code>List</code> of <code>Dimension</code>? </p>\n\n<hr>\n\n<p>I notice that you chose not to put the <code>DimensionConverter</code> code in this post, which is a shame, because I can guess all the juicy parts are there, and you let us glimpse only on code with no complexity since it only delegates to that mysterious class :-(...</p>\n\n<hr>\n\n<p><strong>Update</strong><br>\nBefore I'll tackle the <code>DimensionConverter</code>, there are a couple of things I forgot to mention, which are very important, especially as you aim to have a \"perfect\" code:</p>\n\n<p><strong>Naming Conventions</strong><br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms229043%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">C# naming conventions</a> state that <code>const</code> members as well as all methods should be <code>PascalCase</code>. This is especially important in the case of you elusive <code>const DimensionTypes internalUnitType</code>. Consider the following two lines:</p>\n\n<pre><code>internalDecimalUnit = DimensionConverter.ConvertDimension(passedDimensionType, \n passedInput, internalUnitType);\n\ninternalDecimalUnit = DimensionConverter.ConvertDimension(passedDimensionType, \n passedInput, InternalUnitType);\n</code></pre>\n\n<p>Even SO's syntax highlighter sees the difference, which makes the <em>intention</em> of your constant a whole lot more apparent.</p>\n\n<p><strong>Use Decimal</strong>\nWhen used for human units (base 10), it is always advisable to use <a href=\"https://stackoverflow.com/questions/803225/when-should-i-use-double-instead-of-decimal\"><code>decimal</code> instead of <code>double</code></a>. Doubles are notorious in their quirks when they are involved in arithmetic.</p>\n\n<p><strong>Unit tests</strong><br>\nNo self-respecting perfect code lacks a good fool-proof suite of unit tests! They make your code more stable, more readable and more maintainable. Educate your interns today on the importance of unit tests!</p>\n\n<hr>\n\n<p><strong>String it to me</strong><br>\nYou <a href=\"https://codereview.stackexchange.com/questions/46390/class-for-handling-unit-conversions/46408?noredirect=1#comment81084_46408\">asked me</a> what should <code>ToString()</code> return by default?<br>\nI think that on the most basic level, choose the format you feel is most appropriate in millimeters, or as architectural - the one most convenient to your users (remember to indicate which unit you are using in the resulting string!).<br>\nIf you feel like being a little more elaborate, you can provide a global flag, which the user can set, which tells the <code>ToString()</code> method which is the default unit to render.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:07:36.437",
"Id": "81076",
"Score": "0",
"body": "Thanks so much for your help! I really like your bug on mouseover, that is really cool. I was going to post the dimension converter code but I didnt want to overwhelm with code. is it acceptable to post multiple classes? if so, can I edit it in now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:29:49.773",
"Id": "81081",
"Score": "1",
"body": "I would be stronger about requiring `Equals()`: if you override `GetHashCode()`, you *have to* override `Equals()` as well. Otherwise, hash containers won't work for this type (because they use both methods)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:35:50.203",
"Id": "81082",
"Score": "0",
"body": "I edited in the DimensionConverter class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:48:10.020",
"Id": "81084",
"Score": "0",
"body": "What should my toString return? I dont want to feed him values that he isnt expecting..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T06:48:38.870",
"Id": "81122",
"Score": "0",
"body": "@svick - yeah, when I started writing this section that's what I thought, but actually, there is no real harm in implementing `GetHashCode()` on its own (as long as it's returning the same thing each time...) - its default implementation is the instance's `ObjectID` which is as arbitrary as they come. Of course, although it is not harmful, it is definitely not helpful without `Equals`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T07:08:26.280",
"Id": "81124",
"Score": "0",
"body": "@jth41 see my updated answer regarding ToString"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:49:22.883",
"Id": "81547",
"Score": "0",
"body": "Thanks so much for all of your help. My last question is about the unit tests. I understand how to write them and use them, but I am uncertain how to make sure I have covered every important case. seems like an exponential amount of possibilities here. how should I write these?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:26:23.890",
"Id": "81553",
"Score": "0",
"body": "Unit testing is a big subject, and I believe that it is out of scope for this site. You could look at programmers.stackexchange.com (http://programmers.stackexchange.com/questions/63970/unit-testing-best-practices-for-a-unit-testing-newbie, http://programmers.stackexchange.com/questions/27301/writing-unit-tests-in-the-middle), and if you find that doesn't answer your question - ask it there! (you can then point me there, and I'll give you an answer there)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:00:15.450",
"Id": "46408",
"ParentId": "46390",
"Score": "5"
}
},
{
"body": "<p>I'm not going to discuss your code, but the original problem. If you want a general purpose, highly flexible dimensional analysis class, you need (for physical problems) three dimensions:</p>\n\n<p>Length, Mass, Time (the Newtonian constants).</p>\n\n<p>Using these you can define any physical constant.</p>\n\n<p>A unit adds a coefficient to these three.</p>\n\n<p>Let's take MKS as the default system.</p>\n\n<pre><code>public class Unit {\n private double c; // coeficient\n private int LENGTH, MASS, TIME;\n\n public Unit(String name) { ... }\n\n}\n</code></pre>\n\n<p>Ok, so the unit \"meter\" corresponds to c=1, LENGTH = 1, MASS = 0, TIME = 0</p>\n\n<p>the unit \"foot\" corresponds to c=1/3.048, LENGTH = 1, ...</p>\n\n<p>The unit \"kg\" corresponds to C = 1, LENGTH = 0, MASS = 1, TIME = 0</p>\n\n<p>With this class you can represent any physical quantity\nArea of an apartment in square meters?: C = 1, LENGTH = 2, MASS = 0, TIME = 0</p>\n\n<p>For business applications, I find that a fourth dimension is useful, money.\nUnlike the others, money is not invariant. So if you specify in dollars, you need to specify what time the dollars are from. Still, ignoring inflation, you can use this to specify problems like:</p>\n\n<p>house materials cost = 1 ton steel * $170/ton + 352 kg fiberglass * $2/kg + 270m^2 of tile * $32/m^2 + ...\nThen quote the cost to the buyer in Euros based on the conversion ratio at the time.</p>\n\n<p>To do this, just add a fourth dimension, money.</p>\n\n<p>[1.0 3 1 1 -1] means: 1.0 m^3 kg s / $</p>\n\n<p>Let's start by defining what you want to achieve, something you never really stated.\nI personally would like something like the following. I'm not really current in C# so I'm going to write it in C++ notation, which I'm pretty sure you can do in C#.</p>\n\n<pre><code>TypedQty houseArea(Dimension.MSQUARED, 500); // The area of the house in square meters\nTypedQty houseHeight(Dimension.METERS, 10);\nTypedQty houseVolume(Dimension.MCUBED, 2500);\nTypedQty SteelMass(Dimension.KG, 1000);\nTypedQty housePrice(Dimension.DOLLAR, 300e3);\nTypedQty pricePerArea = houseArea/housePrice;\nDimension yenPerSquareInch = Dimension.YEN / Dimension.DOLLAR * Dimension.INCH * Dimension.INCH / Dimension.MSQUARED;\npricePerArea.convert(yenPerSqInch).print();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T06:08:46.953",
"Id": "46433",
"ParentId": "46390",
"Score": "3"
}
},
{
"body": "<p>Since my previous answer is already long, I've decided to write a separate answer for the second class, to give it the proper respect...</p>\n\n<p>I will not repeat the virtue in succinct names (I believe that <code>ToMillimeters(string architectural)</code> conveys as much information as <code>ConvertArchitectualStringtoMillimeters(String arch)</code>).</p>\n\n<p><strong>Make your regular expression readable</strong><br>\nThe single most important part of the first method is the regular expression. It is also the most hard to read...<br>\nRegular expression <em>are</em> hard to read, but there are ways to make them more readable. You can use <a href=\"http://answers.oreilly.com/topic/213-how-to-add-comments-to-a-regular-expression/\" rel=\"nofollow noreferrer\">comments</a> to your expression, writing it in a <a href=\"https://stackoverflow.com/questions/1100260/multiline-string-literal-in-c-sharp\">multiline</a> fashion, to make it a lot more readable:</p>\n\n<pre><code>String expr = @\"^\\s*\n (?<minus>-)? # optional minus sign\n \\s*(((?<feet>\\d+)(?<inch>\\d{2})(?<sixt>\\d{2}))| # long number format (121103 == 12 Feet and 11 Inches and 3 sixteenths)\n (\n (?<feet>[\\d.]+)')?[\\s-]* # 12'\n ((?<inch>\\d+)?[\\s-]* # 11''\n ((?<numer>\\d+)/(?<denom>\\d+))?\\\")? # ...or 11 3/16''\n ) # 12' 11 3/16''\n \\s*$\";\n\n Match m = new Regex(expr, RegexOptions.IgnorePatternWhitespace).Match(arch);\n</code></pre>\n\n<p><strong>Meaningful names</strong><br>\nI was surprised to see a variable name called <code>num</code> in your, otherwise verbose, code. You add insult to injury, when the first thing you do in that method is <em>change its value and meaning</em>!<br>\nI had to read the code a few times to understand how you can convert from millimeters to feet by dividing by 12...<br>\nCall the parameter <code>millimeters</code>, and create a new variable - <code>inches</code> inside the method.</p>\n\n<p><strong>Declare variables only when they are needed</strong><br>\nDon't declare a bucket load of variables at the beginning of a long method. This will cause the reader to continuously scroll up and down to see what the variable might mean.<br>\nAlso, don't give an unused default value when declaring variables. You can hide bugs when trying to use the variables before they are set. And again, bug of the day, can you spot the bug caused by this in <code>ConvertDecimalDimensionToArchitecturalString</code>? Don't peek!</p>\n\n<blockquote class=\"spoiler\">\n <p> All converted values will be from <code>0.0</code></p>\n</blockquote>\n\n<p>Declare variables as late as possible in the method, and don't give meaningless default values:</p>\n\n<pre><code>int feet = (int)inches / 12;\n// ...\nstring feetString = (feet == 0) ? \"\" : Convert.ToString(feet);\n</code></pre>\n\n<p>(see what I did there with <code>FeetString</code>? read about naming conventions in my other answer...)</p>\n\n<p>Where possible, skip the variable altogether, and inline it:</p>\n\n<pre><code>public static string ConvertDecimalDimensionToArchitecturalString(DimensionType typeConvertingFrom, double passedValue)\n{\n return ConvertMillimetersToArchitecturalString(\n ConvertDimension(DimensionType.Millimeter, passedValue, typeConvertingFrom));\n}\n</code></pre>\n\n<p><strong>When comments are forgotten</strong><br>\nIn <code>ConvertDimension</code> you have the following comments:</p>\n\n<pre><code>//first convert value passedValue to inches\n\n//Now convert the value from inches to the desired output\n</code></pre>\n\n<p>But your code converts to and from millimeters...</p>\n\n<p><strong>Method too long</strong><br>\nIt seems that <code>ConvertDimension</code> method is <a href=\"http://sourcemaking.com/refactoring/long-method\" rel=\"nofollow noreferrer\">too long</a>. Its usage in <code>Dimension</code> class is always from a known unit to millimeters, or vice versa. I believe that breaking it down to methods doing just that is preferable, and more readable:</p>\n\n<pre><code>public static double FromThirtySecond(double thirtySecond)\n{\n return (thirtySecond / 32) * 0.0393701;\n}\n\npublic static double FromSixteenth(double sixteenth) \n{\n return FromThirtySecond(sixteenth * 2);\n}\n\n// ... snip ...\n\npublic static double ToMile(double millimeters)\n{\n return millimeters / 1609344;\n}\n\npublic static double ToKilometer(double millimeters)\n{\n return millimeters / 1000000;\n}\n</code></pre>\n\n<p>Now the properties in <code>Dimension</code> class can also look a lot more readable:</p>\n\n<pre><code>public double Sixteenth\n{\n get { return DimensionConverter.ToSixteenth(intrinsicValue); }\n set { intrinsicValue = DimensionConverter.FromSixteenth(value); }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:47:44.483",
"Id": "81156",
"Score": "0",
"body": "Why would you want to write hardcoded methods for every potential unit? There are a huge number even if you \"only\" consider the common ones: mile, km, meter, yard, foot, inch, cm, mm\n\nmile"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:33:03.070",
"Id": "81166",
"Score": "0",
"body": "@Dov, since the original method had nothing generic or dynamic about it, it is basically a huge `switch` case, replacing the long unreadable method with a lot of small, readable, and more testable methods has no real downside... You don't 'save' any code writing by lumping it all up in a big method. See also real-life example in C# http://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:07:02.213",
"Id": "81211",
"Score": "0",
"body": "see my answer. I am arguing for a rather different total solution"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:14:42.787",
"Id": "81212",
"Score": "0",
"body": "@Dov, as you testify yourself about your answer - it does not discuss the OP's code. Since this is codereview.stackexchange.com, I prefer to stay with the OP's objectives and strategy, and help him write better code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T08:13:06.547",
"Id": "46437",
"ParentId": "46390",
"Score": "1"
}
},
{
"body": "<p>I'm going to write a separate answer with code the way I think it should be, but since I'm not a C# programmer there will be small differences in syntax. The overall design should be the same.</p>\n\n<p>First, conventions: a Dimension in physics is the kind of unit. A unit has a particular scale in that dimension. For example, a Dimension of length is a generic thing, but there are meters, feet, etc. I realize your field is architecture, but even so you deal with at least L, L^2, L^3 if not more, so I will stick to this convention.</p>\n\n<pre><code>import java.util.*;\n\npublic class Unit {\n private String name;\n private String abbrev;\n private int LENGTH, MASS, TIME, MONEY;\n private double c;\n private static HashMap<String, Unit> unitsByName;\n private static HashMap<Integer, Unit> unitsByDimension;\n\n // these static units are declared at compile time for error checking\n // if all units are put here, that makes the code fairly big\n\n //MKS (Systeme Internationale the engineering superset of the metric system)\n public static Unit METER, KG, SEC;\n // derivative common units\n public static Unit NM, uM, MM, CM, KM, GRAM, TONNE, MINUTE, HOUR, DAY, YEAR;\n\n //English\n public static Unit INCH, FOOT, YARD, MILE, POUNDMASS;\n\n //Money\n public static Unit USD, JPY, EUR;\n\n static {\n unitsByName = new HashMap<String, Unit>(128);\n unitsByDimension = new HashMap<Integer, Unit>(128);\n METER = new Unit(\"meter\", \"m\", 1,0,0,0);\n KG = new Unit(\"kilogram\", \"kg\", 0,1,0,0);\n SEC = new Unit(\"second\", \"s\", 0,0,1,0);\n USD = new Unit(\"dollar\", \"$\", 0,0,0,1);\n\n NM = new Unit(\"nanometer\", \"nm\", 1e-9,1,0,0,0);\n uM = new Unit(\"micrometer\", \"um\", 1e-6,1,0,0,0);\n MM = new Unit(\"millimeter\", \"mm\", 1e-3,1,0,0,0);\n CM = new Unit(\"centimeter\", \"cm\", 0.01,1,0,0,0);\n KM = new Unit(\"kilometer\", \"km\", 1000.0,1,0,0,0);\n\n GRAM = new Unit(\"gram\", \"g\", 0.001,0,1,0,0); // scaled in terms of MKS kilogram\n TONNE = new Unit(\"tonne\", \"T\", 1000,0,1,0,0); // scaled in terms of MKS kilogram\n\n INCH = new Unit(\"inch\", \"in\", 0.0254,1,0,0,0);\n FOOT = new Unit(\"foot\", \"ft\", 12*0.0254,1,0,0,0); // don't combine constants, keep it understandable\n YARD = new Unit(\"yard\", \"yd\", 36*0.0254,1,0,0,0);\n }\n public int hashCode() {\n return ((LENGTH * 4 + MASS) * 4 + TIME) * 4 + MONEY;\n }\n public Unit(String name, String abbrev, double c, int len, int mass, int time, int money) {\n this.name = name;\n this.abbrev = abbrev;\n this.c = c;\n LENGTH=len; MASS = mass; TIME = time; MONEY = money;\n unitsByName.put(name, this);\n unitsByDimension.put(hashCode(), this);\n }\n public Unit(String name, String abbrev, int len, int mass, int time, int money) {\n this(name, abbrev, 1.0, len, mass, time, money);\n }\n public Unit(double c, int len, int mass, int time, int money) {\n this(\"\", \"\", c, len, mass, time, money);\n }\n\n public boolean equals(Object other) {\n Unit o = (Unit)other;\n // Hmmm.. thinking of what equality of dimension really means...\n return LENGTH == o.LENGTH && MASS == o.MASS && TIME == o.TIME && MONEY == o.MONEY &&\n Math.abs(c - o.c) / c < .001;\n // for units at least, an accuracy of 0.1% is pretty much a guarantee. Haven't thought about this much though\n }\n\n public Unit mult(Unit u) {\n u = new Unit(c*u.c, LENGTH+u.LENGTH, MASS+u.MASS, TIME+u.TIME, MONEY+u.MONEY);\n Unit stdUnit = unitsByDimension.get(u);\n return (stdUnit != null) ? stdUnit : u;\n }\n}\n</code></pre>\n\n<p>The above code is not quite done, but it shows the idea and the elegance of this approach.\nA DimensionalQty is a pair (number, Unit). I have not shown that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:43:44.237",
"Id": "46972",
"ParentId": "46390",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "46408",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:40:18.700",
"Id": "46390",
"Score": "12",
"Tags": [
"c#",
"strings",
"converting"
],
"Title": "Class for handling unit conversions"
} | 46390 |
<p>I feel like there is room for improvement in the push/pop methods. Any suggestions?</p>
<pre><code>#include <exception>
template <typename T>
class List
{
public:
List();
~List();
void PushBack(const T &data);
void PushFront(const T &data);
void PopBack();
void PopFront();
void Clear();
bool IsEmpty() const;
unsigned int Size() const;
T& Front() const;
T& Back() const;
private:
template <typename T>
struct Node
{
Node(const T &data) : data(data), next(NULL) {}
T data;
Node *next;
};
Node<T> *head;
Node<T> *tail;
};
template <typename T>
List<T>::List()
: head(NULL),
tail(NULL)
{
}
template <typename T>
List<T>::~List()
{
Clear();
}
template <typename T>
void List<T>::PushBack(const T &data)
{
if ( !head )
{
head = new Node<T>(data);
tail = head;
return;
}
tail->next = new Node<T>(data);
tail = tail->next;
}
template <typename T>
void List<T>::PushFront(const T &data)
{
Node<T> *tmp = head;
head = new Node<T>(data);
head->next = tmp;
if ( !tail )
{
tail = head;
}
}
template <typename T>
void List<T>::PopBack()
{
//empty list
if ( !head )
{
throw std::out_of_range("Can't pop from empty list");
}
//list with one element
if ( head == tail )
{
delete head;
head = NULL;
tail = NULL;
return;
}
Node<T> *current = head;
while ( current->next != tail )
{
current = current->next;
}
delete tail;
tail = current;
tail->next = NULL;
}
template <typename T>
void List<T>::PopFront()
{
//empty list
if ( !head )
{
throw std::out_of_range("Can't pop from empty list");
}
//list with one element
if ( head == tail )
{
delete head;
head = NULL;
tail = NULL;
return;
}
Node<T> *tmp = head->next;
delete head;
head = tmp;
}
template <typename T>
void List<T>::Clear()
{
Node<T> *current = head;
while ( head )
{
current = head;
head = head->next;
delete current;
}
head = NULL;
tail = NULL;
}
template <typename T>
bool List<T>::IsEmpty() const
{
return ( head == NULL );
}
template <typename T>
unsigned int List<T>::Size() const
{
unsigned int size = 0;
for ( Node<T> *current = head; current; current = current->next )
{
++size;
}
return size;
}
template <typename T>
T& List<T>::Front() const
{
if ( !head )
{
throw std::out_of_range("Can't return value from empty list");
}
return head->data;
}
template <typename T>
T& List<T>::Back() const
{
if ( !head )
{
throw std::out_of_range("Can't return value from empty list");
}
return tail->data;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:47:16.247",
"Id": "81063",
"Score": "3",
"body": "Hm, I realised there is no way of iterating through it. I should implement an iterator"
}
] | [
{
"body": "<ul>\n<li><p>Consider using a different naming convention for your data members and methods, such as camelCase or snake_case. Your user-defined types are already uppercase, which is okay. Whichever you choose, it's more readable to keep them separate.</p></li>\n<li><p>The push/pop methods here imply that this is a stack implementation, but a linked list should be capable of inserting or removing a node at <em>any</em> location in the list. Consider adding additional functions for this. For an idea of typical linked list functions, <a href=\"http://en.cppreference.com/w/cpp/container/list\">read this</a>.</p></li>\n<li><p>Since you're using a list <code>class</code>, you should have a size member to maintain. Your <code>Size()</code> method is calculating the size at each call by traversing, which is O(n).</p>\n\n<p>Instead, have a size data member and update it with other operations:</p>\n\n<ul>\n<li>initialize to 0 in the initializer list</li>\n<li>increment with each push</li>\n<li>decrement with each pop</li>\n<li>reset to 0 with each clear</li>\n</ul>\n\n<p>When you call <code>Size()</code>, it should just return the data member value, which is O(1).</p>\n\n<p>It should also return a <code>std::size_t</code>. It is closest to the return type used in STL containers, and a very large list size may not fit inside an <code>unsigned int</code>.</p></li>\n<li><p>Instead of having a <code>return</code> in <code>PushFront()</code>, put the last two lines into an <code>else</code> block.</p></li>\n<li><p>Shouldn't <code>popBack()</code> check <code>tail</code> if <code>PopFront()</code> checks <code>head</code>? Although they may be pointing to the same node if there's only one node, but the intent is more clear this way.</p></li>\n<li><p>You should probably also have a <code>Front()</code> and <code>Back()</code> that return a <code>T const&</code>, in case the reference will not be modified or a <code>const</code> value is needed.</p></li>\n<li><p>You should have some way of displaying the list. For that, consider overloading <code>operator<<</code> for the <code>List</code> class (instead of a display function), allowing you to do this:</p>\n\n<pre><code>List list;\nstd::cout << list;\n</code></pre>\n\n<p>You could also overload <code>Node</code>'s operator, allowing you to output a node within the <code>List</code> class.</p></li>\n<li><p><code>std::out_of_range</code> is defined in <code><stdexcept></code>, not <code><exception></code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:59:57.853",
"Id": "81073",
"Score": "0",
"body": "Thank You! I might edit with the implemented iterator later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:01:49.257",
"Id": "81074",
"Score": "3",
"body": "@Innkeeper: You're welcome! As that change may affect more of your code, I'd recommend asking a new question with that implementation. Follow-up questions are okay here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:35:01.013",
"Id": "81102",
"Score": "0",
"body": "What's the problem with the capitalization convention? I don't see any issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:38:10.857",
"Id": "81105",
"Score": "2",
"body": "@200_success: More of a personal preference, I suppose. It just seems odd sharing it with types, variables, and functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T09:56:45.323",
"Id": "81129",
"Score": "0",
"body": "If I overloaded `operator<<`, I still wouldn't have any way to iterate through and say, modify each item. Wouldn't an iterator/const iterator be more useful? Well, these could coexist, but I'm on the right track thinking this really needs an iterator, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:02:55.280",
"Id": "81193",
"Score": "0",
"body": "@Innkeeper: Yes, iterators would still be useful. They could still be used for modifying nodes as well as displaying the list in a loop. They can still coexist with `operator<<`. The operator would display the entire list, whereas the iterators can display a portion of it (think of how `std::begin()` and `std::end()` are used in loops)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:30:07.290",
"Id": "46401",
"ParentId": "46391",
"Score": "8"
}
},
{
"body": "<p>IMO, if you're going to implement a linked list (probably shouldn't--they're pretty worthless) it's best to specify both the data <em>and</em> the <code>next</code> pointer when you create a node.</p>\n\n<pre><code>Node(const T &data, struct node *next = nullptr) : data(data), next(next) {}\n</code></pre>\n\n<p>This lets you simplify quite a bit of the insertion code. For example:</p>\n\n<pre><code>template <typename T>\nvoid List<T>::PushFront(const T &data) {\n\n head = new node(data, head);\n\n if ( !tail )\n tail = head;\n}\n</code></pre>\n\n<p>The other big thing that jumped out at me (that Jamal hasn't already discussed) was using <code>NULL</code>. I'd prefer <code>nullptr</code>, unless you're stuck with an ancient compiler that doesn't support it yet (in which case, you still want to do it, but after updating your compiler).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:34:42.503",
"Id": "81100",
"Score": "0",
"body": "I haven't forgotten about `nullptr`, but I sometimes feel tempted to not bring it up if it appears that the OP isn't already using C++11."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T09:58:37.220",
"Id": "81130",
"Score": "0",
"body": "Yeah, much clearer with that ctor, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T15:26:39.933",
"Id": "110110",
"Score": "0",
"body": "Linked lists are not worthless, you need to know when to use the correct data structure. Linked lists have constant time insertion and deletion at the front and tail or anywhere where you already have a pointer. If you are frequently inserting or deleting at the front or tail (like a queue) then a linked list is just fine. A plain vector or array would perform terribly in this case making a `pop` operation an \\$\\mathcal{O}(n)\\$ operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T15:39:59.920",
"Id": "110115",
"Score": "0",
"body": "@EmilyL.: You sound like you were in the data structures classes I taught 20+ years ago. At that time, the advice was even sort of close to accurate. Unfortunately, it wasn't nearly as good then as I thought, and it's much less so now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T15:48:35.973",
"Id": "110117",
"Score": "0",
"body": "@JerryCoffin \"Right tool for the job\" is no longer applicable? Then I'm out of a job :'( Jokes aside, I'm not saying to use linked lists for everything or even most things. I'm saying that there are use cases and you need to know what structure you need and how it will perform on your target machine. Blanket statements like \"linked-lists are worthless\" are not constructive or educational in any way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T15:51:04.530",
"Id": "110119",
"Score": "0",
"body": "@EmilyL.: Okay, if you find somebody making an unqualified statement that \"linked-lists are worthless\", feel free to tell them so. So far, you're showing much more about your inability to quote accurately than anything about linked lists though. If you really do have a good use-case for them, feel free to add it as an answer to [this question](http://stackoverflow.com/q/2429217/179910)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T23:39:20.230",
"Id": "110200",
"Score": "0",
"body": "That question already has plenty of good answers of uses for linked lists. But to take two examples not brought up there: free lists in memory pools, managing free heap blocks (operating systems topic). False blanket statement saying linked lists are worthless here: \"(probably shouldn't--they're pretty worthless)\", they have plenty of uses as seen by your link and my examples. Also I implore you to avoid using ad hominems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T23:43:52.787",
"Id": "110202",
"Score": "0",
"body": "@EmilyL.: I implore you to learn what *ad hominem* means before accusing people of using it (there has been nothing remotely similar to an *ad hominem* attack here). And free heap block/free lists in memory pools are really one topic, not two (and while linked lists aren't entirely worthless there, they're rarely ideal either)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T10:59:26.143",
"Id": "110264",
"Score": "0",
"body": "@JerryCoffin This \"So far, you're showing much more about your inability to quote accurately than anything about linked lists though.\" is an ad hominem attack, more specifically you're poisoning the well; My ability to quote has no bearing on my knowledge of linked lists. I have shown usages and plenty of arguments for linked lists having theirs uses counter to your blanket statement while you have failed to show any arguments for your statement. For example why is handling a heap like a linked list rarely ideal for example? What is a better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T13:01:50.373",
"Id": "110285",
"Score": "0",
"body": "@EmilyL.: An *ad hominem* argument has the form: \"X's argument should not be believed because X is an evil person.\" The wording can obviously change, but to be an *ad hominem* attack, it still has to have that intent: saying somebody's argument should not be believed because they're evil. No such statement (nor implication) has been made here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T13:06:33.610",
"Id": "110286",
"Score": "0",
"body": "@EmilyL.: As for why heaps as linked lists are rarely ideal: for pretty much the usual reasons, especially poor cache locality. The primary intent of a free list is to find a block for allocation. Given caching, a bitmap of free blocks (for one possible alternative) can do that with substantially less cache pollution."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:22:41.390",
"Id": "46425",
"ParentId": "46391",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46401",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:44:03.727",
"Id": "46391",
"Score": "6",
"Tags": [
"c++",
"linked-list",
"reinventing-the-wheel"
],
"Title": "Singly linked list implementation"
} | 46391 |
<p>This is my first PHP script (although I like to think I'm a good general coder). </p>
<p>The script accepts a number from the user, uses it to generate a regular expression, and then returns all dictionary words that match that expression. </p>
<p>It's currently live <a href="http://www.joereddington.com/major/majorEncoder.php" rel="nofollow">here</a>, and I'd appreciate any comments on style, security, best practices, and even efficiency. Please ignore the Html for now - it's got a WordPress template to be inserted into later on. </p>
<pre><code><html>
<head>
<title>Major Analysis Number Encoder</title>
</head>
<body>
<H1>Tool for finding keywords for major analysis</h1>
This tool uses the numbering system shown by Derren Brown in the
excellent book
<a
href="http://www.amazon.co.uk/Tricks-Mind-Derren-Brown/dp/1905026269">Trick
of the mind</a>. For a (much better) tool that uses the older
numbering system see
<a href="http://www.rememberg.com/">http://www.rememberg.com/</a><br>
<form action="majorEncoder.php" method="post">
<label for="firstname">Number to encode (at least three digits
please):</label> <input type="text" id="targetNumber"
name="targetNumber" /><br /> <input type="submit"
value="Generate results" name="submit" />
</form>
<?php
if ($_POST != null) {
$target = $_POST ['targetNumber'];
if (strlen ( $target ) >= 3) {
$f = '[waeiouyc]?';
$regex = '/^' . $f . $target;
echo 'You entered the target' . $target . '<br><br>';
$regex = str_replace ( '1', 'l' . $f, $regex );
$regex = str_replace ( '2', 'n' . $f, $regex );
$regex = str_replace ( '3', 'm' . $f, $regex );
$regex = str_replace ( '4', 'r' . $f, $regex );
$regex = str_replace ( '5', '[fv]' . $f, $regex );
$regex = str_replace ( '6', '[bp]' . $f, $regex );
$regex = str_replace ( '7', 't' . $f, $regex );
$regex = str_replace ( '8', '[sc]h' . $f, $regex );
$regex = str_replace ( '9', '[gd]' . $f, $regex );
$regex = str_replace ( '0', '[sz]' . $f, $regex );
$lines = file ( 'words.txt' );
$fl_array = preg_grep ( $regex . '$/', $lines );
if (sizeof ( $fl_array ) > 0) {
echo 'Exact matches: <br>';
foreach ( $fl_array as $element ) {
echo $element . '<br>';
}
echo '<br>';
}
$fl_array = preg_grep ( $regex . '/', $lines );
if (sizeof ( $fl_array ) > 0) {
echo 'Matches that allow trailing characters: <br>';
foreach ( $fl_array as $element ) {
echo $element . '<br>';
}
} else {
echo "No matches found for the input $target";
}
} else {
echo 'Please enter at least three digits<br>';
}
}
?>
</body>
</html>
</code></pre>
| [] | [
{
"body": "<p>One thing I would do is that <code>str_replace</code> can receive an array of items to look for and an array of its replacement:</p>\n\n<p><a href=\"http://www.php.net/manual/en/function.str-replace.php\" rel=\"nofollow noreferrer\">PHP str_replace</a></p>\n\n<pre><code>// Provides: You should eat pizza, beer, and ice cream every day\n$phrase = \"You should eat fruits, vegetables, and fiber every day.\";\n$healthy = array(\"fruits\", \"vegetables\", \"fiber\");\n$yummy = array(\"pizza\", \"beer\", \"ice cream\");\n\n$newphrase = str_replace($healthy, $yummy, $phrase);\n</code></pre>\n\n<p>instead of going line by line to do it.</p>\n\n<p>Just nit-picking but </p>\n\n<p>sizeof() is an alias of count() and count() is more widely used, so use something that is more general in the PHP community</p>\n\n<p>Also $_POST != null would typically be !isset($_POST) rather as explained in <a href=\"https://stackoverflow.com/questions/10949066/if-post-is-empty-function\">this post</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:54:38.310",
"Id": "46725",
"ParentId": "46394",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:29:37.623",
"Id": "46394",
"Score": "3",
"Tags": [
"php",
"regex"
],
"Title": "Generate regular expression based on inputted number"
} | 46394 |
<p>Let's say I need to write a function that applies a function to each item in a List, and then appends it to an accumulator. When the List is empty, return the accumulator.</p>
<pre><code>go :: [a] -> (a -> [b]) -> [b] -> [b]
go [] f acc = acc
go (x:xs) f acc = go xs f (acc ++ f x)
myFold :: [a] -> (a -> [b]) -> [b]
myFold as f = go as f []
</code></pre>
<p>I used the <code>go</code> function so that I wouldn't force the <code>myFold</code> caller to have to provide an empty <code>[b]</code> type. Also, I used the <code>go</code> function to achieve tail recursion. </p>
<p>In Scala, I would've put <code>@annotation.tailrec</code> to make the compilation fail if the compiler could not perform tail-call optimization.</p>
<p>Is the above code idiomatic in Haskell?</p>
| [] | [
{
"body": "<p>First, your function is <code>concatMap</code> from Prelude.</p>\n\n<p>More idiomatic ways to write it:</p>\n\n<pre><code>myFold :: (a -> [b]) -> [a] -> [b]\nmyFold = concat . map\n-- or\nmyFold f = foldr (\\x acc -> (f x) ++ acc) []\n</code></pre>\n\n<p>If efficiency is a concern, it's a completely different question. Recommended steps in priority order:</p>\n\n<ol>\n<li>Always compile at least with <code>-O2</code></li>\n<li>Lists are slow. <code>++</code> operation especially. Consider <code>Data.Sequence</code> or even <code>vector</code>s.</li>\n<li>Avoid lazyness in your types</li>\n<li>Provide all small functions with <code>INLINE</code> pragma.</li>\n<li>And more...</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T21:03:40.410",
"Id": "81085",
"Score": "0",
"body": "I'm interested in readability for this question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T22:04:59.350",
"Id": "81088",
"Score": "0",
"body": "Your second `myFold` concatenates the lists in reverse, and should probably [avoid use of foldl](http://www.well-typed.com/blog/90/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T22:37:56.963",
"Id": "81090",
"Score": "0",
"body": "@bisserlis you are right. Edited answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:41:53.507",
"Id": "46405",
"ParentId": "46395",
"Score": "2"
}
},
{
"body": "<p>You're definitely on the right track here for producing good Haskell code, assuming you're intentionally avoiding Prelude functions in favor of exercising other skills!</p>\n\n<p>The very first thing I would change is the order of arguments in your <code>myFold</code> function (and by extension <code>go</code>), i.e., pass the function to map over the list in the first position. This can help you be terse when calling it elsewhere in your code. For instance, consider these two trivial definitions of the same identity function.</p>\n\n<pre><code>listid :: [a] -> [a]\nlistid as = myFold as (:[])\n\nlistid' = myFold' (:[]) -- Implies an instance of myFold w/ arguments flipped\n</code></pre>\n\n<p>The second definition is written in <a href=\"http://www.haskell.org/haskellwiki/Pointfree\" rel=\"nofollow\">pointfree</a> style. This is considered good practice (in moderation) due to its emphasis on composing functionality over moving data around.</p>\n\n<p>The next thing I would address is hiding your helper function <code>go</code> by making it locally defined in <code>myFold</code>.</p>\n\n<pre><code>myFold f as = go ...\n where go f as acc = ...\n</code></pre>\n\n<p>This has a few benefits.</p>\n\n<ol>\n<li>If you're writing a library module here by default <code>go</code> will end up being exported to all of your users. Since this is an anonymous helper function, you probably don't want that.</li>\n<li>Because again this is a one-shot helper function, locally defining it for <code>myFold</code> keeps it close to where it's used as opposed to floating around the top-level elsewhere.</li>\n</ol>\n\n<p>That's about as idiomatic as you'll get without using Prelude functions. It is good to note however that your function is the composition of <code>concat</code> and <code>map</code>, and reusing functions from the Prelude is almost <em>always</em> better for readability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T22:49:26.977",
"Id": "46413",
"ParentId": "46395",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:33:26.747",
"Id": "46395",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Implement a fold-like Function in Haskell"
} | 46395 |
<p>Originally asked here: <a href="https://codereview.stackexchange.com/q/45310/507">Dynamically call lambda based on stream input</a></p>
<p>The following version is based heavily on the answer provided by <a href="https://codereview.stackexchange.com/a/45334/507">@iavr</a>, though I hope that I have done enough more to make it worth reviewing again.</p>
<p>A way to clean parameters of all declarations:</p>
<pre><code>template<typename Decorated>
struct CleanType
{
typedef typename std::remove_reference<Decorated>::type NoRefType;
typedef typename std::remove_const<NoRefType>::type BaseType;
};
</code></pre>
<p>Get Caller traits of a functor:</p>
<pre><code>template <typename T>
struct CallerTraits
: public CallerTraits<decltype(&T::operator())>
{};
template<typename C, typename ...Args>
struct CallerTraits<void (C::*)(Args...) const>
{
static constexpr int size = sizeof...(Args);
typedef typename std::make_integer_sequence<int, size> Sequence;
typedef std::tuple<typename CleanType<Args>::BaseType...> AllArgs;
};
// Notice the call to `CleanType` to get the arguments I want.
// So that I can create objects of the correct type before passing
// them to the functor:
</code></pre>
<p>The actual calling of the functor based on reading data from a stream (via <code>ResultSetRow</code> (but I am sure that can be easily generalized)).</p>
<p>Done in 2 parts:</p>
<p>This is the part you call:</p>
<pre><code>template<typename Action>
void callFunctor(Action action, Detail::ResultSetRow& row)
{
// Get information about the action.
// And retrieve how many parameters myst be read from
// the stream before we call `action()`
typedef CallerTraits<decltype(action)> Trait;
typedef typename Trait::Sequence Sequence;
doCall2(action, row, Sequence());
}
</code></pre>
<p>Part 2:</p>
<p>Here we extract the parameters from the stream then call the action.</p>
<pre><code>template<typename Action, int... S>
void doCall2(Action action, Detail::ResultSetRow& row, std::integer_sequence<int, S...> const&)
{
// Create a tupple that holds all the arguments we need
// to call the functior `action()`
typedef CallerTraits<decltype(action)> Trait;
typedef typename Trait::AllArgs ArgumentTupple;
// Use the template parameter pack expansion
// To read all the values from the stream.
// And place them in the tuple.
ArgumentTupple arguments(row.getValue1<typename std::tuple_element<S, ArgumentTupple>::type>()...);
// Use the template parameter pack expansion
// To call the function expanding the tupple into
// individual parameters.
action(std::get<S>(arguments)...);
}
</code></pre>
<p>Example usage:</p>
<pre><code>// Using `ResultRowSet` from below.
int main()
{
std::stringstream stream("1 Loki 12.3 2.2");
Detail::ResultRowSet row(stream);
callFunctor([](int ID, std::string const& person, double item1, float item2){
std::cout << "Got Row:"
<< ID << ", "
<< person << ", "
<< item1 << ", "
<< item2 << "\n";
}, row);
}
</code></pre>
<p>Here it will read an <code>int</code> (<code>ID</code>), a <code>std::string</code> (<code>person</code>) a <code>double</code> (<code>item1</code>) and a <code>float</code> (<code>item2</code>) from the stream (represented by row), then call the lambda provided.</p>
<p>This is not the actual implementation of <code>Detail::ResultSetRow</code>. But for code review purposes you can think of it as:</p>
<pre><code>namespace Detail
{
class ResultRowSet
{
std::istream& stream;
public:
ResultRowSet(std::istream& s)
: stream(s)
{}
template<typename T>
T getValue1()
{
T val;
stream >> val;
return val;
}
};
}
</code></pre>
| [] | [
{
"body": "<p>It is becoming really good, but there are still a few things that can be done:</p>\n\n<ul>\n<li><p>There already is a standard way to \"clean\" a type: <a href=\"http://en.cppreference.com/w/cpp/types/decay\"><code>std::decay</code></a>. It does a little bit more than just removing the reference and the <code>const</code> qualification though, but it does basically what you need. Therefore, you can totally get rid of <code>CleanType</code> and use <code>std::decay</code> instead:</p>\n\n<pre><code>using AllArgs = std::tuple<typename std::decay<Args>::type...>;\n</code></pre>\n\n<p>And since you are using C++14 (I assume this because of <code>std::integer_sequence</code>), you can even use <code>std::decay_t</code> instead:</p>\n\n<pre><code>using AllArgs = std::tuple<std::decay_t<Args>...>;\n</code></pre></li>\n<li><p><a href=\"http://open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3887.pdf\">N3887</a> also made its way to the C++14 standard. Therefore, if you actually use C++14, you will be able to use the alias template <code>std::tuple_element_t</code> instead of the metafunction <code>std::tuple_element</code>:</p>\n\n<pre><code>ArgumentTupple arguments(row.getValue1<std::tuple_element_t<S, ArgumentTupple>>()...);\n</code></pre></li>\n<li><p>This line looks kind of wrong:</p>\n\n<pre><code>typedef typename std::make_integer_sequence<int, size> Sequence;\n</code></pre>\n\n<p>When I tried to compile your example, it didn't compile at first because of the <code>typename</code> in this line. <a href=\"http://en.cppreference.com/w/cpp/utility/integer_sequence\"><code>std::make_integer_sequence</code></a> is an alias template, there shouldn't be a <code>typename</code> before it.</p></li>\n<li><p>You sometimes use <code>ResultRowSet</code> and use <code>ResultSetRow</code> at some other places. It's probably a typo or something like that :p</p></li>\n<li><p><code>ArgumentTupple</code> also feels like a typo. It should probably be <code>ArgumentTuple</code>.</p></li>\n<li><p><code>std::integer_sequence</code> does not contain anything. Therefore, there is no need to pass is by <code>const&</code>, you can simply pass it by value.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:41:16.193",
"Id": "81170",
"Score": "0",
"body": "What is the advantage of doing `using X = Y;` over `typedef Y X;`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:48:24.137",
"Id": "81171",
"Score": "0",
"body": "Sorry about `ResultRowSet` that was in the code I types in as an example and had not compiled."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:48:54.113",
"Id": "81172",
"Score": "0",
"body": "Fixed everything else. And the unit tests still work. So +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:00:26.643",
"Id": "81173",
"Score": "0",
"body": "@LokiAstari There's no advantage actually, I did it out of habit. At the very best, it allows you to always be consistent since `using` works for templates while `typedef` does not. Also, it's close to `auto X = Y;` so I never get confused about the position of the old and the new name :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:08:45.277",
"Id": "81175",
"Score": "0",
"body": "OK. Looks like another old habit I will need to break then."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T11:57:09.220",
"Id": "46448",
"ParentId": "46397",
"Score": "9"
}
},
{
"body": "<p>Good work!</p>\n\n<p>I'm also happy to see there's now <code>std::make_integer_sequence</code> in C++14, I didn't know that when I said \"similar stuff will be once part of STL\" in your previous post!</p>\n\n<p>I only have a couple of comments on top of <a href=\"https://codereview.stackexchange.com/a/46448/39083\">Morwenn</a>.</p>\n\n<ul>\n<li><p>Your <code>CleanType</code> (in case you don't use <code>std::decay</code>) could just be</p>\n\n<pre><code>template<typename Decorated>\nusing CleanType = std::remove_const<typename std::remove_reference<Decorated>::type>;\n</code></pre>\n\n<p>because</p>\n\n<ul>\n<li>it's standard to use the name <code>type</code> for the resulting type rather than a custom name like <code>BaseType</code></li>\n<li>you don't need <code>NoRefBase</code>; it's cleaner to use <code>std::remove_reference</code> or <code>std::remove_reference_t</code> directly.</li>\n</ul></li>\n<li><p>Tuple initialization</p>\n\n<pre><code>ArgumentTupple arguments(row.getValue1<typename std::tuple_element<S, ArgumentTupple>::type>()...);\n</code></pre>\n\n<p><em>really</em> needs the braces</p>\n\n<pre><code>ArgumentTupple arguments{row.getValue1<typename std::tuple_element<S, ArgumentTupple>::type>()...};\n</code></pre>\n\n<p>because the right order (left-to-right) is only guaranteed in this case (iso 8.5.4/4). Otherwise, it's implementation defined.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:28:41.220",
"Id": "81231",
"Score": "0",
"body": "I differentiate Type identifers (things that can not be objects) from other identifiers by using an initial capital letter. So `<X>::type` does not work for my naming convention. Though `<X>::Type` does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:30:54.850",
"Id": "81233",
"Score": "0",
"body": "I think you mean: \"Otherwise, it's **implementation defined** behaviour.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T05:30:22.787",
"Id": "81267",
"Score": "0",
"body": "@LokiAstari I think it is UB since evaluations of function arguments are unsequenced by 1.9/15 and no diagnostic is required. But I am not sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:26:09.523",
"Id": "81342",
"Score": "0",
"body": "@ivar: Yes they are unsequenced. But **\"Undefined Behavior\"** has a specific meaning. In that the program is not valid. Just because the arguments are evaluated in an implementation defined order does not make the program invalid (just not very portable). Otherwise `f(g(1), h(1));` would be an invalid program which obviously it is not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:15:54.990",
"Id": "81380",
"Score": "0",
"body": "@LokiAstari Ok makes sense. I read its definition again and again, but I always have a hard time getting its meaning :-) Updated accordingly."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:31:06.513",
"Id": "46501",
"ParentId": "46397",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46448",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:37:30.300",
"Id": "46397",
"Score": "11",
"Tags": [
"c++",
"c++14",
"lambda",
"template-meta-programming"
],
"Title": "Dynamically call lambda based on stream input: Try 2"
} | 46397 |
<p>I just spent almost one day to figure out the following code, which analyzes the output data from material science programs called VASP and Bader. As a Python beginner, I earnestly ask some aces to help me make this code more pythonic, or efficient. Because I know that although the code can run smoothly, it definitely needs more modification from professionals. The code is listed below, with the data file <code>ACF.dat</code> after it.</p>
<pre><code>#!/usr/bin/python
import numpy as np
def charge(x): # function to calculate charge difference
if x<4:
return 4-x # atom1
else:
return 6-x # atom2
# read from file ACF.dat
f = open('ACF.dat', 'r')
lines = []
for row in f.readlines():
tmp = row.split()
lines.append(tmp)
lines = lines[2:-4] # remove unecessary rows
lines = np.array(lines, dtype=float)
lines = lines[:,0:5] # remove unecessary columns
# calculate residual charge
chg = np.vectorize(charge)
lines[:,4] = chg(lines[:,4])
# calculate interatomic distances
dist = []
for i in range(0,len(lines)):
d = np.sqrt(np.sum((lines[i,1:4]-lines[0,1:4])**2))
dist.append(d)
lines = np.column_stack((lines, dist)) # attach dist to lines
lines = lines[lines[:,5].argsort()]
for row in lines:
print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])
f.close()
</code></pre>
<p><strong>ACF.dat</strong></p>
<p>The structure of the file is seen as the heading. What I need are the first five columns: the atomic index, the x, y, z coordinates of each atom, the atomic charge.</p>
<pre><code># X Y Z CHARGE MIN DIST ATOMIC VOL
--------------------------------------------------------------------------------
1 7.5119 7.5119 7.5119 2.9875 1.1144 20.7692
2 18.0286 18.0286 18.0286 2.8514 1.3688 23.0095
3 6.0058 18.0205 18.0205 2.8500 1.3599 22.9265
4 12.0323 18.0342 18.0342 2.8480 1.3638 22.9816
5 18.0205 6.0058 18.0205 2.8500 1.3599 22.9265
6 5.9968 5.9968 17.9789 2.7979 1.2317 22.3582
--------------------------------------------------------------------------------
VACUUM CHARGE: 0.0000
VACUUM VOLUME: 0.0000
NUMBER OF ELECTRONS: 1085.9999
</code></pre>
<p>What the code does is:</p>
<ol>
<li>Read in the content of <code>ACF.dat</code>, and removes the first two rows and last four rows. Then saves only the first five columns into array <code>lines</code>.</li>
<li>Calculates the residual charge using function <code>charge(x)</code>.</li>
<li>Calculates the interatomic distances using the x, y, z coordinates of the atoms, and attach the array of distances to <code>lines</code> as its last column.</li>
<li>Sorts lines according to the interatomic distances (column #6 of <code>lines</code>).</li>
<li>Prints out the atomic index, interatomic distances, and atomic charges.</li>
</ol>
<p>I understand that this is a lengthy question, but I still would like to ask someone helping me, and other newbies, learn Python faster by optimizing our own code. Any suggestion is welcomed.</p>
| [] | [
{
"body": "<h2>Coding style</h2>\n\n<p>For starters, read <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, which is the Python style guide. This gives suggestions on whitespace around operators and commas, variable names, and the like. Your code isn’t bad if it doesn’t follow these conventions, but it will slow down more experienced Python programmers reading your code, and might make it harder for you later when you read other people’s Python.</p>\n\n<p>You should also read <a href=\"http://legacy.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>, which explain the Python conventions for docstrings. Rather than including a description for the function on the same line as the <code>def</code>, we put it on a special line inside the function definition.</p>\n\n<p>With those two in mind, I might rewrite your <code>charge</code> function as:</p>\n\n\n\n<pre><code>def residual_charge(x):\n \"\"\"Returns the residual charge of an atom.\"\"\"\n if x < 4:\n return 4 - x # atom 1\n else:\n return 6 - x # atom 2\n</code></pre>\n\n<p>The rest of the style changes are only minor, and you can find them yourself.</p>\n\n<h2>Opening/closing the file</h2>\n\n<p>As far as I can tell, the six lines after you’ve defined <code>charge</code> are the only lines where you’re directly interacting with the file <code>ACF.dat</code>, but you don’t issue a <code>close()</code> command until the end of the script. That can cause problems if the input file is large, or if you want to load multiple files.</p>\n\n<p>I’d make three changes:</p>\n\n<ul>\n<li><p>Use Python’s <code>with open() ...</code> construction – this keeps all the file handling code in one place, and automatically closes it for you as well.</p></li>\n<li><p>Wrap this in a function: it keeps the code for processing the file input in one place, and means you can use it again if you want to feed it a different file.</p></li>\n<li><p>Go through the file a line at a time (you might not need this, but it saves loading the whole file into memory if <code>ACF.dat</code> is large).</p></li>\n</ul>\n\n<p>So I’d write something like:</p>\n\n\n\n<pre><code>def parse_dat_file(filename):\n \"\"\"Returns a numpy array based on the contents of the input file.\"\"\"\n # read the file contents\n with open(filename, 'r') as f:\n for line in f:\n parsed_lines.append(line.split())\n\n # remove unnecessary rows and columns\n parsed_lines = parsed_lines[2:-4]\n parsed_lines = np.array(parsed_lines, dtype=float)\n parsed_lines = parsed_lines[:,0:5]\n\n return parsed_lines\n</code></pre>\n\n<h2>Doing the necessary calculations</h2>\n\n<p>Again, I’d break this into a single function. It separates that block of work from the rest of the file, and makes it easier to organise. This means that if you get the data from another source, you can use the same code untouched.</p>\n\n<p>Some notes:</p>\n\n<ul>\n<li><p>In Python, a <code>range()</code> starts at 0 by default, so you don’t need to add it. If no start is supplied, it just counts from 0 upwards. You can find out more by typing <code>help(range)</code> at a Python shell.</p></li>\n<li><p>If the data set is large, you should use <code>xrange()</code> instead. This is faster when you’re using a large range of objects. See <a href=\"https://stackoverflow.com/questions/94935/what-is-the-difference-between-range-and-xrange\">What is the difference between range and xrange?</a> for more details.</p></li>\n</ul>\n\n<p>This is what I get at the end:</p>\n\n\n\n<pre><code>def process_lines(lines):\n \"\"\"Returns the lines with the residual charge and\n interatomic distances computed and added.\n \"\"\"\n # Calculate residual charge\n v_charge = np.vectorize(residual_charge)\n lines[:, 4] = v_charge(lines[:, 4])\n\n # Calculate atomic distances\n distances = []\n for i in xrange(len(lines)):\n line_sum = np.sum((lines[i, 1:4] - lines[0, 1:4]) ** 2)\n min_dist = np.sqrt(line_sum)\n distances.append(min_dist)\n\n lines = np.column_stack((lines, dist))\n lines = lines[lines[:, 5].argsort()]\n\n return\n</code></pre>\n\n<h2>Printing the file</h2>\n\n<p>Without wishing to sound like a broken record, put this in a function as well. This one is easy:</p>\n\n\n\n<pre><code>def print_data(lines):\n \"\"\"Prints the parsed and formatted data.\"\"\"\n for row in lines:\n print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])\n</code></pre>\n\n<h2>Script vs. module</h2>\n\n<p>At the end of the script, we can add the lines</p>\n\n\n\n<pre><code>acf_lines = parse_dat_file('ACF.dat')\nprint_data(process_lines(acf_lines))\n</code></pre>\n\n<p>and it will do the printing we originally set out to do.</p>\n\n<p>But now the code has been broken into separate functions, we can use it in other scripts. Say this was <code>atomic.py</code>; then we could write <code>from atomic import residual_charge</code> in another file, and we’d have access to the <code>residual_charge</code> function.</p>\n\n<p>However, when we <code>import</code> this file in another script, we don’t want it to start reading and printing <code>ACF.dat</code>; we just want the definitions. If we put the particular code for <code>ACF.dat</code> in a special <code>if</code> statement, then it <em>only</em> gets run if the file is called directly:</p>\n\n\n\n<pre><code>if __name__ == '__main__':\n acf_lines = parse_dat_file('ACF.dat')\n print_data(process_lines(acf_lines))\n</code></pre>\n\n<p>Now, if we type <code>python atomic.py</code> at a command line, this code gets run and the data is printed. If we use <code>import atomic</code> elsewhere, then we just get the function definitions. You can find out more in <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">What does <code>if __name__ == \"__main__\":</code> do?</a></p>\n\n<h2>Summary</h2>\n\n<p>If I combine everything I’ve done above and put it into a single file, then this is what I’m left with:</p>\n\n\n\n<pre><code>#!/usr/bin/python\nimport numpy as np\n\ndef residual_charge(x):\n \"\"\"Returns the residual charge of an atom.\"\"\"\n if x < 4:\n return 4 - x # atom 1\n else:\n return 6 - x # atom 2\n\ndef parse_dat_file(filename):\n \"\"\"Returns a numpy array based on the contents of the input file.\"\"\"\n # read the file contents\n parsed_lines = []\n with open(filename, 'r') as f:\n for line in f:\n parsed_lines.append(line.split())\n\n # Remove unnecessary rows and columns\n parsed_lines = parsed_lines[2:-4]\n parsed_lines = np.array(parsed_lines, dtype=float)\n parsed_lines = parsed_lines[:,0:5]\n\n return parsed_lines\n\ndef process_lines(lines):\n \"\"\"Returns the lines with the residual charge and\n interatomic distances computed and added.\n \"\"\" \n # Calculate residual charge\n v_charge = np.vectorize(residual_charge)\n lines[:, 4] = v_charge(lines[:, 4])\n\n # Calculate atomic distances\n distances = []\n for i in xrange(len(lines)):\n line_sum = np.sum((lines[i, 1:4] - lines[0, 1:4]) ** 2)\n min_dist = np.sqrt(line_sum)\n distances.append(min_dist)\n\n lines = np.column_stack((lines, distances))\n lines = lines[lines[:, 5].argsort()]\n\n return lines\n\ndef print_data(lines):\n \"\"\"Prints the parsed and formatted data.\"\"\"\n for row in lines:\n print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])\n\nif __name__ == '__main__':\n acf_lines = parse_dat_file('ACF.dat')\n print_data(process_lines(acf_lines))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:42:35.703",
"Id": "81185",
"Score": "0",
"body": "This is fantastic, thank you, Alex! Then I realize that it is always more readable to use functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:33:25.017",
"Id": "46403",
"ParentId": "46398",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46403",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:44:55.423",
"Id": "46398",
"Score": "5",
"Tags": [
"python",
"numpy"
],
"Title": "Pythonic way to manipulate arrays: a case study"
} | 46398 |
<p>The <a href="http://www.codechef.com/APRIL14/problems/ADIGIT" rel="nofollow">challenge</a> is to reconstruct an <em>n</em>-digit number using the following information:</p>
<blockquote>
<p>On each step, you choose an index <em>x</em> from 1 to <em>n</em>. For all indices <em>y</em> (<em>y</em>
< <em>x</em>), you calculate the difference <em>b</em><sub><em>y</em></sub> = <em>a</em><sub><em>x</em></sub> - <em>a</em><sub><em>y</em></sub>.</p>
<p>You then calculate <em>B</em><sub>1</sub> — sum of all by which are greater
than 0 and <em>B</em><sub>2</sub> — sum of all by which are less than 0.</p>
<p>The answer for this step is <em>B</em><sub>1</sub> - <em>B</em><sub>2</sub>.</p>
<p><strong>Input</strong></p>
<p>The first line contains two integers <em>n</em> and <em>m</em>, denoting the number
of digits and number of steps. The second line contains <em>n</em> digits
(without spaces) <em>a</em><sub>1</sub>, <em>a</em><sub>2</sub>, ..., <em>a</em><sub><em>n</em></sub>.
Each of the next <em>m</em> lines contains a single integer <em>x</em> denoting the index for
the current step.</p>
<p><strong>Output</strong></p>
<p>For each of <em>m</em> steps print single number in a line - answer of the
step.</p>
</blockquote>
<p>Can someone please help me optimize this code or provide a better, less time-consuming solution?</p>
<pre><code>import java.io.*;
import java.util.*;
public class Chefs
{
//BufferedReader in;
DataInputStream in;
PrintWriter out;
HashMap<Integer,Integer> mymap=new HashMap<Integer,Integer>();
int a[],n,m,b1,b2;
public Chefs()
{
//in=new BufferedReader(new InputStreamReader(System.in));
in=new DataInputStream(System.in);
out=new PrintWriter(System.out,true);
readInput();
calchef();
}
void readInput()
{
try
{
String digit=in.readLine();
String split[]=digit.split("\\s+");
n=Integer.parseInt(split[0]);
m=Integer.parseInt(split[1]);
a=new int[n];
digit=in.readLine();
for(int i=0;i<digit.length();i++)
a[i]=digit.charAt(i);
}
catch(Exception e)
{
e.printStackTrace();
}
}
void calchef()
{
for(int i=0;i<m;i++)
{
try
{
b1=0;
b2=0;
int index=Integer.parseInt(in.readLine());
if(mymap.containsKey(index))
{
int ans=mymap.get(index);
out.println(ans);
}
else
{
for(int j=0;j<index-1;j++)
{
if(a[index-1]-a[j]>0)
{
b1+=(a[index-1]-a[j]);
}
else
{
b2+=(a[index-1]-a[j]);
}
}
int ans=b1-b2;
out.println(ans);
mymap.put(index,ans);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
//long startTime = System.currentTimeMillis();
Chefs c=new Chefs();
//long endTime = System.currentTimeMillis();
//long totalTime = endTime - startTime;
//System.out.println(totalTime);
}
}
</code></pre>
| [] | [
{
"body": "<p>1) I would change the inner for loop this way (very little optimization, unlikely it will bring better performance)</p>\n\n<pre><code>int ans=0;\nint y=index-1;\nfor(int j=0; j<y; j++)\n{\n int diff = a[y] - a[j];\n\n if(diff > 0)\n ans += diff;\n else\n ans -= diff;\n}\n</code></pre>\n\n<p>2) You never store ans in the map.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:14:01.653",
"Id": "81580",
"Score": "0",
"body": "ya ya i forgot to add the updated code here,i missed that part,its added now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:23:37.503",
"Id": "81582",
"Score": "0",
"body": "even after ur code,it exceeds my 1sec time limit,cant it be further optimized"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T07:02:19.373",
"Id": "46436",
"ParentId": "46399",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:04:00.140",
"Id": "46399",
"Score": "5",
"Tags": [
"java",
"programming-challenge",
"complexity"
],
"Title": "Calculate difference of indices"
} | 46399 |
<p>The <code>InputHandler</code> class for my game detects key presses, turns each one into a <code>GameAction</code>, and raises an event:</p>
<pre><code>public class InputHandler
{
public delegate void ActionListener(GameActions gameAction);
public event ActionListener ActionRequested;
private void ProcessKeyboard(KeyboardState keyboardState)
{
var pressedKeys = keyboardState.PressedKeys();
foreach (var inputAction in pressedKeys.Select(GetInputAction))
{
ActionRequested(inputAction.Down);
}
var releasedKeys = keyboardState.ReleasedKeys(prevPressedKeys);
foreach (var inputAction in releasedKeys.Select(GetInputAction))
{
ActionRequested(inputAction.Up);
}
prevPressedKeys = pressedKeys;
}
}
</code></pre>
<p>Only one <code>GameAction</code> can be requested at a time. This means that if you press the key bound to <code>GameActions.MoveUp</code> and the key bound to <code>GameActions.MoveLeft</code> at the same time, two separate events are raised and it looks like your character is moving diagonally.</p>
<p>Now, I need to detect this as a single <code>GameAction</code>, e.g. <code>GameActions.MoveUpLeft</code>. There has to be a better way to do it than what I've come up with.</p>
<pre><code>private void ProcessKeyboard(KeyboardState keyboardState)
{
var pressedKeys = keyboardState.PressedKeys();
var inputActions = pressedKeys.Select(GetInputAction).ToList();
var downActions = inputActions.Select(ia => ia.Down);
if (downActions.Contains(GameActions.MoveUp) && downActions.Contains(GameActions.MoveLeft))
{
ActionRequested(GameActions.MoveUpLeft);
}
else if (downActions.Contains(GameActions.MoveUp) && downActions.Contains(GameActions.MoveRight))
{
ActionRequested(GameActions.MoveUpRight);
}
else if ...
}
</code></pre>
<p>I'm sure you can see how this can get quickly out of hand. How can I make it better?</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>var pressedKeys = keyboardState.PressedKeys();\nvar inputActions = pressedKeys.Select(GetInputAction).ToList();\nvar downActions = inputActions.Select(ia => ia.Down);\n</code></pre>\n</blockquote>\n\n<p>This is what's painted you into the corner you're in. You're not showing your <code>GameActions</code> enum (a better name would be <code>GameAction</code>, or even better, <code>MoveDirection</code>..actually, <code>Direction</code> suffices, since all there is to it is a bunch of values that each represent a direction - the point is, enum type names should not be plural), but I presume it looks something like this:</p>\n\n<pre><code>public enum GameActions\n{\n MoveLeft,\n MoveUpLeft,\n MoveUp,\n MoveUpRight,\n MoveRight,\n MoveDownRight,\n MoveDown,\n MoveDownLeft\n}\n</code></pre>\n\n<p>The problem is that <code>MoveUpLeft</code> is a combination of <code>MoveUp</code> and <code>MoveLeft</code>, and since the enum type itself doesn't account for it, your code has to.</p>\n\n<p>I'd suggest using a <code>[Flags]</code> attribute:</p>\n\n<pre><code>[Flags]\npublic enum Direction\n{\n Left = 1,\n Top = 2,\n Right = 4,\n Down = 8\n}\n</code></pre>\n\n<p>Then, instead of <code>downActions</code> being an <code>IEnumerable<GameActions></code> and using LINQ <code>IEnumearble<T>.Contains</code> extension, you can add the values of all \"down actions\", and pass <code>ActionRequested</code> an enum value that represents the sum of all pressed directions, be it <code>Left+Top</code>, <code>Down+Right</code> or whatever. The [Flags] attribute merely serves as a visual cue to remind you that these values can be combined and, using <a href=\"https://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c\">bitwise AND operations</a> or simply, the <code>.HasFlag()</code> method, the handler can determine whether the received value 3 contains <code>Direction.Left</code>:</p>\n\n<pre><code>void ActionRequested(Direction direction)\n{\n if (direction.HasFlag(Direction.Left))\n {\n // direction contains Direction.Left\n }\n if (direction.HasFlag(Direction.Right))\n {\n // direction contains Direction.Right\n }\n if (direction.HasFlag(Direction.Top))\n {\n // direction contains Direction.Top\n }\n if (direction.HasFlag(Direction.Bottom))\n {\n // direction contains Direction.Bottom\n }\n}\n</code></pre>\n\n<hr>\n\n<p>It's not clear from your post exactly what <code>GetInputAction</code> does and what <code>downActions</code> means, so it's hard to recommend a change that will fit into your code, but here's some inspiration:</p>\n\n<pre><code>class Program\n{\n [Flags]\n public enum Direction\n {\n Left = 1,\n Top = 2,\n Right = 4,\n Bottom = 8\n }\n\n static void Main(string[] args)\n {\n var direction = (Direction)3;\n Console.WriteLine(\"Direction: {0}\", direction);\n Console.WriteLine(\"Left: {0}\", direction.HasFlag(Direction.Left);\n Console.WriteLine(\"Top: {0}\", direction.HasFlag(Direction.Top);\n Console.WriteLine(\"Right: {0}\", direction.HasFlag(Direction.Right);\n Console.WriteLine(\"Bottom: {0}\", direction.HasFlag(Direction.Bottom);\n\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<p><img src=\"https://i.stack.imgur.com/6B6Dl.png\" alt=\"enter image description here\"></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T04:48:41.590",
"Id": "81113",
"Score": "1",
"body": "The flags thing is just what I was looking for. I knew there was some way to combine enum values but I couldn't even think of how to phrase what exactly I was trying to do."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T04:15:25.897",
"Id": "46428",
"ParentId": "46404",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:39:45.220",
"Id": "46404",
"Score": "7",
"Tags": [
"c#",
"xna"
],
"Title": "Turn multiple key presses into single GameAction"
} | 46404 |
<p>I've written this class as an exercise for a synchronization construct to be used across multiple threads.</p>
<p>The intent is to have worker threads <code>Increment()</code> it, do some work, then finally <code>Decrement()</code>it.</p>
<p>Meanwhile, when a master thread decides to shut down the program, it signals the threads using a <code>CancellationToken</code> and <code>Wait()</code>s on this structure until all threads have ceased (signalled by <code>_number</code> hitting zero).</p>
<p>I am depending mainly on the fact that Interlocked operations imply full memory fences. I am concerned with the read on the <code>Wait()</code> method, see the comment there.</p>
<pre><code>public class CountdownLatch
{
int _number;
readonly ManualResetEventSlim _event;
public CountdownLatch()
{
this._event = new ManualResetEventSlim();
}
public void Increment()
{
Interlocked.Increment(ref this._number);
}
public void Decrement()
{
int currentNumber;
bool firstAttempt = true;
do
{
currentNumber = this._number;
if (!firstAttempt)
{
var spinWait = new SpinWait();
spinWait.SpinOnce();
}
else
{
firstAttempt = false;
}
if (currentNumber == 0)
{
throw new InvalidOperationException("Attempt to decrement past zero");
}
} while (Interlocked.CompareExchange(ref this._number, currentNumber - 1, currentNumber) != currentNumber);
if (currentNumber == 1)
{
this._event.Set();
}
}
public bool Wait(TimeSpan timeout)
{
// Should this be a volatile read: Volatile.Read(ref this._number) ?
// AFAICT the memory barrier here would prevent instruction reordering
// when the order of reads/writes matter, but here it doesn't. I just care
// to have the latest value of this._number across all CPUs/cores.
// Or does volatile read in C# specifically do both ?
if (this._number == 0)
{
return true;
}
return this._event.Wait(timeout);
}
}
</code></pre>
| [] | [
{
"body": "<h3>The Good</h3>\n<p>I don't write multithreaded code very often, so other reviewers will probably have other comments (read: I'm a <a href=\"/questions/tagged/multithreading\" class=\"post-tag\" title=\"show questions tagged 'multithreading'\" rel=\"tag\">multithreading</a> beginner myself), but I like what I'm seeing.</p>\n<blockquote>\n<pre><code>Interlocked.Increment(ref this._number);\n</code></pre>\n</blockquote>\n<p>I don't see anything that could go wrong with this. This is how I've read a thread-safe increment should be done, using the <code>Interlocked</code> class.</p>\n<blockquote>\n<pre><code>while (Interlocked.CompareExchange(ref this._number, currentNumber - 1, currentNumber) != currentNumber)\n</code></pre>\n</blockquote>\n<p>Looks good to me. <code>currentNumber</code> belongs to the thread that's running this, so no thread can mess with <em>that</em> <code>currentNumber</code> while <code>currentNumber - 1</code> or <code>CompareExchange</code> is being evaluated, and again the <code>Interlocked</code> class at play has my full trust.</p>\n<hr />\n<h3>The Bad</h3>\n<p>Ignorance is bliss, nothing in sight.</p>\n<hr />\n<h3>The Ugly</h3>\n<p>The very first thing that jumped at me, is the abundance of redundant <code>this</code> qualifiers. They're not needed, you have underscores:</p>\n<blockquote>\n<pre><code>int _number;\nreadonly ManualResetEventSlim _event;\n</code></pre>\n</blockquote>\n<p>I like the underscore prefix, because it allows me to have a <code>_number</code> field and a <code>number</code> parameter or local variable, for example:</p>\n<pre><code>public CountdownLatch(ManualResetEventSlim event)\n{\n _event = event;\n}\n</code></pre>\n<p>The way I read <code>currentNumber</code>, <em>"current"</em> stands for <em>"current thread's working copy of <code>_number</code>"</em>. I find the name <code>number</code> conveys that more succinctly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:52:24.797",
"Id": "81158",
"Score": "0",
"body": "I was hoping for some feedback on thread-safety rather than code style :-). I use \"this\" to increase readability, it is part of a code convention I follow in all my code. Your understanding of \"current\" is exactly right. I meant to emphasize that I am making a copy of shared memory to a private variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:18:11.050",
"Id": "81163",
"Score": "0",
"body": "I'm not experienced enough with threaded code to specifically address the read in `Wait`; I preferred leaving that to other reviewers. Remember that CR answers may address any aspect of the code; if you used ReSharper you'd see code inspections suggesting to remove the redundant `this` qualifiers (they'd show up faded, too). It might be personal preference, but I find non-needed qualifiers clutter up the code, whether it's `this` or a namespace."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T06:46:56.210",
"Id": "46435",
"ParentId": "46407",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T19:59:59.150",
"Id": "46407",
"Score": "5",
"Tags": [
"c#",
"multithreading",
"thread-safety",
"lock-free"
],
"Title": "CountdownLatch Thread-Safety Check"
} | 46407 |
<p>I have some code which is designed for the following purposes:</p>
<ol>
<li>Implement a cache structure which stores cached elements, as well as a method for reloading those elements.</li>
<li>Ensure the new structure can use any type of <code>IEnumerable</code> to store the elements.</li>
<li>Implement a dynamic cache which inherits from the standard cache, as well as storing additional methods for appending new elements and determining which elements to drop.</li>
<li>Ensure the dynamic cache can only use List to store the cached elements, in order to make use of <code>List<T>.AddRange</code> and <code>List<T>.RemoveAll</code>.</li>
</ol>
<p>This works, but seems unnecessarily complicated. I essentially have 5 classes and 1 interface to pull this off, and having to declare <code>TEnumerable</code> as <code>IEnumerable<TElement></code> in the where clause of a class declaration feels odd at best.</p>
<p>Is there a simpler way to implement this?</p>
<pre><code>internal interface ICache : IEnumerable
{
bool Contains(object element);
}
internal class DynamicCache<TElement> : DynamicCache<List<TElement>, TElement> {
internal DynamicCache(
Func<List<TElement>> initElements
, Func<List<TElement>> addElements
, Predicate<TElement> dropElementsIf
)
: base(initElements, addElements, dropElementsIf)
{
}
}
internal class DynamicCache<TEnumerable, TElement> : Cache<TEnumerable, TElement> where TEnumerable : List<TElement> {
protected Func<TEnumerable> AddElements;
protected Predicate<TElement> DropElementsIf;
internal DynamicCache(
Func<TEnumerable> initElements
, Func<TEnumerable> addElements
, Predicate<TElement> dropElementsIf
)
: base(initElements)
{
this.AddElements = addElements;
this.DropElementsIf = dropElementsIf;
}
protected override sealed void UpdateElements() {
if (!isInitialized) {
this.elements = InitElements();
this.isInitialized = true;
}
else {
this.elements.AddRange(AddElements());
this.elements.RemoveAll(DropElementsIf);
}
}
}
internal class Cache<TElement> : Cache<IEnumerable<TElement>, TElement> {
internal Cache(Func<IEnumerable<TElement>> initElements)
: base(initElements)
{
}
}
internal class Cache<TEnumerable, TElement> : IEnumerable<TElement>, ICache where TEnumerable : IEnumerable<TElement> {
protected TEnumerable elements;
protected bool isInitialized;
protected Func<TEnumerable> InitElements;
internal Cache(Func<TEnumerable> initElements) {
this.InitElements = initElements;
}
protected virtual void UpdateElements() {
if (!isInitialized) {
this.elements = InitElements();
this.isInitialized = true;
}
}
public IEnumerator<TElement> GetEnumerator() {
UpdateElements();
foreach (TElement element in this.elements) {
yield return element;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return (IEnumerator)this.GetEnumerator();
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
foreach (TElement element in this) {
sb.Append(element.ToString() + "\n");
}
sb.Append("\n");
return sb.ToString();
}
bool ICache.Contains(object element) {
if (element is TElement) {
return this.Contains((TElement)element);
}
return false;
}
internal bool Contains(TElement element) {
UpdateElements();
return this.elements.Contains(element);
}
}
internal class Wrapper {
internal int id {get; set;}
internal string name {get; set;}
public override string ToString() {
return string.Format("Wrapper id: {0}, name: {1}", this.id, this.name);
}
}
internal static class Builder {
internal static int WrapperCount;
static Builder() {
WrapperCount = 0;
}
internal static IEnumerable<Wrapper> WrapperFactory(int count) {
Wrapper[] wArray = new Wrapper[count];
for (var i = 0; i < count; i++) {
wArray[i] = Builder.SingleWrapperFactory();
}
return wArray;
}
internal static Wrapper SingleWrapperFactory() {
return new Wrapper {
id = WrapperCount,
name = "Wrapper " + WrapperCount++
};
}
}
void Main()
{
// example Cache usage
Cache<Wrapper> wCache = new Cache<Wrapper>(
() => Builder.WrapperFactory(5) // Initialize with 5 Wrappers from the Builder
);
Debug.Write("Standard Cache Pass 1: \n" + wCache); // 0, 1, 2, 3, 4
Debug.Write("Standard Cache Pass 2: \n" + wCache); // 0, 1, 2, 3, 4
// example DynamicCache usage
DynamicCache<Wrapper> wDynamicCache = new DynamicCache<Wrapper>(
() => Builder.WrapperFactory(5).ToList() // Initialize with 5 Wrappers from the Builder
, () => Builder.WrapperFactory(3).ToList() // Append 3 new Wrappers from the Builder on each iteration
, (w) => w.id < Builder.WrapperCount - 5 // Remove items which have an id less than Builder.WrapperCount
);
Debug.Write("Dynamic Cache Pass 1: \n" + wDynamicCache); // 5, 6, 7, 8, 9
Debug.Write("Dynamic Cache Pass 2: \n" + wDynamicCache); // 8, 9, 10, 11, 12
Debug.Write("Dynamic Cache Pass 3: \n" + wDynamicCache); // 11, 12, 13, 14, 15
Debug.Write("Dynamic Cache Pass 4: \n" + wDynamicCache); // 14, 15, 16, 17, 18
ICache iCache = new Cache<string>(
() => new HashSet<string> { "this", "is", "my", "new", "HashSet<string>", "to", "use", "in", "ICache" }
);
Debug.Write("iCache.Contains(\"use\") : " + iCache.Contains("use"));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T07:12:40.640",
"Id": "81274",
"Score": "3",
"body": "This seems unnecessary: \"Ensure the new structure can use any type of `IEnumerable` to store the elements.\" and it contradicts with \"Ensure the dynamic cache can only use `List` to store the cached elements, in order to make use of `List<T>.AddRange` and `List<T>.RemoveAll`.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T13:10:17.247",
"Id": "81315",
"Score": "0",
"body": "The main reason behind that original request was to be able to use a HashSet with the base Cache class in order to improve the performance of a .Contains call. The other reason I would like to use inheritance for the DynamicCache is that the Cache class is considerably more complicated (including some thread safety items, cache states, etc), and all of its methods can be used with the DynamicCache."
}
] | [
{
"body": "<p>Interface design is wanting.</p>\n\n<p>This looks like this was made by mistake:</p>\n\n<pre><code>internal interface ICache : IEnumerable\n{\n bool Contains(object element);\n}\n</code></pre>\n\n<p>It should implement <code>IEnumerable<T></code> which already provides <code>IEnumerable</code> functionality. </p>\n\n<pre><code>internal interface ICache<TElement> : IEnumerable<TElement>\n{\n bool Contains(TElement element);\n}\n</code></pre>\n\n<p>This way you can do <code>Cache<TEnumerable, TElement> : ICache<TElement></code> instead of <code>class Cache<TEnumerable, TElement> : IEnumerable<TElement>, ICache</code>. Which allows non-type-safe and redundant <code>Contains(object)</code> method.</p>\n\n<p>More importantly though your <code>ICache</code> provides no additional functionality w.r.t any other <code>IEnumerable<T></code>, given <code>IEnumerable</code> already has a <code>Contains</code> extension method.</p>\n\n<p>Before writing some component, you should be able to write <em>interfaces</em> thereof, and test the required functionality against those interfaces.</p>\n\n<p>In general:</p>\n\n<ul>\n<li>a cache is a specialized Key-Value store. </li>\n<li>They are used to improve read performance where reads outnumber updates by far, and write are relatively expensive.</li>\n<li>They exploit time locality (and <em>sometimes</em> space) <a href=\"http://en.wikipedia.org/wiki/Locality_of_reference#Types_of_locality\">locality</a>.</li>\n</ul>\n\n<p>The only way to access the elements in your cache is through enumerating them. Which precludes random access. For example you cannot get a <code>Wrapper</code> with a given <code>id</code> from the cache.</p>\n\n<p><code>GetEnumerator</code> modifies the underlying collection by calling <code>UpdateElements();</code>, \nand this ruins the other two properties.\nYou cannot exploit there being many more reads than updates, because every read is an update. \nYou cannot exploit time locality because even if you are reading the same elements over and over again you are updating the collection.</p>\n\n<p>Consider this:</p>\n\n<pre><code>DynamicCache<Wrapper> wDynamicCache = //......\n\nvar wrapper = new Wrapper{id=10, name = \"Wrapper 10\"};\nConsole.WriteLine(wDynamicCache.Contains(wrapper)); // False\nConsole.WriteLine(wDynamicCache.Contains(wrapper)); // True\nConsole.WriteLine(wDynamicCache.Contains(wrapper)); // False\n</code></pre>\n\n<p>In order to exploit time (or other) locality is choosing the correct <a href=\"http://en.wikipedia.org/wiki/Cache_algorithms\"><em>caching strategy</em></a>. \nFor example if some data feed is updated on average once a day, you might decide to not hit the source if cache contains a data read in the past 6 hours. \nOr you might want to have a fixed size cache which automatically evicts the least recently used when it is full and a value not contained therein is accessed.</p>\n\n<p>But these types of common strategies cannot be implemented with a <code>Predicate<TElement> dropElementsIf</code>. You might try to wrap the data with last access time etc details, as you already did in your test; but this would leak to the interface, as <code>TElement</code> is now a wrapper with implementation details. For example changing caching strategy will require recompiling the code using the cache.</p>\n\n<p>Some other problems not specific to caches:</p>\n\n<ul>\n<li>everytime <code>Cache</code> classes are accessed <code>UpdateElements</code> is called even though <code>Cache</code> classes are not dynamic by default.</li>\n<li><code>protected bool isInitialized;</code> is present on Cache \nand also everytime <code>Cache</code> classes are accessed checked even if it consists of a fixed collection of elements.</li>\n<li><p>Every overriding method of <code>UpdateElements</code> must start with copied : </p>\n\n<pre><code>if (!isInitialized) {\n this.elements = InitElements();\n this.isInitialized = true;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:37:46.327",
"Id": "82751",
"Score": "0",
"body": "This is true, thank you for your response. In production, I have an Enum which captures the state of the cache, which allows me to only execute updates as necessary. I think I agree with you about ICache, though. I had originally intended to implement a CachePool class which contained an internal dictionary of <string, ICache>, which in turn required me to have ICache be non-generic (I think...), but the methods around it just felt awkward. I ended up with a lot of manual type casting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T11:30:12.643",
"Id": "47224",
"ParentId": "46409",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:16:08.143",
"Id": "46409",
"Score": "6",
"Tags": [
"c#",
"generics"
],
"Title": "Maintaining a cache structure with elements"
} | 46409 |
<p>I have been working with C++11 code that uses <code>std::vector[]</code> to store coordinates. Most often this code uses 2D or 3D but it occurred to me that it may be generally useful for n-dimensional Euclidean distance calculations.</p>
<p>Because these calculations are used within a simulation, they should be as fast as practical without sacrificing generality. </p>
<pre><code>// euclid.h
#include <vector>
#include <algorithm>
#include <stdexcept>
template <typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)
{
if (a.size() != b.size())
throw std::domain_error("vector addition must have equal length vectors");
std::vector<T> result;
result.reserve(a.size());
std::transform(a.begin(), a.end(), b.begin(),
std::back_inserter(result), std::plus<T>());
return result;
}
template <typename T>
std::vector<T> operator-(const std::vector<T>& a, const std::vector<T>& b)
{
if (a.size() != b.size())
throw std::domain_error("vector subtraction must have equal length vectors");
std::vector<T> result;
result.reserve(a.size());
std::transform(a.begin(), a.end(), b.begin(),
std::back_inserter(result), std::minus<T>());
return result;
}
template <typename T>
T squared_distance(const std::vector<T>& a, const std::vector<T>& b)
{
if (a.size() != b.size())
throw std::domain_error("squared_distance requires equal length vectors");
return std::inner_product(a.begin(), a.end(), b.begin(), T(0),
std::plus<T>(), [](T x,T y){return (y-x)*(y-x);});
}
</code></pre>
<p>Here is some driver code to demonstrate usage.</p>
<pre><code>// points.cpp
#include <iostream>
#include <vector>
#include "euclid.h"
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T> &v)
{
out << "{ ";
for (auto p : v)
out << p << ' ';
return out << "}";
}
#define say(x) std::cout << "" #x " = " << (x) << std::endl
int main()
{
std::vector<double> origin{0, 0, 0}, a{3, 4, 5}, b{-1, -2, -3},g{0,0,0,0};
say(origin);
say(a);
say(b);
say(a+b);
say(a-b);
say(b-a);
say(squared_distance(origin,a));
say(squared_distance(origin,b));
}
</code></pre>
<p>The output from the program looks like this:</p>
<pre><code>origin = { 0 0 0 }
a = { 3 4 5 }
b = { -1 -2 -3 }
a+b = { 2 2 2 }
a-b = { 4 6 8 }
b-a = { -4 -6 -8 }
squared_distance(origin,a) = 50
squared_distance(origin,b) = 14
</code></pre>
<p>I'm interested in general ideas for improvement or criticism of the existing code, but I also have some specific questions:</p>
<ol>
<li>can the squared_distance calculation be made more efficient?</li>
<li>is there a nice way to reduce code duplication in the <code>+</code> and <code>-</code> operators?</li>
<li>I've tested with <code>int</code>, <code>float</code>, <code>double</code> and <code>std::complex</code>. What else might be useful?</li>
<li>is there any point to accommodating <code>unsigned</code> types?</li>
<li>should I do anything about possible numeric overflow or underflow?</li>
<li>is there any point to having an <code>#ifndef</code> header guard in this file?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-26T12:50:01.533",
"Id": "254755",
"Score": "0",
"body": "If you want performance, forcing a memory allocation for each coordinate sounds like a bad idea."
}
] | [
{
"body": "<p>I know that this won't answer any of your questions, but instead of using <code>std::vector<T></code>, you should consider using <code>std::array<T, N></code> to represent your data. Here is why this design could be more interesting:</p>\n\n<ul>\n<li><code>std::array<T, N></code> uses stack memory while <code>std::vector<T></code> uses heap memory. I bet that a stack-allocated array will be a little bit more efficient than a heap-allocated vector.</li>\n<li>Mathematically speaking, it does not make any sense to change the size of a vector. Therefore, a fixed size container will also ensure that the size does not change.</li>\n<li>You won't have to bother with <code>reserve</code> anymore.</li>\n<li><p>In your functions, you make sure that the vector you add or subtract have the same size. If you use <code>std::array<T, N></code> to store your data, you will get an implicit compile time check instead of an explicit runtime one:</p>\n\n<pre><code>template <typename T, size_t N>\nstd::array<T, N> operator+(const std::array<T, N>& a, const std::array<T, N>& b)\n{\n std::array<T, N> result;\n for (size_t i = 0 ; i < N ; ++i)\n {\n result[i] = a[i] + b[i];\n }\n return result;\n}\n</code></pre>\n\n<p>Moreover, since your loop has a static condition, it may be unrolled at compile time by the compiler.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:52:29.207",
"Id": "81188",
"Score": "1",
"body": "Just a note: efficiency-wise (regardless of changing the container type), you are dropping the need to update the container size at each iteration, but at the same time you are implictly default-initializing all elements *before* entering the loop. This is exactly why Edward is using `reserve` and `back_inserter`, to avoid unnecessary initialization. Otherwise, one could say `std::vector<T> result(N);` and then write the same `for` loop as yours. Without measurements I cannot say which approach is better, but for me none is good enough (see discussion in my answer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:56:29.260",
"Id": "81189",
"Score": "0",
"body": "Plus, I bet you can't fit 10^7 elements on the stack, so it really depends on the application. The fact that STL algorithms are defined on iterators rather than containers has something to say (not on convenience, but at least on performance and genericity)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:15:26.983",
"Id": "81196",
"Score": "0",
"body": "@iavr Those were some of my concerns, but since he mainly talked about 2D and 3D vectors, I considered that those weren't major drawbacks. I don't believe that many people perform computations in 10^7 dimensions Euclidean space."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:26:46.463",
"Id": "81214",
"Score": "0",
"body": "@Morwenn You're right. Since modern physics says that all of spacetime can be described in [11 dimensions](http://en.wikipedia.org/wiki/M-theory), more than that seems extravagant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:50:50.323",
"Id": "81217",
"Score": "0",
"body": "@Morwenn,Edward Well, algorithms for 2D/3D or even 11D spaces would rather use `std:array` if the number of dimensions is (compile-time) fixed. On the other hand, a color 1024x768 image has roughly 2,5M elements and I routinely do vector operations on such objects, or [even worse](http://image.ntua.gr/iva/files/agm.pdf). Element-wise operations, norms and squared distances remain the same in both cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:59:35.403",
"Id": "81218",
"Score": "0",
"body": "@iavr Since the original purpose was Euclidean space vectors, I wouldn't have used the class for other purposes. I would probably have made another class for another kind of vector. The problem is that the word \"vector\" is polysemous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:07:58.867",
"Id": "81219",
"Score": "0",
"body": "@Morwenn Well, what makes a space Euclidean are certain mathematical properties that have nothing to do with the number of dimensions. It's not a matter of polysemy, rather a matter of application domain."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T23:48:54.133",
"Id": "46415",
"ParentId": "46410",
"Score": "4"
}
},
{
"body": "<p>To reduce redundancy, I'd probably move the check for the inputs being the same size into a function template by itself, and just invoke that from the other three:</p>\n\n<pre><code>template <typename T>\nvoid check_size(std::vector<T> const &a, std::vector<T> const &b) {\n if (a.size() != b.size())\n throw std::domain_error(\"vector addition must have equal length vectors\");\n}\n</code></pre>\n\n<p>I'd then at least test with passing one of the input parameters by value, using it as the destination for the calculation, and returning it:</p>\n\n<pre><code>template <typename T>\nstd::vector<T> operator+(std::vector<T> a, const std::vector<T>& b)\n{\n check_size(a, b);\n std::transform(a.begin(), a.end(), \n b.begin(), \n a.begin(), \n std::plus<T>());\n return a;\n}\n</code></pre>\n\n<p>Although this doesn't always improve speed, it does often enough to be worth testing/profiling to see how well it works in this case.</p>\n\n<p>Another possibility to consider would be using <code>std::valarray</code> instead. It's the forgotten step-child (so to speak) of the C++ standard, but it was designed specifically to support fast numeric calculations. It already defines equivalents of your <code>+</code> and <code>-</code> operators, as well as a <code>sum</code> and <code>*</code> operators, so your code comes out something like this:</p>\n\n<pre><code>std::valarray<double> origin{ 0, 0, 0 }, a{ 3, 4, 5 }, b{ -1, -2, -3 }, g{ 0, 0, 0, 0 };\nsay(origin);\nsay(a);\nsay(b);\nsay(a + b);\nsay(a - b);\nsay(b - a);\nsay(((a - origin) * (a - origin)).sum());\nsay(((b - origin) * (b - origin)).sum());\n</code></pre>\n\n<p>Since <code>std::valarray</code> defines all the operators we're using, the only other code we need is the <code>say</code> macro and the <code>operator<<</code> overload (minutely modified to take a <code>std::valarray</code> parameter instead of a <code>std::vector</code>).</p>\n\n<p>Considering your more specific questions:</p>\n\n<p>specific questions:</p>\n\n<blockquote>\n <ul>\n <li>can the squared_distance calculation be made more efficient?</li>\n </ul>\n</blockquote>\n\n<p><code>std::valarray</code> and/or <code>std::array</code> might help--but for a relatively small number of dimensions, I wouldn't expect to see much difference.</p>\n\n<blockquote>\n <ul>\n <li>is there a nice way to reduce code duplication in the + and - operators?</li>\n </ul>\n</blockquote>\n\n<p>The code above attempts to answer this, to at least some degree.</p>\n\n<blockquote>\n <ul>\n <li>I've tested with int, float, double and std::complex. What else might be useful?</li>\n <li>is there any point to accommodating unsigned types?</li>\n </ul>\n</blockquote>\n\n<p>I don't see a lot of point in unsigned types for this task. Yes, distances are always positive, but you can pretty easily end up with a negative number from an intermediate calculation, and you don't want that wrapping around to a large number as it would with an unsigned type.</p>\n\n<blockquote>\n <ul>\n <li>should I do anything about possible numeric overflow or underflow?</li>\n </ul>\n</blockquote>\n\n<p>Harder to say. It basically depends on the use to which you're putting the code. If you need the distance, there are ways of computing it that avoid the larger magnitude of the squared distance (even as an intermediate), and are fairly fast to compute as well--but they're still slower than computing the squared distance, in which case the final result is also often the single largest value you deal with, so there's not a lot you can about overflow. </p>\n\n<p>In floating point, subtraction is one of the prime culprits that can/will lead to precision loss. At least in theory, you might prefer to avoid it if possible, but for finding a squared distance I don't know of a lot of alternatives either.</p>\n\n<blockquote>\n <ul>\n <li>is there any point to having an #ifndef header guard in this file?</li>\n </ul>\n</blockquote>\n\n<p>The compiler will (or should, anyway) give errors if you include it twice in the same translation unit, so it wouldn't hurt. Of course, you're unlikely to include it twice in the same translation unit directly, but its getting included via two other headers wouldn't be all that rare an occurrence.</p>\n\n<p>I was going to mention <code>std::array</code> as well, but while I was writing this, I see @Morwenn has written one about that already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T09:52:30.577",
"Id": "81128",
"Score": "0",
"body": "Sorry about that :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:01:07.103",
"Id": "81134",
"Score": "0",
"body": "I had completely forgotten about `std::valarray` and just now read the relevant bits of the standard about it. Seems tailor-made for what I'm trying to do, so I'll do some performance tests with `std::vector`, `std::array` and `std::valarray` and post results soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:02:28.467",
"Id": "81190",
"Score": "3",
"body": "I think `std::valarray` was forgotten by its designers first, then by the users. When you start using it you realize you want more, but this more is simply not there :-("
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T00:38:21.167",
"Id": "46417",
"ParentId": "46410",
"Score": "8"
}
},
{
"body": "<p>Regarding duplication, you could have a single function for applying a function elementwize:</p>\n\n<pre><code>template< typename T, typename U, typename BinaryFunc >\nauto elementwise_apply(const vector<T> &x, const vector<U> &y, BinaryFunc func)\n -> vector<decltype(func(x[0], y[0]))>\n{\n // apply `func` to all arguments and return a vector\n}\n</code></pre>\n\n<p>and then declare your other binary operations in terms of it</p>\n\n<pre><code>template< typename T>\nvector<T> operator+(const vector<T> &x, const vector<T> &y)\n{\n return elementwise_apply(x, y, plus<T>());\n}\n</code></pre>\n\n<p>and so forth.</p>\n\n<p>I also agree with seeing if you can use <code>array</code> rather than <code>vector</code> -- the more that you can make happen at compile-time rather than run time, the better. Similarly, fewer dynamic allocations and fewer non-inlined functions would generally lead to more efficient code.</p>\n\n<p>I would also suggest that you consider making a <code>point</code> struct that has an <code>array</code> member (or a <code>vector</code> member), rather than using a naked <code>array</code>, so that all of your functions will only applicable to objects meant to actually refer to points.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T01:24:38.100",
"Id": "46422",
"ParentId": "46410",
"Score": "6"
}
},
{
"body": "<p>I am working on this topic so I have much to say, please bear with me. I am starting with your question (2), which is the most interesting. At the same time, I am making a series of abstraction and generalization steps. The final result will appear weird at first, but is quite more powerful than your current setup, in different ways. I will then discuss your remaining questions quite shortly. All my suggestions can be seen in a <a href=\"http://coliru.stacked-crooked.com/a/7888e81f27dfffbc\" rel=\"noreferrer\">live example</a>.</p>\n<h2>Generalizations</h2>\n<p>Before coming to your question, let's look at a couple of limitations in the current approach</p>\n<pre><code>operator+(const std::vector<T>& a, const std::vector<T>& b)\n</code></pre>\n<p>(A) Why should the vectors have the same value type? Better, why have the same kind of containers in the first place?</p>\n<p>(B) Why limit the operation to two arguments? there are unary operators out there, and there are n-ary functions as well.</p>\n<p>Issue (A) can be dealt with by a few type functions:</p>\n<pre><code>template <typename C, typename T>\nstruct subs_type;\n\ntemplate <template <typename...> class C, typename T, typename... A, typename S>\nstruct subs_type<C<T, A...>, S> { using type = C<S, A...>; };\n\ntemplate <typename... A>\nusing container_common_type = std::common_type<typename A::value_type...>;\n\ntemplate <typename A, typename... B>\nusing container_result =\n subs_type<A, typename container_common_type<A, B...>::type>;\n</code></pre>\n<p>In words, we are finding the common type of all value types of the given container types, and we are generating a new container of the same kind (e.f. <code>std::vector</code> with the first container and the common value type. Additional template parameters like allocators etc. are reused.</p>\n<p>Issue (B) can be dealt with by a quite generic function object <code>apply</code>:</p>\n<pre><code>template <typename F>\nstruct apply : F\n{\n using F::operator();\n\n template <typename A, typename... B>\n typename container_result<A, B...>::type\n operator()(const A& a, const B&... b) const\n {\n using R = typename container_result<A, B...>::type;\n\n if (_or()(a.size() != b.size()...))\n throw std::domain_error("vector operation must have equal length vectors");\n\n R result;\n result.reserve(a.size());\n auto r = std::back_inserter(result);\n transform(*this, r, a.begin(), a.end(), b.begin()...);\n return result;\n }\n};\n</code></pre>\n<p>In words, <code>apply</code> applies function object of type <code>F</code> to input arguments of types <code>A, B...</code>. There are a few interesting generalizations here:</p>\n<ul>\n<li><p>It requires <em>at least</em> one input argument <code>A</code>, but otherwise the fully variadic definition allows unary, binary, or arbitrary n-ary functions.</p>\n</li>\n<li><p>It <em>derives</em> function object <code>F</code>, <em>overloads</em> its <code>operator()</code>, and uses <em>itself</em> as a function when entering <code>transform</code>. This allows <em>recursive</em> application so that the same object can apply to scalars as well as any kind of container. We'll see an example below under your question 3.</p>\n</li>\n</ul>\n<p>However, it keeps the same logic of storing the result, using <code>reserve</code> and <code>back_inserter</code>. I am discussing alternatives later on.</p>\n<p>The underlying operations required by <code>apply</code> are the following:</p>\n<pre><code>struct _or\n{\n constexpr bool operator()() const { return false; }\n\n template <typename A, typename... B>\n constexpr bool operator()(A&& a, B&&... b) const\n { return std::forward<A>(a) || operator()(std::forward<B>(b)...); }\n};\n\nstruct _do { template <typename... A> _do(A&&...) { } };\n\ntemplate <typename F, typename R, typename I, typename E, typename... J>\nvoid transform(const F& f, R r, I i, E e, J... j)\n{\n for (; i != e; _do{++r, ++i, ++j...})\n *r = f(*i, *j...);\n}\n</code></pre>\n<p>Function object <code>_or</code> is pretty much self-explanatory: it's an n-ary generalization of <code>operator||</code>.</p>\n<p>Function <code>transform</code> is maybe the weirdest of all. It is more or less an n-ary generalization of <code>std::transform</code>. <code>r</code> is the output iterator, <code>i,e</code> are the current iterator and <code>end</code> respectively of the first container, and <code>j...</code> are the iterators of the remaining iterators. The function object and the output iterator come first, to allow for variadic input iterators in the sequel. All iterators are passed by value.</p>\n<p>In words, <code>transform</code> has an output and a number of input iterators. All iterators advance <em>in parallel</em>. At each iteration, function object <code>f</code> is applied to the dereferenced values of all input iterators <code>*i, *j...</code> and the result is stored to the value of the output iterator <code>*r</code>.</p>\n<p>Auxiliary struct <code>_do</code> allows for variadic, sequenced evaluation of its contained sub-expressions. I use it quite frequently, see <code>Do</code> <a href=\"https://codereview.stackexchange.com/a/45334/39083\">here</a> for more.</p>\n<h2>Code duplication</h2>\n<blockquote>\n<p>(2) is there a nice way to reduce code duplication in the + and - operators?</p>\n</blockquote>\n<p>Ok, whatever tools the language provides for generic programming, there comes a time when macros become inevitable. <strong>Macros?</strong> Before rushing to criticize, look at the following and please keep your mind open:</p>\n<pre><code>MYLIB_OP_UNARY(plus, +)\nMYLIB_OP_UNARY(minus, -)\n\nMYLIB_OP_BINARY(add, +)\nMYLIB_OP_BINARY(sub, -)\nMYLIB_OP_BINARY(mul, *)\nMYLIB_OP_BINARY(div, /)\nMYLIB_OP_BINARY(mod, %)\n\nMYLIB_OP_BINARY(eq, ==)\nMYLIB_OP_BINARY(neq, !=)\nMYLIB_OP_BINARY(gt, >)\nMYLIB_OP_BINARY(lt, <)\nMYLIB_OP_BINARY(ge, >=)\nMYLIB_OP_BINARY(le, <=)\n\nMYLIB_OP_UNARY(_not, !)\nMYLIB_OP_BINARY(_and, &&)\nMYLIB_OP_BINARY(_or, ||)\n\nMYLIB_OP_UNARY(bit_not, ~)\nMYLIB_OP_BINARY(bit_and, &)\nMYLIB_OP_BINARY(bit_or, |)\nMYLIB_OP_BINARY(bit_xor, ^)\n</code></pre>\n<p>These macros are defined and then only used once to generate the code for the required operators. You are then free to undefine them to avoid pollution. Be careful to use a prefix in the name of the macros to avoid collisions. I have assumed here you are making a library called <code>mylib</code>.</p>\n<p>Macros are needed because each expands to around 20 lines of code (which is the minimal possible, despite abstractions), and I wouldn't like to copy this code 20 times or more. And if you think that <code>operator==</code> is an overkill, someone else will not.</p>\n<p>Now here is how <code>MYLIB_OP_BINARY</code> is defined (<code>MYLIB_OP_UNARY</code> is similar):</p>\n<pre><code>#define MYLIB_OP_BINARY(NAME, OP) \\\n \\\nnamespace operators { \\\nstruct NAME \\\n{ \\\n template <typename A, typename B> \\\n constexpr auto \\\n operator()(A&& a, B&& b) const \\\n -> decltype(std::forward<A>(a) OP std::forward<B>(b)) \\\n { return std::forward<A>(a) OP std::forward<B>(b); } \\\n}; \\\n} \\\n \\\ntemplate <typename A, typename B> \\\ntypename container_result<A, B>::type \\\noperator OP(const A& a, const B& b) \\\n{ \\\n return apply<operators::NAME>()(a, b); \\\n} \\\n</code></pre>\n<p>First, inside a separate namespace <code>operators</code> we are capturing the meaning of each C++ operator into a function object. This is similar to <code>std::plus</code> etc. but</p>\n<ul>\n<li>applies to any C++ operator</li>\n<li>is non-template, allowing easier use</li>\n</ul>\n<p>Then, for each operator, we define the corresponding "vectorized" operator for containers <em>and</em> scalars by just calling <code>apply</code>.</p>\n<p>Note that this latter definition, although taking arbitrary types of input arguments, does not interfere with other potential overloads, because the result type</p>\n<pre><code>typename container_result<A, B>::type\n</code></pre>\n<p>is only valid if <code>A,B</code> are instances of class templates defining their own <code>value_type</code> (so, usually containers). Otherwise, other overloads are considered only. So we don't need <code>enable_if</code> in this; <code>container_result</code> is enough for substitution failure.</p>\n<p>I hope you can now see that this macro is not possible to simplify further by existing language abstraction mechanisms. It would only be convenient to eliminate it if we could make it an one-liner, but then we'd loose all the nice generalizations exposed above.</p>\n<p>In my work, I separately capture <em>all</em> C++ operators <a href=\"https://github.com/iavr/ivl2/blob/master/include/ivl/root/core/type/fun/op.hpp\" rel=\"noreferrer\">here</a> and then define the "vectorized" counterparts <a href=\"https://github.com/iavr/ivl2/blob/master/include/ivl/root/core/fun/op/op.hpp\" rel=\"noreferrer\">here</a>.</p>\n<h2>Namespaces</h2>\n<p>Regardless of any other precautions, we are defining a number of very generic operators that extend the language in a way that may not be desirable in combination with (or compatible to) other code or other libraries. As an extra measure of precaution, define everything in a separate namespace. Check the live example for details. Again I have assumed you are building a library called <code>mylib</code>.</p>\n<h2>Efficiency (accumulation)</h2>\n<blockquote>\n<p>(1) can the <code>squared_distance</code> calculation be made more efficient?</p>\n</blockquote>\n<p>I don't want to elaborate too much here. A simple change would be fine:</p>\n<pre><code>return std::inner_product(a.begin(), a.end(), b.begin(), T(0),\n std::plus<T>(), [](T x,T y){T z = y-x; return z*z;});\n</code></pre>\n<p>We just introduce a temporary to avoid doing the subtraction twice. But I would suggest to measure because most probably the optimizer is doing this anyway for us.</p>\n<h2>Efficiency (element-wise operations)</h2>\n<p>I have left the issue of storing the result inside <code>apply</code>. Using <code>std::vector::reserve()</code> along with <code>std::back_inserter</code> means that</p>\n<ul>\n<li>We are limited to containers having <code>reserve()</code>, hence most probably to <code>std::vector</code>.</li>\n<li>We resize the container at each iteration. Even if we are not reallocating, we need to at least update the vector size.</li>\n</ul>\n<p>There are numerous options here, but in most cases one would have go to a lower level of implementation, or use another kind of container.</p>\n<p>For instance, if we could <a href=\"https://stackoverflow.com/questions/21585675/building-a-vector-to-allow-uninitialized-storage\">build a vector to allow uninitialized storage</a>, we could give the appropriate size without initializing elements. <code>transform</code> would then only <em>initialize</em> each element instead of <em>copying</em> a new value. This <em>can</em> be implemented with a specialized allocator to be used with <code>std::vector</code>.</p>\n<p>But then, why should <code>apply</code> decide what is the returned container type and how it should be initialized, resized, or copied? To me, the ultimate solution is to <a href=\"http://en.wikipedia.org/wiki/Lazy_evalution\" rel=\"noreferrer\">delay</a> evaluation of the result by using <a href=\"http://en.wikipedia.org/wiki/Expression_templates\" rel=\"noreferrer\">expression templates</a>. Then, expression <code>a - b</code> only returns a temporary object holding references to <code>a, b</code> and knowing the function type (like std::minus), while <code>c = a - b</code> does the actual work, initializing according to <code>c</code>'s type.</p>\n<p>As I said, I am working on this topic. <a href=\"https://github.com/iavr/ivl2/blob/master/include/ivl/root/core/array/view/apply.hpp\" rel=\"noreferrer\">Here</a> is the <em>sequence view</em> (object behaving like a container) corresponding to <code>apply</code> as given above, and <a href=\"https://github.com/iavr/ivl2/blob/master/include/ivl/root/core/array/iter/apply.hpp\" rel=\"noreferrer\">here</a> is its iterator. I am afraid this code will be probably unreadable because it's using much more entities defined elsewhere, and because it has taken many more steps of abstraction and generalization than shown here.\nLibraries like <a href=\"http://www.boost.org/doc/libs/1_55_0/libs/multi_array/doc/user.html\" rel=\"noreferrer\">boost::multi_array</a>, <a href=\"http://www.boost.org/doc/libs/1_55_0b1/libs/numeric/ublas/doc/index.htm\" rel=\"noreferrer\">boost::ublas</a> or <a href=\"http://eigen.tuxfamily.org/\" rel=\"noreferrer\">Eigen</a> are similar in this respect (actually, in using expression templates <em>and</em> in being unreadable internally)!</p>\n<p>I am sorry I am not giving any more concrete solution here, but I feel this is a huge topic, and if you start in this direction, you may soon realize you should be using an existing library in the first place.</p>\n<p>Anyhow, the good news are that you now have a single generic implementation of all operations so whenever you decide to invest on a more efficient implementation, you'll only have to define it once.</p>\n<h2>Other types</h2>\n<blockquote>\n<p>(3) I've tested with int, float, double and std::complex. What else might be useful?</p>\n<p>(4) is there any point to accommodating unsigned types?</p>\n</blockquote>\n<p>You won't need anything for unsigned types. The definitions given here will work fine and conversions will be made according to language rules by <code>std::common_type</code>, even for <code>std::complex</code>.</p>\n<p>Other types? <strong>Anything!</strong> For instance, why not other containers? Consider:</p>\n<pre><code>std::vector<std::vector<double> >\n u{{0, 0, 0}, {3, 4, 5}},\n v{{-1, -2, -3}, {5, 6, 7}};\nsay(u);\nsay(v);\nsay(-u);\nsay(+v);\nsay(u+v);\nsay(u-v);\nsay(v-u);\n</code></pre>\n<p>This works automatically now, for any level of nested containers, thanks to recursion. It wouldn't work with your code.</p>\n<p>One "glitch" is that separation between vectors and scalars is done by checking for member type <code>::value_type</code> as I said above. Unfortunately this is not quite appropriate because e.g. <code>std::complex</code> has this type but is not a container. I have a simple workaround in my live example by also requiring <code>::size_type</code>, but all such issues will be resolved by <a href=\"http://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29\" rel=\"noreferrer\">C++ concepts</a>.</p>\n<p>One comes soon to realize that adding a scalar to a vector would also be convenient. This results in four combinations of operations. Then how about an n-ary function? This would result in <code>2^n</code> combinations. I have a generic solution and <a href=\"https://github.com/iavr/ivl2/blob/master/test/array/vec_op.cpp\" rel=\"noreferrer\">here</a> is a test sample of my code showing just a few of the things than can be done. But this goes way too far.</p>\n<p>Another issue is that we have mostly ignored <em>move semantics</em> here. If we were to write this code in the most generic way, we should use rvalue references and forwarding everywhere. This is not so hard to do, but I have skipped it and used <code>const&</code> parameters almost everywhere.</p>\n<h2>Type promotion</h2>\n<blockquote>\n<p>(5) should I do anything about possible numeric overflow or underflow?</p>\n</blockquote>\n<p>For element-wise operations, nothing.</p>\n<p>For accumulation operations like <code>squared_distance</code>, maybe yes. For instance, adding up <code>1000</code> values of type <code>int</code> might only fit into a <code>long</code>, and <code>1000</code> values of type <code>float</code> might only fit into a <code>double</code>. It would be convenient to have type promotions automatically done somewhere, but to decide exactly when a promotion is needed requires run time information, otherwise we may be promoting "just in case", which is contrary to the C++ principle</p>\n<blockquote>\n<p><em>don't pay for what you don't use</em></p>\n</blockquote>\n<p>I believe the user should be aware of such issues. Lazy evaluation may come to the rescue again: in an expression <code>c = f(a, b)</code>, if <code>f(a, b)</code> is just a temporary intermediate object, then the actual work is only done when the type of <code>c</code> is known. This is exactly why <code>std::accumulate</code> and <code>std::inner_product</code> take another argument for the output. I also have a generic solution here, but again this goes too far.</p>\n<p>For now, I would suggest to just use the right types for the input vectors (e.g. <code>double</code>) when an operation is expected to overflow the result. This is maybe too much a burden to the user, but we don't live in a perfect world.</p>\n<h2>UPDATE: Corrections</h2>\n<p>I now realize that using <code>common_type</code> is not the right approach for finding the return type. It works for operators like <code>+,*</code> but not e.g. for boolean operators where the result is always <code>bool</code>. Moreover, <code>common_type</code> won't work with nested containers with different value types; it's simply not defined for such cases.</p>\n<p>It's not too hard to make the return type depend on the <em>operation</em> <code>F</code> as well, using <code>decltype</code> as in the "capturing" function objects, or <code>std::result_of</code>. However, a further complication when considering nested containers with different value types is that substitution of the value type is not enough. For instance, <code>std::vector<T></code> is actually</p>\n<pre><code>std::vector<T, std::allocator<T> >\n</code></pre>\n<p>so one has to substitute <code>T</code> for a new type, say <code>S</code>, in <em>both</em> the container and the allocator, to yield</p>\n<pre><code>std::vector<S, std::allocator<S> >\n</code></pre>\n<p>Assuming that containers follow this structure (in particular, they all have allocators), I have updated the previous code accordingly, but I am only giving here a link to a new <a href=\"http://coliru.stacked-crooked.com/a/b8622f02529699fb\" rel=\"noreferrer\">live example</a> to avoid making this answer even longer. For something more general without too much boilerplate, the containers should provide for such type substitution <em>themselves</em>; but to my knowledge, unfortunately this is not the case in STL.</p>\n<p>We can now apply binary operators between containers of as diverse value types as</p>\n<pre><code>std::vector<std::vector<double> > u{{-2, 0, 0}, {3, 4, 5}};\nstd::vector<std::vector<int> > v{{-1, 0, -3}, {5, 6, 5}};\n</code></pre>\n<p>as shown in the live example, along with some interesting cases like <code>u < v</code>.</p>\n<p>Ok, that's it, I hope I will write no more!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T14:35:27.887",
"Id": "46461",
"ParentId": "46410",
"Score": "6"
}
},
{
"body": "<h1>Results</h1>\n\n<p>Based on the feedback received, (thank you all for taking the time!) I wrote three different versions using <code>std::vector</code>, <code>std::array</code> and <code>std::valarray</code>. I then modified my test code to create a vector of one million randomly created 3D points (using <code>double</code>) and then called the <code>squared_distance</code> template function to populate a second results array with the squared distance between a fixed random point and each of the million other points. I then used the <code>time</code> command under Linux to record the User time taken for each of the three variants. Ten trials were done for each and the summary of the timing is shown below.</p>\n\n<pre><code> valarray array vector\naverage 0.976 0.904 1.730\nvariance 0.000 0.002 0.020\n</code></pre>\n\n<p>As is clear from the results, both <code>std::valarray</code> and <code>std::array</code> are almost two times faster than my original <code>std::vector</code> version with <code>std::array</code> being fastest. That version of the code is shown below:</p>\n\n<pre><code>template <typename T, size_t N>\nT squared_distance(const std::array<T,N>& a, const std::array<T,N>& b)\n{\n T accum(0);\n for (int i=0; i<N; ++i)\n {\n T delta = b[i]-a[i];\n accum += delta*delta;\n }\n return accum;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-05T10:29:02.050",
"Id": "88855",
"ParentId": "46410",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46417",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T20:21:36.300",
"Id": "46410",
"Score": "12",
"Tags": [
"c++",
"c++11",
"template-meta-programming"
],
"Title": "n-dimensional Euclidean space calculation templates"
} | 46410 |
<p>I am generating a content bar with jQuery, that can be inserted into any webpage. It is a <code><ul></code> with two smaller lists within it. Those two minor lists have a header and a text box. The whole thing can be resized vertically, and each block within can be resized horizontally.</p>
<p>Is there a way to simplify the HTML and CSS?</p>
<p>Here's a <a href="http://jsfiddle.net/easilyBaffled/E5WnR/" rel="nofollow noreferrer">jsFiddle</a> incase you want to play with it a bit.</p>
<p>I know I could probably swap out the list stuff for spans and divs, but I don't think that would simplify things enough to matter.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
function generate_element_group() {
var list_elem = $("<li />");
var container = $("<ul />", { class: "elem_container" });
container.resizable({ handles: "e" });
var header = $("<li />", { class: "header_t" });
var content_container = $("<li />", { class: "content_container_t" });
var content = $("<textarea />", { class: "content_t" });
content_container.append(content);
container.append(header);
container.append(content_container);
list_elem.append(container);
return list_elem;
}
var resize_container = $("<span />", {class: "resize_container"});
var container = $("<ul />", { class: "container_t" });
container.resizable({ handles: "n" });
container.append(generate_element_group());
container.append(generate_element_group());
resize_container.append(container);
$('body').append(resize_container);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.resize_container {
position : fixed !important;
top : 65% !important;
left : 0px !important;
}
.container_t {
position : relative;
display : inline-block;
bottom : 0px;
left : 0px;
height : 150px;
margin : 0;
padding : 0;
background-color : red;
list-style : none;
}
.container_t > li {
display : inline-block;
height : 100%;
}
.elem_container {
height : 100%;
width : 350px;
padding : 0;
list-style : none;
}
.header_t {
position : absolute;
box-sizing : border-box;
height : 35px;
width : 100%;
padding : 5px;
background-color : blue;
}
.content_container_t {
position : absolute;
top : 35px;
bottom : 0;
box-sizing : border-box;
width : 100%;
padding : 5px;
background-color : green;
}
.content_t {
position : absolute;
top : 5px;
bottom : 5px;
left : 5px;
width : 90%;
}
.ui-resizable-n {
cursor : n-resize;
border-top : 5px solid purple;
}
.ui-resizable-e {
right : 0;
cursor : e-resize;
border-right : 5px solid purple;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="resize_container">
<ul class="container_t ui-resizable">
<div class="ui-resizable-handle ui-resizable-n" style="z-index: 90; display: block;">
</div>
<li>
<ul class="elem_container ui-resizable" style="width: 398px;">
<div class="ui-resizable-handle ui-resizable-e" style="z-index: 90; display: block;">
</div>
<li class="header_t">
</li>
<li class="content_container_t"><textarea class="content_t">
</textarea>
</li>
</ul>
</li>
<li>
<ul class="elem_container ui-resizable" style="width: 349px;">
<div class="ui-resizable-handle ui-resizable-e" style="z-index: 90; display: block;">
</div>
<li class="header_t">
</li>
<li class="content_container_t"><textarea class="content_t">
</textarea>
</li>
</ul>
</li>
</ul>
</span></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>Well, lists generally speaking should be used for lists, so <code><div></code>'s and <code><spans></code>s would probably be more semantically accurate, but hard to say what the purpose of this is. </p>\n\n<p>Additionally, if you're using headings, it would probably be worth it to change the <code><li class=\"header_t\"></code> to an <code><h2></code> tag.</p>\n\n<p>Not sure what your support levels are for this, but I'd do something along these lines: <a href=\"http://jsfiddle.net/darcher/smQ7D/1/\" rel=\"nofollow\">http://jsfiddle.net/darcher/smQ7D/1/</a></p>\n\n<p>Replace <code><section></code>'s with <code><div></code>'s if you aren't using html5 elements.</p>\n\n<p>*I didn't do much in term of cleaning up the css, so you may want to check to make sure there aren't any unused properties. If you ever come back to see this I'll refine the css a bit.</p>\n\n<p>*I added aria roles to add more value to devices that support it. I'd also look into State aria roles that you can dynamically adjust as the user interacts with items. e.g. `aria-grabbed', etc. That doesn't really go along with 'simplifying html' so If not, just stick with what's in the fiddle.</p>\n\n<p>HTML:</p>\n\n<pre><code><div class=\"resize_container\">\n <div class=\"container_t ui-resizable\">\n <div class=\"ui-resizable-handle ui-resizable-n\" aria-label=\"resize\"></div>\n\n <section class=\"elem_container ui-resizable\">\n <div class=\"ui-resizable-handle ui-resizable-e\" aria-label=\"resize\"></div>\n <h2 role=\"heading\" aria-label=\"heading1\" class=\"header_t\"></h2>\n <textarea class=\"content_t\" role=\"textbox\" aria-labelledby=\"heading1\"></textarea>\n </section>\n\n <section class=\"elem_container ui-resizable\">\n <div class=\"ui-resizable-handle ui-resizable-e\" aria-label=\"resize\"></div>\n <h2 role=\"heading\" aria-label=\"heading2\" class=\"header_t\"></h2>\n <textarea class=\"content_t\" role=\"textbox\" aria-labelledby=\"heading2\"></textarea>\n </section>\n\n </div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.resize_container {\n position: fixed !important;\n top: 65% !important;\n left: 0px !important;\n *zoom:1\n}\n\n .resize_container:after,\n .resize_container:before {\n content:' ';\n display:table\n }\n .resize_container:after {clear:both}\n\n.container_t{\n height: 100px;\n background-color: green;\n padding: 0;\n margin: 0;\n}\n\n.elem_container {\n padding: 0;\n width: 250px;\n float:left;\n display:inline-block;\n height: 100%;\n}\n\n.header_t {\n height: 35px;\n margin:0;\n background-color: blue;\n padding: 5px;\n box-sizing: border-box;\n}\n\n.content_t {\n width: 90%;\n margin:2%;\nheight: 50px;\nborder: 1px solid #cccccc;\npadding: 5px;\n}\n\n.ui-resizable-n {\n cursor: n-resize;\n border-top: 5px solid purple;\n}\n\n.ui-resizable-e {\n cursor: e-resize;\n border-right: 5px solid purple;\n right: 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T08:57:08.200",
"Id": "47637",
"ParentId": "46411",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T21:48:38.407",
"Id": "46411",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"jquery-ui"
],
"Title": "Resizeable HTML"
} | 46411 |
<p>I have previously asked <a href="https://codereview.stackexchange.com/questions/42823/pong-game-written-in-c-and-using-sdl-2-0">here</a> for a review of my Pong game. Since then I have implemented most of the recommendations but I'm not sure I did so correctly, the result can be found on my <a href="https://github.com/chaficnajjar/pong" rel="nofollow noreferrer">github</a>.</p>
<p>Would it be possible to get another review? Below is the whole source code of the game:</p>
<p><strong>main.cpp</strong></p>
<pre><code>/*
* Pong game
* Author: Chafic Najjar <chafic.najjar@gmail.com>
* Note: Origin of the coordinate system is the upper left corner of the screen
*/
#include "pong.hpp"
int main(int argc, char *argv[]) {
Pong pong(argc, argv);
pong.execute();
return 0;
}
</code></pre>
<p><strong>pong.hpp</strong></p>
<pre><code>/*
* Pong class declaration
*/
#ifndef PONG_HPP
#define PONG_HPP
#include <SDL2/SDL.h> // SDL library
#include <SDL2/SDL_ttf.h> // SDL font library
#include <SDL2/SDL_mixer.h> // SDL sound library
#include <iostream>
class Ball;
class Paddle;
class Pong {
public:
Pong(int argc, char *argv[]);
/* Screen resolution */
static const int SCREEN_WIDTH;
static const int SCREEN_HEIGHT;
/* Window and renderer */
SDL_Window* window; // holds window properties
SDL_Renderer* renderer; // holds rendering surface properties
/* Game objects */
Ball *ball;
Paddle *left_paddle;
Paddle *right_paddle;
/* Sounds */
Mix_Chunk *paddle_sound; // holds sound produced after ball collides with paddle
Mix_Chunk *wall_sound; // holds sound produced after ball collides with wall
Mix_Chunk *score_sound; // holds sound produced when updating score
/* Controllers */
enum Controllers { mouse, keyboard, joystick };
Controllers controller;
SDL_Joystick *gamepad; // holds joystick information
int gamepad_direction; // gamepad direction
int mouse_x, mouse_y; // mouse coordinates
/* Fonts */
std::string fonts[2]; // font names
SDL_Color dark_font; // dark font color
SDL_Color light_font; // light font color
SDL_Texture* font_image_left_score; // holds text indicating player 1 score (left)
SDL_Texture* font_image_right_score; // holds text indicating palyer 2 score (right)
SDL_Texture* font_image_winner; // holds text indicating winner
SDL_Texture* font_image_restart; // holds text suggesting to restart the game
SDL_Texture* font_image_launch1; // holds first part of text suggesting to launch the ball
SDL_Texture* font_image_launch2; // holds second part of text suggesting to launch the ball
/* Scores */
int left_score;
int right_score;
bool left_score_changed; // indicates when rendering new score is necessary
bool right_score_changed; // indicates when rendering new score is necessary
/* Game states */
bool exit; // true when player wants to exit game
/* Main functions */
void execute();
void input();
void update();
void render();
void clean_up();
};
#endif
</code></pre>
<p><strong>pong.cpp</strong></p>
<pre><code>/*
* Pong class definition
*/
#include "pong.hpp"
#include "ball.hpp"
#include "paddle.hpp"
#include "utilities.hpp"
/* Screen resolution */
const int Pong::SCREEN_WIDTH = 640;
const int Pong::SCREEN_HEIGHT = 480;
Pong::Pong(int argc, char *argv[]) {
/* Initilize SDL */
SDL_Init(SDL_INIT_EVERYTHING);
SDL_ShowCursor(0); // don't show cursor
/* Window and renderer */
window = SDL_CreateWindow("Pong",
SDL_WINDOWPOS_UNDEFINED, // centered window
SDL_WINDOWPOS_UNDEFINED, // centered window
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
/* Game objects */
ball = new Ball(SCREEN_WIDTH/2-ball->LENGTH/2, SCREEN_HEIGHT/2);
left_paddle = new Paddle(40, SCREEN_HEIGHT/2-30);
right_paddle = new Paddle(SCREEN_WIDTH-(40+Paddle::WIDTH), SCREEN_HEIGHT/2-30);
/* Sounds */
Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024); // initialize SDL_mixer
paddle_sound = Mix_LoadWAV("resources/sounds/paddle_hit.wav"); // load paddle sound
wall_sound = Mix_LoadWAV("resources/sounds/wall_hit.wav"); // load wall sound
score_sound = Mix_LoadWAV("resources/sounds/score_update.wav"); // load score sound
/* Controllers */
if (argc == 2) {
if ( strcmp(argv[1], "keyboard") == 0 )
controller = keyboard;
else if ( strcmp(argv[1], "joystick") == 0 )
controller = joystick;
else
controller = mouse;
} else
controller = mouse; // default controller
if (controller == joystick) {
printf("%i joysticks were found.\n\n", SDL_NumJoysticks() );
printf("The names of the joysticks are:\n");
gamepad = SDL_JoystickOpen(0); // give control to the first joystick
for(int i = 0; i < SDL_NumJoysticks(); i++)
std::cout << "\t" << SDL_JoystickName(gamepad) << std::endl;
SDL_JoystickEventState(SDL_ENABLE); // initialize joystick controller
gamepad_direction = 0;
}
/* Fonts */
TTF_Init(); // initialize font
dark_font = {67, 68, 69}; // dark grey
light_font = {187, 191, 194}; // light grey
fonts[0] = "resources/fonts/Lato-Reg.TTF";
fonts[1] = "resources/fonts/FFFFORWA.TTF";
font_image_launch1 = renderText("Press SPA", fonts[0], light_font, 18, renderer);
font_image_launch2 = renderText("CE to start", fonts[0], dark_font, 18, renderer);
/* Scores */
left_score = 0;
right_score = 0;
left_score_changed = true; // indicates when rendering new score is necessary
right_score_changed = true; // indicates when rendering new score is necessary
/* Game states */
exit = false;
}
void Pong::execute() {
while(!exit) {
input();
update();
render();
}
clean_up();
}
void Pong::input() {
//=== Handling events ===//
SDL_Event event;
while(SDL_PollEvent(&event)) {
// Track mouse movement
if (event.type == SDL_MOUSEMOTION)
SDL_GetMouseState(&mouse_x, &mouse_y);
// Clicking 'x' or pressing F4
if (event.type == SDL_QUIT)
exit = true;
// Joystick direction controller moved
if (event.type == SDL_JOYAXISMOTION) {
// 32767
// Up or down
if (event.jaxis.axis == 1)
gamepad_direction = event.jaxis.value/5461;
}
// Joystick action button pressed
if (event.type == SDL_JOYBUTTONDOWN)
if (ball->status == ball->READY)
ball->status = ball->LAUNCH;
// Pressing a key
if (event.type == SDL_KEYDOWN)
switch(event.key.keysym.sym) {
// Pressing ESC exits from the game
case SDLK_ESCAPE:
exit = true;
break;
// Pressing space will launch the ball if it isn't already launched
case SDLK_SPACE:
if (ball->status == ball->READY)
ball->status = ball->LAUNCH;
break;
// Pressing F11 to toggle fullscreen
case SDLK_F11:
int flags = SDL_GetWindowFlags(window);
if(flags & SDL_WINDOW_FULLSCREEN)
SDL_SetWindowFullscreen(window, 0);
else
SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
break;
}
}
}
// Update game values
void Pong::update() {
//=======================//
//=== Paddle movement ===//
// Right paddle follows the player's mouse on the y-axis
if (controller == mouse)
right_paddle->set_y(mouse_y);
// Right paddle follows the player's gamepad
else if (controller == joystick)
right_paddle->add_to_y(gamepad_direction);
// AI paddle movement
left_paddle->AI(ball);
//===================//
//=== Launch ball ===//
if (ball->status == ball->READY)
return;
else if (ball->status == ball->LAUNCH) {
ball->launch_ball(left_paddle);
ball->predicted_y = left_paddle->predict(ball);
}
//=========================//
//=== Update ball speed ===//
ball->update_speed();
//=================//
//=== Collision ===//
if (ball->collides_with(left_paddle)) {
ball->bounces_off(left_paddle);
Mix_PlayChannel(-1, paddle_sound, 0); // play collision sound
}
else if (ball->collides_with(right_paddle)) {
ball->bounces_off(right_paddle);
ball->predicted_y = left_paddle->predict(ball); // predict ball position on the y-axis
Mix_PlayChannel(-1, paddle_sound, 0);
}
// Upper and bottom walls collision
if (ball->wall_collision()) {
ball->dy *= -1; // reverse ball direction on y-axis
Mix_PlayChannel(-1, wall_sound, 0); // play collision sound
}
//===============================//
//=== Update ball coordinates ===//
ball->x += ball->dx;
ball->y += ball->dy;
//=====================//
//=== Ball goes out ===//
if (ball->x > SCREEN_WIDTH || ball->x < 0) {
// Change score
if (ball->x > SCREEN_WIDTH) {
left_score++;
left_score_changed = true;
} else {
right_score++;
right_score_changed = true;
}
Mix_PlayChannel(-1, score_sound, 0);
ball->reset();
}
}
// Render objects on screen
void Pong::render() {
// Clear screen (background color)
SDL_SetRenderDrawColor( renderer, 67, 68, 69, 255 ); // dark grey
SDL_RenderClear(renderer);
// Color left background with light grey
SDL_Rect left_background = { SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT };
SDL_SetRenderDrawColor( renderer, 187, 191, 194, 255 );
SDL_RenderFillRect( renderer, &left_background );
// Paddle color
SDL_SetRenderDrawColor( renderer, 212, 120, 102, 255 );
// Render filled paddle
SDL_Rect paddle1 = { left_paddle->get_x(), left_paddle->get_y(), Paddle::WIDTH, Paddle::HEIGHT };
SDL_RenderFillRect( renderer, &paddle1 );
// Render filled paddle
SDL_Rect paddle2 = { right_paddle->get_x(), right_paddle->get_y(), Paddle::WIDTH, Paddle::HEIGHT };
SDL_RenderFillRect( renderer, &paddle2 );
// Render ball
SDL_Rect pong_ball = { ball->x, ball->y, ball->LENGTH, ball->LENGTH };
SDL_RenderFillRect(renderer, &pong_ball);
// Render scores
if (left_score_changed) {
font_image_left_score = renderText(std::to_string(left_score), "resources/fonts/Lato-Reg.TTF", light_font, 24, renderer);
left_score_changed = false;
if (left_score == 5) {
font_image_winner = renderText("Player 1 won!", fonts[0], light_font, 24, renderer);
font_image_restart = renderText("Press SPACE to restart", fonts[0], light_font, 18, renderer);
}
}
renderTexture(font_image_left_score, renderer, SCREEN_WIDTH * 4 / 10, SCREEN_HEIGHT / 12);
int score_font_size = 24;
if (right_score_changed) {
font_image_right_score = renderText(std::to_string(right_score), "resources/fonts/Lato-Reg.TTF", dark_font, score_font_size, renderer);
right_score_changed = false;
if (right_score == 5) {
font_image_winner = renderText("Player 2 won!", fonts[0], dark_font, 24, renderer);
font_image_restart = renderText("Press SPACE to restart", fonts[0], dark_font, 18, renderer);
}
}
renderTexture(font_image_right_score, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT/ 12);
// Render text indicating the winner
if (left_score == 5) {
renderTexture(font_image_winner, renderer, SCREEN_WIDTH * 1 / 10 + 3, SCREEN_HEIGHT / 4); // align with score
renderTexture(font_image_restart, renderer, SCREEN_WIDTH * 1 / 10 + 3, SCREEN_HEIGHT / 3);
if (ball->status == ball->LAUNCHED) {
left_score = 0;
right_score = 0;
left_score_changed = true;
right_score_changed = true;
}
} else if (right_score == 5) {
renderTexture(font_image_winner, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT / 4); // align with score
renderTexture(font_image_restart, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT / 3);
if (ball->status == ball->LAUNCHED) {
left_score = 0;
right_score = 0;
left_score_changed = true;
right_score_changed = true;
}
}
// Draw "Press SPACE to start"
else if (!ball->status == ball->LAUNCHED) {
renderTexture(font_image_launch1, renderer, SCREEN_WIDTH / 2 - 80, SCREEN_HEIGHT - 25);
renderTexture(font_image_launch2, renderer, SCREEN_WIDTH / 2 + 1, SCREEN_HEIGHT - 25);
}
// Swap buffers
SDL_RenderPresent(renderer);
}
//=== Release resources ===//
void Pong::clean_up() {
// Destroy textures
SDL_DestroyTexture(font_image_left_score);
SDL_DestroyTexture(font_image_right_score);
// Free the sound effects
Mix_FreeChunk(paddle_sound);
Mix_FreeChunk(wall_sound);
Mix_FreeChunk(score_sound);
// Quit SDL_mixer
Mix_CloseAudio();
// Close joystick
if (controller == joystick)
SDL_JoystickClose(gamepad);
// Destroy renderer and window
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
// Shuts down SDL
SDL_Quit();
}
</code></pre>
<p><strong>paddle.hpp</strong></p>
<pre><code>/*
* Paddle class declaration
*/
#ifndef PADDLE_HPP
#define PADDLE_HPP
class Ball;
class Paddle {
private:
// Paddle position
int x;
int y;
public:
Paddle(int x, int y);
public:
// Paddle dimensions
static const int HEIGHT;
static const int WIDTH;
// Functions
int get_x();
int get_y();
void set_y(int new_y);
void add_to_y(int new_y);
int predict(Ball *ball);
void AI(Ball *ball);
};
#endif
</code></pre>
<p><strong>paddle.cpp</strong></p>
<pre><code>/*
* Paddle class definitions
*/
#include "paddle.hpp"
#include "pong.hpp"
#include "ball.hpp"
const int Paddle::HEIGHT = 60;
const int Paddle::WIDTH = 10;
Paddle::Paddle(int new_x, int new_y){
x = new_x;
y = new_y;
}
int Paddle::get_x() {
return x;
}
int Paddle::get_y() {
return y;
}
void Paddle::set_y(int new_y) {
y = new_y;
// Paddle shouldn't be allowed to go above or below the screen
if (y < 0)
y = 0;
else if (y + HEIGHT > Pong::SCREEN_HEIGHT)
y = Pong::SCREEN_HEIGHT - HEIGHT;
}
void Paddle::add_to_y(int new_y) {
y += new_y;
// Paddle shouldn't be allowed to go above or below the screen
if (y < 0)
y = 0;
else if (y + HEIGHT > Pong::SCREEN_HEIGHT)
y = Pong::SCREEN_HEIGHT - HEIGHT;
}
// Imprecise prediction of ball position on the y-axis
int Paddle::predict(Ball *ball) {
// Find slope
float slope = (float)(ball->y - ball->y+ball->dy)/(ball->x - ball->x+ball->dx);
// Distance between ball and paddle
int paddle_distance = ball->x - x;
// Prediction without taking into consideration upper and bottom wall collisions
int predicted_y = abs(slope * -(paddle_distance) + ball->y);
// Calculate number of reflexions
int number_of_reflexions = predicted_y / Pong::SCREEN_HEIGHT;
// Predictions taking into consideration upper and bottom wall collisions
if (number_of_reflexions % 2 == 0) // Even number of reflexions
predicted_y = predicted_y % Pong::SCREEN_HEIGHT;
else // Odd number of reflexsion
predicted_y = Pong::SCREEN_HEIGHT - (predicted_y % Pong::SCREEN_HEIGHT);
return predicted_y;
}
// Basic AI movement
void Paddle::AI(Ball *ball) {
// Ball on the left 3/5th side of the screen and going left
if (ball->x < Pong::SCREEN_WIDTH*3/5 && ball->dx < 0) {
// Follow the ball
if (y + (HEIGHT - ball->LENGTH)/2 < ball->predicted_y-2)
add_to_y(ball->speed/8 * 5);
else if (y + (HEIGHT - ball->LENGTH)/2 > ball->predicted_y+2)
add_to_y( -(ball->speed/8 * 5) );
}
// Ball is anywhere on the screen but going right
else if (ball->dx >= 0) {
// Left paddle slowly moves to the center
if (y + HEIGHT / 2 < Pong::SCREEN_HEIGHT/2)
add_to_y(2);
else if (y + HEIGHT / 2 > Pong::SCREEN_HEIGHT/2)
add_to_y(-2);
}
}
</code></pre>
<p><strong>ball.hpp</strong></p>
<pre><code>/*
* Ball class declaration
*/
#ifndef BALL_HPP
#define BALL_HPP
class Paddle;
class Ball {
public:
Ball(int x, int y);
// Ball status
enum Status {READY, LAUNCH, LAUNCHED};
Status status;
// Ball dimensions
static const int LENGTH;
// Ball position
int x;
int y;
// Ball movement
int dx; // movement in pixels over the x-axis for the next frame (speed on the x-axis)
int dy; // movement in pixels over the y-axis for the next frame (speed on the y-axis)
bool bounce; // true when next frame renders ball after collision impact (ball has bounced)
int speed; // ball speed = √(dx²+dy²)
float angle; // angle after collision with paddle
int hits; // counts the number of hits of the ball with the right paddle, increase speed after 3 hits
int predicted_y; // predicted ball position on y-axis after right paddle collision (used for paddle AI)
void launch_ball(Paddle *ai_paddle);
void update_speed();
bool wall_collision();
bool collides_with(Paddle *paddle);
void bounces_off(Paddle *paddle);
void reset();
};
#endif
</code></pre>
<p><strong>ball.cpp</strong></p>
<pre><code>/*
* Ball class definitions
*/
#include "ball.hpp"
#include "pong.hpp"
#include "paddle.hpp"
#include <random>
std::random_device rd;
std::mt19937 gen(rd());
// Ball dimensions
const int Ball::LENGTH = 10;
Ball::Ball(int x, int y) {
// Ball status
status = READY;
// Ball position
this->x = x;
this->y = y;
// Ball movement
dx = 0;
dy = 0;
bounce = false;
speed = 8;
angle = 0.0f;
hits = 0;
predicted_y = 0;
}
void Ball::launch_ball(Paddle *ai_paddle) {
std::uniform_int_distribution<int> dir(0, 1);
int direction = 1+(-2)*(dir(gen)%2); // either 1 or -1
std::uniform_int_distribution<int> ang(-60, 60);
angle = ang(gen); // between -60 and 60
dx = direction*speed*cos(angle*M_PI/180.0f); // speed on the x-axis
dy = speed*sin(angle*M_PI/180.0f); // speed on the y-axis
status = LAUNCHED;
}
void Ball::bounces_off(Paddle *paddle) {
if (paddle == nullptr)
return;
hits++;
int sign;
if (paddle->get_x() < Pong::SCREEN_WIDTH/2)
sign = 1;
else
sign = -1;
int relative_y = (y - paddle->get_y() + LENGTH);
angle = (2.14f * relative_y - 75.0f);
dx = sign*speed*cos(angle*M_PI/180.0f); // convert angle to radian, find its cos() and multiply by the speed
dy = speed*sin(angle*M_PI/180.0f); // convert angle to radina, find its sin() and multiply by the speed
}
void Ball::update_speed() {
// Increment ball speed for every 6 hits
if (hits == 5) {
speed++;
hits = 0;
}
}
bool Ball::wall_collision() {
return (y + dy < 0) || (y + LENGTH + dy >= Pong::SCREEN_HEIGHT);
}
bool Ball::collides_with(Paddle *paddle) {
// left paddle
if (paddle->get_x() < Pong::SCREEN_WIDTH/2) {
// Check if collision with left paddle occurs in next frame
if ( x > paddle->get_x() + Paddle::WIDTH )
return false;
else if (x < paddle->get_x())
return false;
else if (!(y + LENGTH > paddle->get_y() && y <= paddle->get_y() + Paddle::HEIGHT))
return false;
else
return true;
}
// right paddle
else {
// Check if collision with right paddle occurs in next frame
if ( x + LENGTH < paddle->get_x() )
return false;
else if (x > paddle->get_x() + Paddle::WIDTH)
return false;
else if (!(y + LENGTH > paddle->get_y() && y <= paddle->get_y() + Paddle::HEIGHT))
return false;
else
return true;
}
}
// Reset ball to initial state
void Ball::reset() {
x = Pong::SCREEN_WIDTH/2 - LENGTH/2;
y = Pong::SCREEN_HEIGHT/2;
// Ball is fixed
dx = 0;
dy = 0;
status = READY;
// Speed and hit counter are reset to their initial positions
speed = 8;
hits = 0;
}
</code></pre>
<p><strong>utilities.hpp</strong></p>
<pre><code>/*
* Useful functions
*/
#ifndef UTILITIES_HPP
#define UTILITIES_HPP
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr) {
SDL_RenderCopy(ren, tex, clip, &dst);
}
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr) {
SDL_Rect dst;
dst.x = x;
dst.y = y;
if (clip != nullptr){
dst.w = clip->w;
dst.h = clip->h;
}
else
SDL_QueryTexture(tex, nullptr, nullptr, &dst.w, &dst.h);
renderTexture(tex, ren, dst, clip);
}
SDL_Texture* renderText(const std::string &message, const std::string &fontFile, SDL_Color color, int fontSize, SDL_Renderer *renderer) {
TTF_Font *font = TTF_OpenFont(fontFile.c_str(), fontSize);
SDL_Surface *surf = TTF_RenderText_Blended(font, message.c_str(), color);
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf);
SDL_FreeSurface(surf);
TTF_CloseFont(font);
return texture;
}
#endif
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-11T06:40:58.050",
"Id": "342076",
"Score": "0",
"body": "When running I show: error: 'abs' was not declared in this scope"
}
] | [
{
"body": "<ul>\n<li><p>You don't need <code>return 0</code> at the end of <code>main()</code>. Reaching that point already implies a successful termination, so the compiler will insert it for you.</p></li>\n<li><p>Prefer to avoid raw pointers and manual memory management whenever possible. Instead, utilize standard containers and C++11 smart pointers.</p>\n\n<p>With raw pointers as data members, you would have to maintain <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">The Rule of Three</a> (or <a href=\"https://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11\">The Rule of Five</a> in C++11) because the provided copy constructor and assignment operator will only copy the pointers (shallow copy), not the data they point to (deep copy).</p></li>\n<li><p>Utilize initializer lists for your classes:</p>\n\n<p><code>Ball</code>:</p>\n\n<pre><code>Ball::Ball(int x, int y)\n : status(READY)\n , x(x)\n , y(y)\n , bounce(false);\n , speed(8);\n , angle(0.0f);\n , hits(0); \n , predicted_y(0)\n{}\n</code></pre>\n\n<p><code>Paddle</code>:</p>\n\n<pre><code>Paddle::Paddle(int new_x, int new_y)\n : x(new_x)\n , y(new_y)\n{}\n</code></pre>\n\n<p>This will especially be helpful in case you ever need to initialize <code>const</code> members.</p></li>\n<li><p><code>Paddle</code>'s accessors should be <code>const</code> as they do not modify data members:</p>\n\n<pre><code>int Paddle::get_x() const {\n return x;\n}\n</code></pre>\n\n<p></p>\n\n<pre><code>int Paddle::get_y() const {\n return y;\n}\n</code></pre></li>\n<li><p>Your randomization initializations should be put into an anonymous namespace:</p>\n\n<pre><code>namespace {\n std::random_device rd;\n std::mt19937 gen(rd());\n}\n</code></pre>\n\n<p>This will prevent linker errors in case the same names are used in other files.</p></li>\n<li><p>This:</p>\n\n<pre><code>int sign;\nif (paddle->get_x() < Pong::SCREEN_WIDTH/2)\n sign = 1;\nelse\n sign = -1;\n</code></pre>\n\n<p>can become a single-line ternary statement:</p>\n\n<pre><code>int sign = (paddle->get_x() < Pong::SCREEN_WIDTH/2) ? 1 : -1;\n</code></pre></li>\n<li><p>You're using <code>sin()</code> and <code>cos()</code>, but you haven't included <code><cmath></code>. I assume your compiler is being lenient for some reason and is not raising errors. You should still include this, as well as prefixing the functions with <code>std::</code>.</p></li>\n<li><p>In <code>collides_with()</code>, I'd condense all the <code>if</code>/<code>else if</code> statements into one <code>if</code>, with each condition separated by a <code>||</code>. Only one of them has to be met to <code>return false</code>.</p>\n\n<p>You'll then have something in this form (separate <code>||</code> lines may be necessary):</p>\n\n<pre><code>if (condition1 || condition2 || condition3)\n return false;\nelse\n return true;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T07:47:17.060",
"Id": "81125",
"Score": "0",
"body": "“_Your randomization initializations should be put into an anonymous namespace_” — why is that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T07:58:06.810",
"Id": "81126",
"Score": "0",
"body": "@You: It was based on advice given to me [here](http://codereview.stackexchange.com/a/31714/22222). I just haven't provided those details in this answer. I'll do that soon."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T00:38:09.007",
"Id": "46416",
"ParentId": "46414",
"Score": "6"
}
},
{
"body": "<p>I just have a few additional comments.</p>\n\n<p>First: (My main one) please, for the sake of all the furry little animals, your mother, and anything that's lovable in the world, don't hard-code the screen-width and screen-height as 640x480. Write your code to detect the screen size at run-time and act accordingly.</p>\n\n<p>Second, I'd wrap the <code>M_PI/180.0f</code> in a constant, by strong preference inside a function:</p>\n\n<pre><code>template <class T>\ndeg2rad(double degrees) { \n T factor = static_cast<T>(M_PI/180.0);\n return degrees * factor;\n}\n</code></pre>\n\n<p>My other main suggestion would be to move more of the intelligence about the game out of <code>pong::update</code> and into the individual objects. For example, right now the code for handling a collision between the ball and a wall or paddle isn't handled by the ball or the wall or the paddle. IMO, it would be better if the ball and/or object it collided with handled the collision, rather than leaving it to \"outside\" code (though I'll openly admit that collisions between different types of objects is a problem can be difficult to keep completely object oriented).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:59:50.640",
"Id": "81528",
"Score": "0",
"body": "I'm not sure I understood your first point, can you give an example?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T01:44:01.280",
"Id": "46423",
"ParentId": "46414",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46416",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T23:45:17.873",
"Id": "46414",
"Score": "6",
"Tags": [
"c++",
"game",
"c++11",
"sdl"
],
"Title": "Pong game written in C++ and using SDL 2.0 (part 2)"
} | 46414 |
<p>This question is more-or-less code agnostic. Provided code analysis would be helpful though.</p>
<p>Background: I've never got along with logging too well - probably because I've never had a need to review the non-error level logs. I comply with logging practices on work projects, but I usually don't do any logging in personal projects.</p>
<p>Below is an exempt from the game server module. The class is a persistent connection with the client, and is responsible for receiving (responders) and sending (commands) information from and to the client. Please only analyze the logging.</p>
<pre><code>class CommandProtocol(AMP):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
self.uid = str(id(self))
self.factory.clients[self.uid] = self
logging.info("Client '%s' is connected.", self.uid)
#--------------------------------------------------------------------------
# responders
def queue_int(self, action, arg):
self.factory.requests.add_request(self.uid, (action, arg))
logging.debug(
"Client '%s' queued int '%s' with value '%d'.",
self.uid, action, arg)
return {}
commands.QueueInt.responder(queue_int)
def queue_str(self, action, arg):
self.factory.requests.add_request(self.uid, (action, arg))
logging.debug(
"Client '%s' queued str '%s' with value '%s'.",
self.uid, action, arg)
return {}
commands.QueueStr.responder(queue_str)
def queue_tuple_of_int(self, action, arg1, arg2):
self.factory.requests.add_request(self.uid, (action, (arg1, arg2)))
logging.debug(
"Client '%s' queued tuple of int '%s' with value '(%d, %d)'.",
self.uid, action, arg1, arg2)
return {}
commands.QueueTupleOfInt.responder(queue_tuple_of_int)
def queue_tuple_of_str(self, action, arg1, arg2):
self.factory.requests.add_request(self.uid, (action, (arg1, arg2)))
logging.debug(
"Client '%s' queued tuple of str '%s' with value '(%s, %s)'.",
self.uid, action, arg1, arg2)
return {}
commands.QueueTupleOfStr.responder(queue_tuple_of_str)
def query_equipment(self):
equipment = self.factory.game.get_equipment(self.uid)
amp_equipment = []
for k, v in equipment.items():
v = 'None' if v is None else v.get_name()
amp_equipment.append({'slot': k, 'item': v})
logging.debug("Client '%s' queried for equipment.", self.uid)
return {'equipment': amp_equipment}
commands.QueryEquipment.responder(query_equipment)
def query_inventory(self):
inventory = self.factory.game.get_inventory(self.uid)
amp_inventory = []
for item, qty in inventory.items():
amp_inventory.append({'item': item.get_name(), 'qty': qty})
logging.debug("Client '%s' queried for inventory.", self.uid)
return {'inventory': amp_inventory}
commands.QueryInventory.responder(query_inventory)
#--------------------------------------------------------------------------
# commands
def add_chat_messages(self, messages):
for i, m in enumerate(messages):
messages[i] = {'message': m[0], 'type': m[1]}
logging.debug("Pushed chat messages to client '%s'.", self.uid)
return self.callRemote(commands.AddChatMessages, messages=messages)
def set_bottom_status_bar(self, text):
logging.debug("Set bottom status bar for client '%s'.", self.uid)
return self.callRemote(commands.SetBottomStatusBar, text=text)
def set_equipment(self, equipment):
amp_equipment = []
for k, v in equipment.items():
v = 'None' if v is None else v.get_name()
amp_equipment.append({'slot': k, 'item': v})
logging.debug("Set equipment for client '%s'.", self.uid)
return self.callRemote(commands.SetEquipment, equipment=amp_equipment)
def set_inventory(self, inventory):
amp_inventory = []
for item, qty in inventory.items():
amp_inventory.append({'item': item.get_name(), 'qty': qty})
logging.debug("Set inventory for client '%s'.", self.uid)
return self.callRemote(commands.SetInventory, inventory=amp_inventory)
def set_look_pointer(self, (x, y)):
logging.debug(
"Set look pointer for client '%s' at (%d, %d).",
self.uid, x, y)
return self.callRemote(commands.SetLookPointer, x=x, y=y)
def set_pilot(self, is_pilot):
logging.debug(
"Set pilot mode for client '%s' to '%r'.",
self.uid, is_pilot)
return self.callRemote(commands.SetPilot, is_pilot=is_pilot)
def set_target(self, (x, y)):
logging.debug(
"Set target pointer for client '%s' at (%d, %d).",
self.uid, x, y)
return self.callRemote(commands.SetTarget, x=x, y=y)
def set_top_status_bar(self, text):
logging.debug("Set top status bar for client '%s'.", self.uid)
return self.callRemote(commands.SetTopStatusBar, text=text)
def set_view(self, view, colors):
view = '\n'.join(view)
c_colors = []
for k, v in colors.items():
c_colors.append(
{'x': k[0], 'y': k[1], 'r': v[0], 'g': v[1], 'b': v[2]})
logging.debug("Set view for client '%s'.", self.uid)
return self.callRemote(commands.SetView, view=view, colors=c_colors)
def unset_look_pointer(self):
logging.debug("Unset look pointer for client '%s'.", self.uid)
return self.callRemote(commands.UnsetLookPointer)
def unset_target(self):
logging.debug("Unset target pointer for client '%s'.", self.uid)
return self.callRemote(commands.UnsetTarget)
</code></pre>
<p>Here's an example output:</p>
<pre><code>INFO:root:Started server on port 12345.
INFO:root:Client '4352955472' is connected.
DEBUG:root:Client '4352955472' queued tuple of str 'connect' with value '(Mr Spaceman, Enterprise)'.
DEBUG:root:Set view for client '4352955472'.
DEBUG:root:Set bottom status bar for client '4352955472'.
DEBUG:root:Client '4352955472' queried for inventory.
DEBUG:root:Client '4352955472' queried for equipment.
DEBUG:root:Client '4352955472' queued tuple of int 'move' with value '(0, 1)'.
DEBUG:root:Set view for client '4352955472'.
DEBUG:root:Client '4352955472' queued tuple of int 'move' with value '(1, 0)'.
DEBUG:root:Set view for client '4352955472'.
DEBUG:root:Client '4352955472' queued tuple of int 'move' with value '(1, 0)'.
DEBUG:root:Set view for client '4352955472'.
DEBUG:root:Client '4352955472' queued tuple of int 'activate' with value '(1, 0)'.
DEBUG:root:Set view for client '4352955472'.
DEBUG:root:Set top status bar for client '4352955472'.
DEBUG:root:Client '4352955472' queued int 'quit' with value '1'.
</code></pre>
<p>How much information should I put into the log output? But I'm afraid my logs will contain too much information to easily comprehend what is going on. Should I consider looking into AOP for this? What are the good practices?</p>
<p>Feel free to suggest some good reading on a subject in addition to a code review.</p>
| [] | [
{
"body": "<blockquote>\n <p><strong>my logs will contain too much information</strong></p>\n</blockquote>\n\n<p>Think of your log as a database of logged records. You might have all logged records contain the same number of fields (client#, action, result, etc) and each event decides which fields to fill in when generating the record. Or, you might have N different record layouts (connect event record, query event record, setgui event record, etc) and each event creates the record type specific to that event.</p>\n\n<p>In either case, don't worry that you might have too many records or that records contain too much info, because what you also need to create is a log viewer/filter that allows only the records and contents of interest to be displayed or dumped.</p>\n\n<p>The first logging option (all records contain the same number of fields, although many may be empty) is preferable, because lots of database tools can then be used.</p>\n\n<p>For example, if your logging code creates a table of SQLite records, you can use SQLite to conveniently select and report only the logged events of interest.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:44:32.000",
"Id": "46426",
"ParentId": "46419",
"Score": "3"
}
},
{
"body": "<p>The code in the methods seems repetitive. I suggest that you extract the logging and command registration aspects using decorators. That way, each method only contains the code for its core functionality.</p>\n\n<p><strong>command_decorators.py</strong></p>\n\n<pre><code>from functools import wraps\nimport logging\n\ndef trace(f):\n @wraps(f)\n def logged_f(self, *args):\n logging.debug('Client %s called %s with %s', self, f.__name__, args)\n return f(self, *args)\n return logged_f\n\ndef responder_for(cmd):\n def real_decorator(f):\n cmd.responder(f)\n return f\n return real_decorator\n</code></pre>\n\n<p><strong>command_protocol.py</strong></p>\n\n<pre><code>from command_decorators import trace, responder_for\n\nclass CommandProtocol(object):\n\n @responder_for(commands.QueueInt)\n @trace\n def queue_int(self, action, arg):\n self.factory.requests.add_request(self.uid, (action, arg))\n return {}\n\n @responder_for(commands.QueueStr)\n @trace\n def queue_str(self, action, arg):\n self.factory.requests.add_request(self.uid, (action, arg))\n return {}\n\n @responder_for(commands.QueueTupleOfInt)\n @trace\n def queue_tuple_of_int(self, action, arg1, arg2):\n self.factory.requests.add_request(self.uid, (action, (arg1, arg2)))\n return {}\n\n …\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T06:11:45.077",
"Id": "46434",
"ParentId": "46419",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T01:03:13.080",
"Id": "46419",
"Score": "3",
"Tags": [
"python",
"logging"
],
"Title": "How in-depth should the logging be?"
} | 46419 |
<p>A few weeks ago I posted a code review of a linked list so I decided to implement bubble sort on my journey of learning C. Here is the referenced linked list library, though this isn't really what's being reviewed (feel free if you'd like!).</p>
<p>Linked lists seem inefficient for bubble sort as deletes and gets both have to walk the list. So it's probably something like \$ O\left( n^{3} \right) \$?</p>
<p>I implemented it with arrays too, which is faster because the swapping can be done in place.</p>
<hr>
<p><a href="http://pastebin.com/nfcQYNMg" rel="nofollow"><code>LinkedList.h</code></a></p>
<p><a href="http://pastebin.com/CweuPxF7" rel="nofollow"><code>LinkedList.c</code></a></p>
<p><code>BubbleSort.c</code>:</p>
<pre><code>#include "../linked_list/ll.h"
void sort_linked_list(linked_list *list) {
assert(list);
int sorted = 1;
for (int x = 0; x < list->size; x++) {
/* don't do it if this is the last value */
if (x + 1 == list->size) {
continue;
}
int first = linked_list_get(list, x);
int second = linked_list_get(list, x + 1);
if (first > second) {
sorted = 0;
int temp = linked_list_get(list, x);
/* {1, 7, 3}, 1 -> {1, 3} */
linked_list_delete_at(list, x);
/* {1, 3}, 7, 1 -> {1, 3, 7} */
linked_list_insert_after(list, temp, x);
}
}
/* do it again if it's not fully sorted */
if (!sorted) {
sort_linked_list(list);
}
}
void sort_array(int *array, int size) {
assert(size >= 0);
int sorted = 1;
for (int x = 0; x < size; x++) {
/* don't do it if this is the last value */
if (x + 1 == size) {
break;
}
/* get int address */
int *first = array + x;
/* get int address after that one */
int *second = first + 1;
if (*first > *second) {
/* we did some sorting so not sorted */
sorted = 0;
int temp = *first;
int temp2 = *second;
/* swap values */
*first = temp2;
*second = temp;
}
}
/* do it again if it's not fully sorted */
if (sorted == 0) {
sort_array(array, size);
}
}
void print_array(int *array, int size) {
printf("{ ");
for (int x = 0; x < size; x++) {
printf("%d ", *array);
array++;
}
printf("}\n");
}
int main() {
linked_list *list = new_linked_list();
linked_list_append(list, 7);
linked_list_append(list, 5);
linked_list_append(list, 3);
linked_list_append(list, 8);
linked_list_append(list, 1);
linked_list_print(list);
sort_linked_list(list);
linked_list_print(list);
int a[5] = {7, 5, 3, 8, 1};
print_array(a, 5);
sort_array(a, 5);
print_array(a, 5);
return 0;
}
</code></pre>
<p>Makefile:</p>
<pre><code> all: ../linked_list/ll.h bubble.c
gcc -std=c99 -Wall -o bubble bubble.c ../linked_list/ll.c
./bubble
</code></pre>
<p>As you can see, <code>linked_list</code> is in another directory. Is this the correct way to include this in my project? I don't fully understand Makefiles quite yet. </p>
<p>Also, any general style tips for my bubble sort would be appreciated. I use pointer arithmetic with my arrays because it helps me understand what's really going on (which is why I'm learning C) but let me know if that's messy. I'd just like to keep learning how to write good C code.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T04:16:58.110",
"Id": "81107",
"Score": "0",
"body": "If you want your other code reviewed, you need to post it here, not a link to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T04:17:38.087",
"Id": "81108",
"Score": "0",
"body": "don't need it reviewed, just posting it here because it's referenced in this code!"
}
] | [
{
"body": "<h1>Things you did well</h1>\n\n<ul>\n<li><p>You initialize your variables when you declared them.</p></li>\n<li><p>You initialize variables inside of your <code>for</code> loops.<sup>(C99)</sup></p></li>\n<li><p>Your pointer arithmetic looks pretty sound.</p></li>\n</ul>\n\n<h1>Things you can improve</h1>\n\n<h3>Efficiency/Algorithm</h3>\n\n<ul>\n<li><p>Unfortunately, bubble sort is not a very good sorting algorithm if you are looking for speed. Its average case performance is \\$ O\\left(n^{2}\\right) \\$.</p></li>\n<li><p>If you are looking into greater speed with your sorting function, look at a <a href=\"https://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow\">quicksort algorithm</a>. Its average case performance is \\$ O\\left( n \\log n \\right) \\$.</p></li>\n</ul>\n\n<h3>User experience</h3>\n\n<ul>\n<li>Is shutting down the program really necessary when your linked list doesn't actually exist, or that the size of your array is less than one? Do something more useful than <code>assert()</code>, and return a specific error code that you can handle later on in your code. This will greatly help you in debugging too.</li>\n</ul>\n\n<h3>Makefile</h3>\n\n<ul>\n<li><p><strong>Makefile variables</strong> - Right now your Makefile isn't very expandable. Variables help out a lot with that.</p>\n\n<ul>\n<li><p>Put your compiler names into variables.</p>\n\n<pre><code>CXX = g++\nCC = gcc\n</code></pre>\n\n<p>This is something I like to do, however, some variables like <code>CC</code> are declared already, so you generally don't need to.</p></li>\n<li><p>Put your final executable into a variable name.</p>\n\n<pre><code>EXECUTABLE = bubble\n</code></pre></li>\n<li><p>Put your sources into a variable name.</p>\n\n<pre><code>SOURCES = bubble.c\n</code></pre></li>\n<li><p>Put your objects into a variable name.</p>\n\n<pre><code>OBJECTS = $(SOURCES:.c=.o)\n\n.c.o:\n $(CC) $(CFLAGS) -o $@ $<\n</code></pre></li>\n<li><p>All of your compiler flags should be in one variable. And tack on a linker flag variable while we are at it, for futures sake.</p>\n\n<pre><code>CFLAGS = -std=c99 -Wall\nLDFLAGS =\n</code></pre></li>\n<li><p>Calling the variables is now a lot more easy and flexible.</p>\n\n<pre><code>all: $(EXECUTABLE)\n\n$(EXECUTABLE): $(OBJECTS)\n $(CC) $(LDFLAGS) -o $@ $<\n</code></pre></li>\n</ul></li>\n<li><p><strong>Compiler flags</strong> - get the most out of your compiler so that you can code better.</p>\n\n<ul>\n<li><p>You should change the standards you are using to C11 with <code>--std=c11</code></p></li>\n<li><p><code>-g</code> adds symbols for debugging. Without it, your debugger won't be able to give you variable or function names. The don't slow down the program, and we don't care if the program is a kilobyte larger, so there's little reason to not use this.</p></li>\n<li><p><code>-O3</code> indicated optimization level three, which tries every trick known to build faster code. If, when you run the debugger, you find that too many variables have been optimized out for you to follow what's going on, then change this to <code>-O0</code>.</p></li>\n</ul>\n\n<p>If you want to go above and beyond, here are all of the compiler flags I use.</p>\n\n<pre><code>CFLAGS = -std=gnu11 -c -s -O3 -Werror -Wall -Wextra -Wformat=2 -Winit-self -Wswitch-enum -Wstrict-aliasing=2 -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline -Wdisabled-optimization -Wunused-macros -Wno-unused\n</code></pre></li>\n</ul>\n\n<h3>Standards</h3>\n\n<ul>\n<li><p>You don't have to return <code>0</code> at the end of <code>main()</code>, just like you wouldn't bother putting <code>return;</code> at the end of a <code>void</code>-returning function. The C standard knows how frequently this is used, and lets you not bother.</p>\n\n<blockquote>\n <p><strong>C99 & C11 §5.1.2.2(3)</strong></p>\n \n <p>...reaching the <code>}</code> that terminates the <code>main()</code> function returns a\n value of <code>0</code>.</p>\n</blockquote></li>\n</ul>\n\n<h3>Syntax/Styling</h3>\n\n<ul>\n<li><p>Use <a href=\"https://en.wikipedia.org/wiki/Yoda_conditions\" rel=\"nofollow\">Yoda conditions</a> to prevent future bugs.</p>\n\n<pre><code>if (0 == sorted)\n</code></pre>\n\n<p>Placing the constant value in the expression does not change the behavior of the program. A common mistake is to accidentally assign a value instead of writing a conditional statement. Using Yoda conditions will throw a syntax error if you accidentally do that, so your code won't compile.</p></li>\n<li><p>You should return some status indicators from your sorting functions, so we can check that the sorting went okay. This also makes for easier debugging.</p></li>\n<li><p>You can simplify some of your test conditionals</p>\n\n<blockquote>\n<pre><code>if (sorted == 0)\n</code></pre>\n</blockquote>\n\n<p>That is actually harder for me to understand over my version.</p>\n\n<pre><code>if (!sorted)\n</code></pre>\n\n<p>If I were to read my version out loud, it would read \"if not sorted\", whereas your version is \"if sorted is equal to 0\". It's odd, since you have this in one place, but not the other (always be consistent).</p></li>\n<li><p>Declare your method parameters as <code>void</code> if you don't take any arguments in.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T05:20:04.753",
"Id": "81116",
"Score": "0",
"body": "Awesome. very helpful stuff. (and I know bubble sort is inefficient, I'm just going through basic data structures / algorithms in C to get used to it). Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T05:08:30.957",
"Id": "46431",
"ParentId": "46427",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "46431",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:53:39.347",
"Id": "46427",
"Score": "12",
"Tags": [
"c",
"array",
"linked-list",
"sorting",
"makefile"
],
"Title": "Bubble Sort in C: Array vs Linked List"
} | 46427 |
<p>Recently I had a problem (not in C++) that required merging a number of sorted lists of values. This is effectively the generalised case of merging together two sorted lists. However, instead of merging them into one single list, the requirement was instead to effectively put them into "buckets" of like values. As an example, given:</p>
<blockquote>
<p>{1, 2, 3}, {2, 3, 4}, {1, 3, 5}</p>
</blockquote>
<p>They should go into "buckets" of like values:</p>
<blockquote>
<p>{1, 1}, {2, 2}, {3, 3, 3}, {4}, {5}</p>
</blockquote>
<p>I've rewritten it in C++ for fun:</p>
<pre><code>#include <vector>
#include <type_traits>
#include <list>
#include <deque>
#include <iterator>
// Given an pair of Iterators to an outer container that has a nested
// container, such as std::vector<std::deque<T>>, where the values in each
// std::deque<T> are sorted in ascending order, will return a vector of
// Iterators where the first element is an (equal) minimum over all the containers.
// For example, given:
// std::vector<std::deque<int>> = { {1, 2, 3}, {2, 3, 4}, {1, 4, 5} };
// This would return iterators to the 1st and 3rd elements, as both have
// the equal minimum (here, 1) in the first position.
template <typename Iterator>
std::vector<Iterator> minimums(Iterator begin, Iterator end)
{
std::vector<Iterator> mins;
if(begin == end) { return mins; }
while(begin != end && begin->begin() == begin->end()) { ++begin; }
if(begin == end) { return mins; }
mins.push_back(begin);
++begin;
for(auto it = begin; it != end; ++it) {
const auto& current_min = *std::begin(*mins[0]);
if(*(it->begin()) < current_min) {
mins.clear();
mins.push_back(it);
}
else if(*(it->begin()) == current_min) {
mins.push_back(it);
}
}
return mins;
}
template <typename T>
void erase_front(std::list<T>& l) { l.pop_front(); }
template <typename T>
void erase_front(std::deque<T>& d) { d.pop_front(); }
// Performs a destructive multiway merge.
// The begin and end Iterators should reference a container with nested
// containers, where each nested container is sorted in ascending order.
// Further, the nested containers must support erasure from the front,
// so a std::deque is suggested here for optimal speed.
// To use a container that is not std::list or std::deque, a specialization
// for erase_front must be written for the container. This should simply
// remove the first element of the given container.
// Erasing the first element should NOT invalidate any other iterators,
// hence this should not be used where a std::vector<T> is the nested
// container.
template <typename Iterator>
auto multiway_merge(Iterator begin, Iterator end) ->
std::vector<typename std::remove_reference<decltype(*begin)>::type>
{
using inner_container = typename std::remove_reference<decltype(*begin)>::type;
using container_type = std::vector<inner_container>;
container_type store;
std::vector<Iterator> current_minimums = minimums(begin, end);
for(; current_minimums.size() > 0; current_minimums = minimums(begin, end)) {
auto& minimum = *(std::begin(*current_minimums[0]));
inner_container ic;
for(auto& mins : current_minimums) {
while(std::begin(*mins) != std::end(*mins) &&
*std::begin(*mins) == minimum) {
ic.emplace_back(std::move(*std::begin(*mins)));
erase_front(*mins);
}
}
store.emplace_back(std::move(ic));
}
return store;
}
</code></pre>
<p>This is destructive to the original container, elements are moved out as they are encountered. The other way to do this (which works for non-sorted containers, and is not destructive) is to put everything into a map of some kind:</p>
<pre><code>#include <unordered_map>
template <typename T>
struct remove_const_reference
{
using type = typename std::remove_const<typename std::remove_reference<T>::type>::type;
};
template <typename Container>
auto put_into_map(const Container& v) ->
std::unordered_map<typename remove_const_reference<decltype(v.front().front())>::type,
std::vector<typename remove_const_reference<decltype(v.front().front())>::type>>
{
using T = typename remove_const_reference<decltype(v.front().front())>::type;
std::unordered_map<T, std::vector<T>> m;
for(const auto& d : v) {
for(const auto& i : d) {
m[i].push_back(i);
}
}
return m;
}
</code></pre>
<p>This has the upside of not "destroying" the original container; however, it uses twice the memory, and since we have ordered data, in my tests it's somewhere between 1.5 to 3 times slower.</p>
<p>To satisfy this, the contained type must have an <code>operator<</code> and an <code>operator==</code>. Some tests:</p>
<pre><code>template <typename Container>
void print(const Container& c)
{
std::cout << "{ ";
for(const auto& v : c) {
std::cout << v << ", ";
}
std::cout << "}\n";
}
struct test_struct
{
std::string s;
int i;
double j;
};
bool operator<(const test_struct& a, const test_struct& b)
{
return a.s < b.s;
}
bool operator==(const test_struct& a, const test_struct& b)
{
return a.s == b.s;
}
std::ostream& operator<<(std::ostream& os, const test_struct& ts)
{
return os << "(" << ts.s << ", " << ts.i << ", " << ts.j << ")";
}
int main()
{
std::vector<std::list<int>> v = {{1, 2, 3, 4},
{2, 3, 4},
{1, 3, 4, 5, 6}};
auto sorted = multiway_merge(v.begin(), v.end());
for(const auto& container : sorted) {
print(container);
}
std::vector<std::deque<test_struct>> v2 =
{{ {"a", 1, 1.0}, {"b", 2, 2.5}, {"c", 1, 5.0} },
{ {"b", 7, 0.5}, {"c", 4, 4.5}, {"d", 1, 5.0} } };
auto sorted2 = multiway_merge(v2.begin(), v2.end());
for(const auto& container : sorted2) {
print(container);
}
}
</code></pre>
<p>Any feedback would be appreciated. I consider it a bit ugly because the <code>Iterator</code> template parameters are dealing with nested containers, which makes the code harder to read, so anything that addresses that would be welcome.</p>
| [] | [
{
"body": "<p>My immediate reaction would be to accept a collection of ranges of some sort (e.g., Boost Range, or even just a pair of iterators).</p>\n\n<p>Since the range (or iterator) types would be template parameters, the user can pass normal iterators or move iterators as s/he sees fit, so one piece of code suffices for both copying (non-destructive) and moving (destructive) merges.</p>\n\n<p>I'd expect this to give sort of a half-way point between the two current pieces of code. It would probably be about the speed of the current destructive version, but potentially use more memory--it can move objects from the original container, but doesn't delete the source items from the original container as their moved to the output, so it will consume more memory than your existing destructive merge. </p>\n\n<p>Memory usage will depend on whether you're dealing with objects that store most data in the object itself, or mostly store a pointer in the object and put most of the real data on the heap. In the latter case, moving out of the object will typically just move the pointer to the data into the new object, and leave only the minimal bookkeeping information in the old object, so it won't consume a lot more than the code above that deletes each item from the source container as it's moved to the destination collection.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T05:51:34.110",
"Id": "46432",
"ParentId": "46430",
"Score": "2"
}
},
{
"body": "<p>If you have <code>k</code> sorted lists containing <code>n</code> elements in total, your first approach is <code>O(nk)</code> time, while the second appears to be <code>O(n log n)</code> time. Worse, the \"collect-then-throw-away\" logic of your function <code>minimums</code> makes the process even slower.</p>\n\n<p>The same task can be done in <code>O(n log k)</code> time by using a <a href=\"http://en.wikipedia.org/wiki/Min_heap\" rel=\"nofollow noreferrer\">binary min-heap</a>. The heap keeps track of which list to take the next element from. In practice, you need a very simple algorithm using <code>std::priority_queue</code>. Check <a href=\"https://stackoverflow.com/a/5055937/2644390\">algorithm for N-way merge</a> for instance. Putting in buckets requires only a slight modification.</p>\n\n<p>Whether you copy or move data is irrelevant, and can be controlled by move iterators as <a href=\"https://codereview.stackexchange.com/a/46432/39083\">Jerry Coffin</a> suggests.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:13:25.093",
"Id": "46660",
"ParentId": "46430",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T05:02:37.947",
"Id": "46430",
"Score": "6",
"Tags": [
"c++",
"c++11",
"mergesort"
],
"Title": "Generic Multiway Merge"
} | 46430 |
<p>I am not happy with this code as I am sure there are better ways to do what I'm trying to achieve. I'm a beginner and I've used what I know to date to complete this.</p>
<pre><code>import java.util.Random;
import java.util.Scanner;
public class SeventySix {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//52 Cards, Aces = 11, Picture cards = 10, Ace's cannot be reduced to 1.
int[] newCard = {2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11};
//Shuffle. Once per game.
shuffleArray(newCard);
//Start BlackJack.
System.out.println("Welcome to BlackJack!");
System.out.println();
System.out.println("You get a " + newCard[0] + " and a " + newCard[1] + ".");
int playerTotal = newCard[0] + newCard[1];
System.out.println("Your total is " + playerTotal + ".");
System.out.println();
//Player can get blackjack/bust in the 1st deal. - awaiting betting system (enhanced bets for blackjack in first round)
if (playerTotal == 21){
System.out.println("Blackjack, you win.");
System.exit(0);
}
if (playerTotal > 21){
System.out.println("Bust, You lose.");
System.exit(0);
}
// Dealer cards
System.out.println("The dealer has a " + newCard[2] + " showing, and a hidden card.");
int dealerTotal = newCard[2] + newCard[3];
if (dealerTotal > 21){ //Dealer bust check.
System.out.println();
System.out.println("Dealers total is " + dealerTotal + ".");
System.out.println("Dealer is bust, you win!");
System.exit(0);
}
if (dealerTotal == 21){ //Dealer blackjack check.
System.out.println();
System.out.println("Dealer reveals his second card: " + newCard[3] + ".");
System.out.println("Dealers total is " + dealerTotal + ".");
System.out.println();
System.out.println("Dealer has BlackJack, you lose.");
System.exit(0);
}
System.out.println("His total is hidden.");
System.out.println();
// Hit or Stay for player.
System.out.print("Would you like to \"hit\" or \"stay\"? ");
String hitStay = keyboard.next();
System.out.println();
//cc = card count
int cc = 4;
if (hitStay.equalsIgnoreCase("hit")){
// While loop to ensure different cards & multiple "hits".
while (playerTotal < 21 && hitStay.equalsIgnoreCase("hit")){
if (hitStay.equalsIgnoreCase("hit")){
System.out.println("You drew a " + newCard[cc] + ".");
playerTotal = playerTotal + newCard[cc];
System.out.println("Your total is " + playerTotal + ".");
System.out.println();
cc++; //Adds 1 to ensure next card is different.
// Bust & Blackjack check.
if (playerTotal > 21){
System.out.println("You are bust, You lose.");
System.exit(0);
}
if (playerTotal == 21){
System.out.println("Blackjack, you win.");
System.exit(0);
}
System.out.print("Would you like to \"hit\" or \"stay\"? ");
hitStay = keyboard.next();
System.out.println();
}
}
}
// Dealers turn, only if Round 1 didn't end in bust/blackjack.
keyboard.close();
System.out.println("Ok dealers turn.");
System.out.println("His hidden card was a " + newCard[3] + "."); // reveal hidden from round one.
cc++; // Pretty sure its not needed.
while (dealerTotal < 16){ // Dealer will stay on 16+ and hit if below.
System.out.println();
System.out.println("Dealer chooses to hit.");
System.out.println("He draws a " + newCard[cc] + ".");
cc++;
dealerTotal = dealerTotal + newCard[cc];
System.out.println();
System.out.println("His total is " + dealerTotal);
// bust check - no need for blackjack check due to final win sequence
if (dealerTotal > 21){
System.out.println();
System.out.println("Dealer is bust, YOU WIN!");
System.exit(0);
}
// stay condition.
if (dealerTotal < 21 && dealerTotal > 16){
System.out.println();
System.out.println("Dealer Stays.");
}
}
// final win sequence.
System.out.println();
System.out.println("Dealer total is " + dealerTotal);
System.out.println("Your total is " + playerTotal);
System.out.println();
if (dealerTotal > playerTotal){
System.out.println("Dealer wins.");
}
if (dealerTotal == playerTotal){
System.out.println("You both draw.");
}
if (dealerTotal < playerTotal){
System.out.println("You win.");
}
}
static void shuffleArray(int[] deckCards){
/**
* This code is obtained from the internet and is not my own though process
* I need to understand it before I will be happy using it.
* I'll have a try at explaining this, please correct me if I suckarino.
* deckCards is a placeholder for the array I chose to use.
* i = the length of the array which is 52, -1 would be 51.
* i will be greater than 0 until the i-- completely loops it down to 0.
* index is a random number between 1 & 52.
* a is a random number in the array.
* deckCards[i] is replaced with a;
* essentially shuffling 1 card in the array, this happens 51 times?
*/
Random rnd = new Random();
for (int i = deckCards.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Swap
int a = deckCards[index];
deckCards[index] = deckCards[i];
deckCards[i] = a;
}
}
}
</code></pre>
<p>I've tried to keep the comments understandable to some degree.</p>
| [] | [
{
"body": "<p>You should make your entire application more Object Oriented. \nA good place to start would be to move the deck of cards and associated functions into other classes.</p>\n\n<p>Here's an implementation of a deck stolen from a <a href=\"https://stackoverflow.com/a/15942601/334274\">StackOverflow Question</a>. Notice there's also a <code>Card</code> object.</p>\n\n<pre><code>public class DeckOfCards {\n private Card cards[];\n\n public DeckOfCards() {\n this.cards = new Card[52];\n for (int i = 0; i < 52; i++) {\n Card card = new Card(...); //Instantiate a Card\n this.cards[i] = card; //Adding card to the Deck\n }\n }\n}\n</code></pre>\n\n<p>Also think about using <code>enums</code> for suit and a method of tracking the card value. Searching Google for Cark rank patterns will help with this.</p>\n\n<p>You have a lot of multiline print statements that could probably be joined together;</p>\n\n<pre><code>System.out.println();\nSystem.out.println(\"Dealer total is \" + dealerTotal);\nSystem.out.println(\"Your total is \" + playerTotal);\nSystem.out.println();\n</code></pre>\n\n<p>Could be;</p>\n\n<pre><code>System.out.println(\n String.format(\"\\nDealer total is %s \\nYour total is %s \\n\", dealerTotal, playerTotal)\n);\n</code></pre>\n\n<p>To save on complexity, these should be <code>else if</code>s instead;</p>\n\n<pre><code>if (dealerTotal > playerTotal){\n System.out.println(\"Dealer wins.\");\n} \nelse if (dealerTotal == playerTotal){\n System.out.println(\"You both draw.\");\n}\nelse {\n System.out.println(\"You win.\");\n}\n</code></pre>\n\n<p>Finally, your code is not very <a href=\"https://en.wikipedia.org/wiki/Don't_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>. You need more of your functionality in separate methods to prevent you repeating yourself. A good example of this is that you have multiple win sequences. Your win/lose conditions should result in a win/lose method being called which executes the appropriate sequence.</p>\n\n<p>Also Blackjack is a repetitious game, turn two is identical to turn one, your code just repeats the same operations a second time. Again this should be moved into methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T09:34:04.583",
"Id": "46440",
"ParentId": "46439",
"Score": "15"
}
},
{
"body": "<p>I'd just like to point out that though the cards would be better represented as objects instead of <code>int</code>s, and the program organization and flow is a bit muddled, your choice of shuffling algorithm is excellent.</p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\">Fisher-Yates shuffle</a> is a simple and unbiased way to randomize the order of the elements of an array, and you have a textbook implementation of it. Even if you didn't write the code yourself, I think you should get credit for picking the right code to copy.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Since you asked about the validity of the comment in <code>shuffleArray()</code>…</p>\n\n<p>This is what you wrote, ignoring the initial noise:</p>\n\n<blockquote>\n <ul>\n <li><code>deckCards</code> is a placeholder for the array I chose to use.</li>\n <li><code>i</code> = the length of the array which is 52, -1 would be 51.</li>\n <li><code>i</code> will be greater than 0 until the <code>i--</code> completely loops it down to 0.</li>\n <li><code>index</code> is a random number between 1 & 52.</li>\n <li><code>a</code> is a random number in the array.</li>\n <li><code>deckCards[i]</code> is replaced with <code>a</code>;</li>\n </ul>\n \n <p>essentially shuffling 1 card in the array, this happens 51 times?</p>\n</blockquote>\n\n<p>Your vocabulary is slightly off, and the remarks about <code>i</code> going down to 0 and <code>index</code> being between 1 and 52 are inaccurate.</p>\n\n<blockquote>\n <ul>\n <li><code>deckCards</code> is a <strong>reference to the input array. This function shuffles its elements in place.</strong></li>\n <li><code>i</code> <strong>is initially the index of the last element of the array.</strong></li>\n <li><code>i</code> <strong>iterates down to 1.</strong></li>\n <li><code>index</code> is a random number between <strong>0 and i, inclusive.</strong></li>\n <li><code>a</code> is a random <strong>element of</strong> the array.</li>\n <li><code>deckCards[i]</code> is <strong>swapped</strong> with <code>a</code>;</li>\n </ul>\n \n <p>essentially shuffling 1 card in the array, this happens 51 times?</p>\n</blockquote>\n\n<p>However, that is an uninsightful, mechanical description of the code. A better comment would be:</p>\n\n<blockquote>\n <p>For each element of the array (except the first), starting from the end, pick any previous element (or itself) with uniform probability, and swap them.</p>\n \n <p>This technique is unbiased. For example, consider what happens during the first loop when shuffling a 52-card deck. Every card in the deck is equally likely to take the position of <code>deckCards[51]</code>. With the last element <code>deckCards[51]</code> thus fairly selected, repeat the process — randomly draw from the remaining 51-card deck to fill its last element <code>deckCards[50]</code>, and so on for the entire deck.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:50:13.940",
"Id": "81138",
"Score": "0",
"body": "Thank you for this, I did a fair amount of research to see what shuffling method would be good. Just an additional question, my comments explaining the fisher-yates method is that correct? I don't like using code I don't understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T13:19:02.223",
"Id": "81140",
"Score": "0",
"body": "Indeed, your comment has some problems. I've added a critique of the comment in my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T10:49:54.390",
"Id": "46445",
"ParentId": "46439",
"Score": "11"
}
},
{
"body": "<p>There is a small mistake in your code:</p>\n\n<p>Aces are <strong>only</strong> 11, but not 1. This means the player (or the dealer) could bust with just the two cards they're dealt.<br>\nAssuming they only had Aces, then it would be a bust with this code. I would add a check to see if the player is busting, but that one of the cards was dealt as an Ace. Possibly even creating a boolean, <code>PlayerHasAce</code>. </p>\n\n<p>Pseudocode:\n</p>\n\n<pre><code>If they bust, and PlayerHasAce is TRUE;\n minus 10 from the total;\n are they still busting without additional aces? \n No? Good! They can continue playing. \n</code></pre>\n\n<p>You would just need to make sure the boolean is set only ONCE per Ace though, and not repeated during the same hand.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T16:27:50.383",
"Id": "86555",
"Score": "0",
"body": "your pseudo code isn't complete, if the player has 2 Aces (22) we subtract 10 (12) then gets a ten (22) it should now be (12), they will bust, you need a more complex process for this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T16:44:04.827",
"Id": "86562",
"Score": "0",
"body": "@Can if it is only checked once it won't change both aces to have a value of 1, it will only check one of the aces. in this case it should change the second ace to a value of one when the ten card is drawn. it needs to be checked more than once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T19:30:12.787",
"Id": "86614",
"Score": "1",
"body": "Sorry @Malachi, what I meant was that it only does it once per Ace... I'll edit the answer"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:49:51.457",
"Id": "46524",
"ParentId": "46439",
"Score": "11"
}
},
{
"body": "<p>In addition to creating an object for Deck, an object for a player's hands and the dealer hand will also be useful. In Blackjack a player may take different actions depending on the first two cards dealt, split or double. The player may also take different actions depending on the dealer's up card -- take insurance if it is an ace.</p>\n\n<p>With all that in mind, the basic objects of the game might be:</p>\n\n<p><code>Deck</code>: holds available cards</p>\n\n<p><code>DealersHand</code>: holds cards removed from deck and dealt to dealer. One of the first two cards is the up card.</p>\n\n<p><code>List[Player]</code>: all the players </p>\n\n<p><code>List[PlayerHands]</code>: each Player has a list of <code>PlayerHands</code></p>\n\n<p>All hand objects should be able to calculate their score</p>\n\n<p>Finally you may consider a Game object that can deal hands, evaluate the winners of each round, keep score and display the results.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T11:34:56.583",
"Id": "46538",
"ParentId": "46439",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "46440",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T09:02:07.440",
"Id": "46439",
"Score": "15",
"Tags": [
"java",
"beginner",
"game",
"playing-cards"
],
"Title": "First attempt at a Blackjack game"
} | 46439 |
<p>I found a bit better implementation for Java <code>Arrays.sort(int[])</code>. To make this code review more simple I divide this questions to several parts.</p>
<p>The goal of this question is to find more ways to increase the performance even better.</p>
<p><strong>Edit:</strong> Tested over Java 6, win 64 bit. In average for equal redistributed input(did not tested any other) my algorithm perform 10% better than Java native.</p>
<ul>
<li>How my algorithm is different from traditional merge sort</li>
<li>How does my algorithm work</li>
<li>Algorithm source code in Java.</li>
<li>Testing program source code</li>
<li>Why this testing is not really a test</li>
</ul>
<h2>How my algorithm is different from traditional merge sort</h2>
<p>While the traditional merge sort start by dividing the the input array to half and half and half... Until reaching the bounds of 2 and than starting to merge all the half together. I did the opposite, I started from the smallest piece of the array and merge my way up. Also I have a special case of array with 4 elements. </p>
<h2>How does my algorithm work</h2>
<pre><code>Read input to array.
Dividing the array to pieces of 4, and sort them all.
Take the last 4 elements from the array and sort them.
Iterate over count from 0 to array size, multiply it by 2 in each iteration.
iterate over startingIndex from count to array size, increase it's size by count over each iteration.
merge the two pieces of the array. From startingIndex to startingIndex + count, and from startingIndex + count to startingIndex + 2 * count.
Note that the second part could exceed the array size.
</code></pre>
<h2>Algorithm source code in Java.</h2>
<pre><code>public class SortMerge4 {
public static void sort(int source[]) {
if(source.length < 4){
Arrays.sort(source);
return;
}
presort(source);
int[] buffer = new int[source.length];
boolean swapBufferSource = false;
for (int count = 4; count < source.length; count *= 2) {
Arrays.fill(swapBufferSource ? source : buffer, 0);
for (int startingIndex = 0; startingIndex < buffer.length; startingIndex += count * 2) {
int leftBound = startingIndex + count;
int rightBound = Math.min(startingIndex + count * 2, source.length);
if (swapBufferSource) {
merge(buffer, source, startingIndex, leftBound, rightBound);
}
else{
merge(source, buffer, startingIndex, leftBound, rightBound);
}
}
swapBufferSource = !swapBufferSource;
}
if(swapBufferSource){
System.arraycopy(buffer, 0, source, 0, buffer.length);
}
}
private static void presort(int[] source) {
for (int i = 0; i < source.length - 4; i += 4) {
bubleSort4(source, i);
}
bubleSort4(source, source.length - 4);
}
private static void merge(int[] source, int[] buffer, int startingIndex, int leftBound, int rightBound) {
int leftIndex = startingIndex;
int rightIndex = leftBound;
for (int i = startingIndex; i < rightBound; i++) {
if (leftIndex >= leftBound || (rightIndex < rightBound && source[leftIndex] > source[rightIndex])) {
buffer[i] = source[rightIndex++];
}
else {
buffer[i] = source[leftIndex++];
}
}
}
private static void bubleSort4(int[] source, int startingIndex) {
while (swap(source, 0, 1, startingIndex) |
swap(source, 1, 2, startingIndex) |
swap(source, 2, 3, startingIndex)
);
}
private static boolean swap(int[] source, int i, int j, int startingIndex) {
if(source[startingIndex + i] > source[startingIndex + j]){
int tmp = source[startingIndex + i];
source[startingIndex + i] = source[startingIndex + j];
source[startingIndex + j] = tmp;
return true;
}
return false;
}
}
</code></pre>
<h2>Testing program source code</h2>
<p><strong>Base test class</strong></p>
<pre><code>public abstract class ArraysTestBase {
protected int[][] buffer;
private final Random random = new Random();
public int numberOfTests = 100;
public int maxValue = 1000;
public int numberOfItems = 100;
protected void createBuffer() {
buffer = new int[numberOfTests][];
for (int i = 0; i < numberOfTests; i++) {
int[] list = new int[numberOfItems];
addRandomNumbers(list);
buffer[i] = list;
}
}
protected void createBuffer(int...parametes) {
buffer = new int[1][];
buffer[0] = parametes;
}
protected void addRandomNumbers(int[] list) {
for (int i = 0; i < numberOfItems; i++) {
int value = random.nextInt(maxValue);
list[i] = value;
}
}
protected int[][] cloneBuffer() {
int[][] clonedBuffer = new int[numberOfTests][];
for(int i = 0; i < buffer.length; i++){
int[] clonedList = new int[buffer[i].length];
int[] list = buffer[i];
for (int j = 0; j < list.length; j++) {
int element = list[j];
clonedList[j] = element;
}
clonedBuffer[i] = clonedList;
}
return clonedBuffer;
}
public abstract void test();
}
</code></pre>
<p><strong>Performance Test</strong></p>
<pre><code>public class ArrayPerformanceTest extends ArraysTestBase {
private final Timer timer = new Timer();
public void test() {
createBuffer();
timer.reset();
testSystem();
timeResoult("System");
timer.reset();
testMy();
timeResoult("My List");
}
public void test(int numberOfTests) {
long myTotalTime = 0;
long systemTotalTime = 0;
for(int i = 0; i < numberOfTests; i++){
createBuffer();
timer.reset();
testSystem();
long systemTime = timeResoult();
systemTotalTime += systemTime;
timer.reset();
testMy();
long myTime = timeResoult();
myTotalTime += myTime;
System.out.println("My Time / System Time = " + myTime + " / " + systemTime + " = \t" + ((double) myTime / systemTime));
}
System.out.println("My Time / System Time = " + ((double) myTotalTime / systemTotalTime));
}
private long timeResoult() {
return timeResoult(null);
}
private long timeResoult(String source) {
long time = timer.check();
if (source != null) {
System.out.println(source + ">\tTime: " + time);
}
return time;
}
private void testMy() {
int[][] buffer = cloneBuffer();
for (int i = 0; i < numberOfTests; i++) {
int[] list = buffer[i];
SortMerge4.sort(list);
}
}
private void testSystem() {
int[][] buffer = cloneBuffer();
for (int i = 0; i < numberOfTests; i++) {
int[] list = buffer[i];
Arrays.sort(list);
}
}
}
</code></pre>
<p><strong>Timer</strong></p>
<pre><code>public class Timer {
private long time;
public void reset(){
time = System.currentTimeMillis();
}
public long check(){
return System.currentTimeMillis() - time;
}
}
</code></pre>
<p><strong>Main</strong></p>
<pre><code>public static void main(String[] args) {
ArrayPerformanceTest testBasics = new ArrayPerformanceTest();
testBasics.numberOfTests = 1000;
testBasics.numberOfItems = 1000;
testBasics.maxValue = 1000000;
testBasics.test(1000);
}
</code></pre>
<h2>Why this testing is not really a test</h2>
<p>Well it's just give you the feeling weather my algorithm is really better, but to perform a true test, it need to be tested on different machines(64 bit/ 32 bit), the test need to explain when java jet is starting. The inputs need to be both equal redistributed numbers(like the random numbers in my test) and real world data. I been trying to make more serious analysis over this code but it's to complicate for me.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T11:14:25.930",
"Id": "81132",
"Score": "0",
"body": "I still think it's called merge sort and not marge sort. Also your caption does not mention anything of a bubblesort, and still I find a method with that name in your code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T11:18:14.063",
"Id": "81133",
"Score": "1",
"body": "@Vogel612 I use bubble sort for input of 4 parameters."
}
] | [
{
"body": "<p>This is a lot of code, and I can't cover it all. But I have a few observations:</p>\n\n<p>Your code is practically undocumented. Even for private methods, a short explanation would be useful. Especially when implementing a sorting algorithm, the documentation should also state algorithmic complexity guarantees – it would be very helpful to state that <code>merge</code> is <code>O(rightBound - startingIndex)</code> time and <code>O(1)</code> memory. In highly optimized, very clever code, I'd expect almost as much documentation as actual code.</p>\n\n<p>Now a focussed review on <code>bubleSort4</code>:</p>\n\n<p><code>bubleSort4</code> should be <code>bubbleSort4</code>. Spelling is important.</p>\n\n<p>Let's look at your code:</p>\n\n<pre><code>private static void bubleSort4(int[] source, int startingIndex) {\n while (swap(source, 0, 1, startingIndex) | \n swap(source, 1, 2, startingIndex) |\n swap(source, 2, 3, startingIndex)\n );\n}\n</code></pre>\n\n<p>This body-less <code>while</code> is quite unusual and why this is done isn't exactly obvious. The use of bitwise-or <code>|</code> instead of logical-or <code>||</code> is another subtle detail that really should be explained in a comment.</p>\n\n<p>The code could be made clearer by actually providing an empty body. I would also put the <code>|</code> at the front of each line:</p>\n\n<pre><code>while ( swap(source, 0, 1, startingIndex)\n | swap(source, 1, 2, startingIndex)\n | swap(source, 2, 3, startingIndex)\n) {\n // empty\n}\n</code></pre>\n\n<p>However, I would probably use a do-while loop instead:</p>\n\n<pre><code>boolean changed;\ndo {\n changed = false;\n changed |= swap(source, 0, 1, startingIndex);\n changed |= swap(source, 1, 2, startingIndex);\n changed |= swap(source, 2, 3, startingIndex);\n} while (changed);\n</code></pre>\n\n<p>This code makes it much more obvious</p>\n\n<ul>\n<li>why the loop will execute at least once,</li>\n<li>what the combined return values of <code>swap</code> mean, and </li>\n<li>why we should use <code>|</code> instead of <code>||</code>.</li>\n</ul>\n\n<p>We could now also inline <code>swap</code>:</p>\n\n<pre><code>/* Bubble-sort the four elements in \"source\" starting at \"offset\".\n * The calling code has to make sure that \"source.length - offset > 4\".\n * Because this runs on fixed-sized input, it will run in O(1) time.\n */\nprivate static void bubbleSort4(final int[] source, final int offset) {\n boolean changed = true;\n while (changed) {\n changed = false;\n\n // swap the three pairs 0-1, 1-2, 2-3 starting from \"offset\"\n for (int i = offset; i < offset + 3; i++) {\n if (source[i] > source[i + 1]) {\n int tmp = source[i];\n source[i] = source[i + 1];\n source[i + 1] = tmp;\n\n changed = true;\n }\n }\n }\n}\n</code></pre>\n\n<p>Note that this is the only use of <code>swap</code>, and that this inlining actually reduces overall complexity. Note that the bitwise-or has now been completely removed. The magic number <code>3</code> is explained by a comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:42:43.507",
"Id": "81137",
"Score": "0",
"body": "I had many tests on the bubbleSort4. Sorry for not documenting it. The use of change parameter actually have about 2% of performance. Any line in this code have millions of iterations. So it's all very important. I use '|' instead of '||' as '|' ensure that all the 3 methods been called even if one of them return true. Adding for in bubbleSort4 is also bad for performance. I try to add more documentations today to make it more clear."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:30:11.160",
"Id": "46452",
"ParentId": "46444",
"Score": "4"
}
},
{
"body": "<h2>Algorithms</h2>\n\n<p>I would also like to add couple observation on top of previous answers. I was slightly confused if you were really comparing your <strong>merge sort</strong> with the Arrays.sort(int[])?? The Arrays.sort(int[]) uses a different algorithm. Tuned <strong>quick sort</strong> according to a documentation <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html\" rel=\"nofollow\">Arrays doc</a></p>\n\n<p>So I have a feeling that you might be comparing two different algorithms.</p>\n\n<h2>Performance tests</h2>\n\n<p>Another observation that I found was that I would suggest to adjust the performance test. Firstly, for performance testing you should be using System.nanos(). System.currentMillis() dont have a milisecond precision, depends on a OS it could even have a 16ms interval of incrementing.</p>\n\n<p>Try to run the tests for a different size of the array. I notice you used always 100 items. I would suggest to try more such as 1K, 10K, 100K, 1M... This gives you a overview if the 10% speed up is always there or if, for example, with 1M you only get 1%. The reason why this is good to test is if you find that the speed up decreases with higher numbers then there is some constant overhead that is not connected to a number of items in the array. Which you might want to know. On the other hand if you know that your algorithm will be run for arrays of size around hundred this is a relevant performance test that gives you relevant results. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:24:04.650",
"Id": "46468",
"ParentId": "46444",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T10:45:13.583",
"Id": "46444",
"Score": "5",
"Tags": [
"java",
"mergesort"
],
"Title": "Racing Java Arrays.sort with NON recursive Merge Sort implementation"
} | 46444 |
<p>I'd like to add a bulk of items into a sparse array, starting at a certain index.
I came along this requirement in order to accomplish client side pagination while <strong>not retrieving all data from server</strong> (assuming server returns the <strong>right</strong> data, given the required indexes). </p>
<p>To keep right indexes when "Skipping" and "Taking", I need to store the items in a sparse array. Besides relevant indexes, other places in array might as well be <code>undefined</code>.</p>
<p>I wrote the following snippet of code, assuming <code>bulk</code> is the retrieved chunk of items from Server, and <code>index</code> is where the first item should be placed.</p>
<pre><code> items = new Array(totalItemsPossibleCount);
items = items.slice(-index)
.concat(bulk)
.concat(items.slice(index+bulk.length));
</code></pre>
<ol>
<li>Is there a shorter way to do so?</li>
<li>Can this be achieved with <a href="http://underscorejs.org/">underscore.js</a> in more readable way?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:37:47.617",
"Id": "81182",
"Score": "1",
"body": "Your problem starts with \"I need to store the items in a sparse array\". You really really don't need to store the items in a sparse array here. Sparse arrays are not just slow, they're also not really conceptually arrays. You can use an object as a map for example, or better yet have objects for pages and a non sparse array for those. Remember, you also have a bunch of other collections available at your disposal, a deque might be a good choice here too if users usually navigate to adjacent pages."
}
] | [
{
"body": "<p>You don't need to worry about sparse arrays in JavaScript and there is no need to instantiate with the Array constructor. If you insert into a random index then the rest of the array is just padded with <code>undefined</code> references:</p>\n\n<pre><code>var items = [];\nitems[5] = 'foo';\nconsole.log(items); // [5: \"foo\"]\nitems.toString(); // \",,,,,foo\"\n</code></pre>\n\n<p>To add new items into the middle of an array you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\" rel=\"nofollow\"><code>splice</code></a> function:</p>\n\n<pre><code>items.splice(index, 0, bulk);\n</code></pre>\n\n<p>The <code>index</code> is where to start adding items, <code>0</code> is how many items to remove after that point, and <code>bulk</code> is the new items to add at that point. Splice acts on the array directly, and returns any items that were removed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:40:58.967",
"Id": "81155",
"Score": "0",
"body": "That will work for a single item. I want to add a bulk which is **array of items**. I was using Array C'TOR to boost performance. I saw [here](http://stackoverflow.com/questions/7032550/javascript-insert-an-array-inside-another-array) you can use `splice` in the manner I'd love to. The latter actually answers my question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:08:12.293",
"Id": "81161",
"Score": "0",
"body": "@user40171 Sorry, yes you can use `apply` with the arguments in order to add an array."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:11:39.410",
"Id": "46450",
"ParentId": "46446",
"Score": "4"
}
},
{
"body": "<p>As <a href=\"https://codereview.stackexchange.com/a/46450/14370\">Jlivings points out</a>, <code>splice</code> is what you're looking for. To use it for multiple items you could conceivably use <code>apply</code>:</p>\n\n<pre><code>var args = [index, 0].concat(bulk);\nitems.splice.apply(items, args);\n</code></pre>\n\n<p><em>Edit:</em> Ah, shucks. Didn't see your comment on jlivings' answer; you obviously already found the same code solution over on SO.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-27T01:18:52.963",
"Id": "254902",
"Score": "0",
"body": "This doesn't work if index is greater than the array length. See http://stackoverflow.com/questions/34534295/can-array-splice-be-used-to-create-a-sparse-array-by-adding-an-element-at-an-i"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:06:15.970",
"Id": "46466",
"ParentId": "46446",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T11:33:38.383",
"Id": "46446",
"Score": "5",
"Tags": [
"javascript",
"pagination",
"underscore.js"
],
"Title": "Adding a bulk of items in the middle of a sparse array"
} | 46446 |
<p>I have been trying to learn C by making a Hangman game. It's not perfect, but with C, I worry that my coding practices will not be very good. I'm also new to allocating memory myself, so I feel I may have done something wrong there. I would very much appreciate reviews of my code.</p>
<p>The game takes in a text file with the first line of the file being a category and the rest of the file being words that can be used in the game: a random line is selected. The file address is in the arguments for the program. </p>
<pre><code>/* File: hangman.c
*
*
* This program implements the game, Hangman.
*
* Comments
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <dirent.h>
#include <sys/types.h>
int contains(char[], char, int);
char *hideWord(char []);
void changeWord(char [], char *, char);
void InitializeArray(char [], int);
void printHangMan(int, int);
void Engine(char [], char *);
void Clear();
void printSpace(int);
char *stringTrimmer(char *);
void printOneSpace(int);
char *Randomline(FILE *, char *);
char *Catergory(FILE *, char *);
void printTop();
void printWin(int, int);
void printLost(int, int);
void printRest(int, int, char [], char [], char []);
char **fileArray(char []);
int stringCont(char *, char *);
int menu();
void files();
#define Size 60
#define wordLength 30
int main(int argc, char *argv[])
{
FILE *ptrFile;
char input[5] = " ";
char *randomCat;
char *randomLine;
while (strcmp(input, "quit") != 0)
{
char address[Size]="0";
int menuChoice = menu();
if(menuChoice== 1)
{
char *i=argv[1];
randomLine = Randomline(ptrFile,i);
randomCat = Catergory(ptrFile,i);
}
else if(menuChoice == 2)
{
files(address);
randomLine = Randomline(ptrFile, address);
randomCat = Catergory(ptrFile, address);
system("clear");
}
Engine(p, r);
printf("\ntype menu to return to Menu type quit to quit\n");
scanf("%s", input);
system("clear");
}
return 0;
}
int menu(char *address)
{
char input[9];
printf("*******************************************\n");
printf("* *\n");
printf("* * * * * * * *\n");
printf("* * Play * *\n");
printf("* * * * * * * *\n");
printf("* *\n");
printf("* * * * * * * *\n");
printf("* * Files * *\n");
printf("* * * * * * * *\n");
printf("* *\n");
printf("* * * * * * * *\n");
printf("* * Rules * *\n");
printf("* * * * * * * *\n");
printf("* *\n");
printf("*******************************************\n");
scanf("%s",input);
if(strcmp(input,"play")==0||strcmp(input,"Play")==0)
{
system("clear");
return 1;
}
else if(strcmp(input,"Files")==0||strcmp(input,"files")==0)
{
return 2;
}
else
{
system("clear");
return 0;
}
return 0;
}
void files(char address[])
{
system("clear");
printf("*******************************************\n");
printf("* *\n");
printf("* *\n");
printf("* * * * * * * * * * * * * * * *\n");
printf("* * Type the path of a file.* *\n");
printf("* * Or path of a folder for * *\n");
printf("* * many files. * *\n");
printf("* * * * * * * * * * * * * * * *\n");
printf("* *\n");
printf("* *\n");
printf("* *\n");
printf("* *\n");
printf("*******************************************\n");
scanf("%s",address);
}
void Engine(char mysteryWord[], char *cat)
{
int Length = strlen(mysteryWord); //Length is made strlen() so its only called once
int catLength = strlen(cat);
int spaces = Length+3; // spaces incremented for better formatting
if (Length*2<catLength) // if mystery word is small the screen will be to small
{
spaces = catLength/2+3;
}
else if(Length<7)
{
spaces =10;
}
int lifeLost = 0;
char input = '\n'; // made to \n so it will be ignored later on
char *HiddenWords = hideWord(mysteryWord);
char wrongChars[11] = {' '}; //InitializeArray(wrongChars,11);
//While loop will stop if the user looses 10 lives or guesses all the letters
while (lifeLost < 10 && contains(HiddenWords, '_', Length * 2) > 0)
{
printTop(spaces);
printRest(spaces, lifeLost, cat, HiddenWords, wrongChars);
scanf("\n%c", &input); // /n*c added so that new line char is ignored when enter button is pressed
if (lifeLost < 10 && input != '\n') {
int occurances = contains(mysteryWord, input, Length);
if (occurances < 1)
{
wrongChars[lifeLost] = input;
lifeLost = lifeLost + 1;
}
else
{
changeWord(mysteryWord, HiddenWords, input);
}
}
system("clear");
}
if (lifeLost == 10) {
system("clear");
printLost(spaces, lifeLost);
} else
{
system("clear");
printWin(spaces, lifeLost);
}
}
/*Clear method maybe used as System("clear") is not portable
* and maybe be easily hacked by changing the clear program in memory
* but for this purpose System("clear") should hopefully suffice
*/
void Clear() {
for (int i = 0; i < 20; i++) {
printf("\n");
}
}
/*
* hideWord takes in the mysteryWord array and returns a new array pointer
* based on the hideWord array but with all the letter replaced to underscores
*
*
* every other element in the returned array is also made a space so the array can
* be printed correctly
*
* the new array has to be twice the length of the original because of the extra
* spaces.
* If a letter is found at the ith element in the mysteryWord at must be made an
* underscore in the hiddenWord at the i*2 element as even elements are spaces.
*
* spaces in the mysteryWord remain spaces in the hiddenWord they do not got made
* into underscores.
*/
char *hideWord(char mysteryWord[]) {
int length = strlen(mysteryWord);
char *word = malloc((length * 2));
if (!word) {
return NULL;
}
for (int i = 0; i < length * 2; i++) {
word[i] = ' ';
}
for (int i = 0; i <= length - 1; i++) {
if (mysteryWord[i] == ' ') {
word[i * 2] = ' ';
}
else if (isalpha(mysteryWord[i]) != 0) {
word[i * 2] = '_';
} else {
word[i * 2] = mysteryWord[i];
}
}
return word;
}
/*
* contains takes in the mysteryWord array,its length and the user input
* it returns how many times the input occurs in the array
*
*/
int contains(char mysteryWord[], char input, int arrayLength) {
int a = 0;
if(isalpha(input)==0 && input != '_')
{
return 2;
}
char flipInput;
;
if (isupper(input) != 0) {
flipInput = tolower(input);
} else {
flipInput = toupper(input);
}
for (int i = 0; i < arrayLength; i++) {
if (mysteryWord[i] == input || mysteryWord[i] == flipInput) {
a = a + 1;
}
}
return a;
}
/*changeWord takes in the user input
* The Mystery word p[]
* and the hidden word *a
// *
* for loop loops round the mystery word comparing every item to the input
* and if it is found it then displays the input in the hidden word array
*
* The first element in the Mystery word corresponds to the 1st in the hiddenArray
* But the 2nd element corresponds to the 3rd in the hiddenArray due to there being spaces
* in every other element;
* 0 1 2 3
*[B] [O] [B] [S] (Mystery word)p[]
*[_] [ ] [_] [ ] (Hidden word)*a
*
* if the user input O it would be found in the 1st element of the MysteryArray
* but would be added to the 2nd in the hiddenArray it is alway i*2
*
* If the user enter a lower case letter it is converted to an uppercase and
* then compared to the array if it finds a match it is added to the hiddenWord array
*
*If the user enters a uppercase letter is converted to a lowercase
*
*
*/
void changeWord(char mysteryWord[], char *hiddenWord, char input) {
char flipInput;
int mult;
int length = strlen(mysteryWord);
if (isupper(input) != 0) {
flipInput = tolower(input);
} else {
flipInput = toupper(input);
}
for (int i = 0; i < length; i++) {
if (mysteryWord[i] == input) // compares every element to user input
{
mult = i * 2;
hiddenWord[mult] = input;
} else if (mysteryWord[i] == flipInput) // compares element to lowered Input
{
mult = i * 2;
hiddenWord[mult] = flipInput;
}
}
}
/*Possible the worst looking function ever but it's fairly simple.
*
* due to the varying length of the mystery word different amounts of spaces need
* to be printed the function takes in the width of the game screen prints the
* corresponding amount of spaces.
*
* printHangMan takes in how many lives have been lost
* and then prints out the corresponding hangman drawing
*/
void printHangMan(int livesUsed, int length) {
switch (livesUsed) {
case 0:
printf(" * ");
printSpace(length - 2); // -2 because there is a * at either end
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
break;
case 1:
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printSpace(length - 2);
printf("\n");
printf(" * ");
printf(" ___________");
printSpace(length - 8); // less spaces need printing because of the underscores
printf("\n");
break;
case 2:
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 3:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ ");
printSpace(length - 5);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 4:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ | ");
printSpace(length - 7);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 5:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ | ");
printSpace(length - 7);
printf("\n");
printf(" * | 0 ");
printSpace(length - 7);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 6:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ | ");
printSpace(length - 7);
printf("\n");
printf(" * | 0 ");
printSpace(length - 7);
printf("\n");
printf(" * | | ");
printSpace(length - 7);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 7:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ | ");
printSpace(length - 7);
printf("\n");
printf(" * | 0 ");
printSpace(length - 7);
printf("\n");
printf(" * | |\\ ");
printSpace(length - 7);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 8:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ | ");
printSpace(length - 7);
printf("\n");
printf(" * | 0 ");
printSpace(length - 7);
printf("\n");
printf(" * | /|\\ ");
printSpace(length - 7);
printf("\n");
printf(" * | ");
printSpace(length - 4);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 9:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ | ");
printSpace(length - 7);
printf("\n");
printf(" * | 0 ");
printSpace(length - 7);
printf("\n");
printf(" * | /|\\ ");
printSpace(length - 7);
printf("\n");
printf(" * | \\ ");
printSpace(length - 7);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
case 10:
printf(" * _________ ");
printSpace(length - 8);
printf("\n");
printf(" * |/ | ");
printSpace(length - 7);
printf("\n");
printf(" * | 0 ");
printSpace(length - 7);
printf("\n");
printf(" * | /|\\ ");
printSpace(length - 7);
printf("\n");
printf(" * | / \\ ");
printSpace(length - 7);
printf("\n");
printf(" * ");
printf(" _|__________ ");
printSpace(length - 9);
printf("\n");
break;
}
}
/*
* countLetter takes in the mysteryWord its length
* and returns how many letters it contains
*/
int countLetter(char mysteryWord[], int length) {
int ret = 0;
for (int i = 0; i < length; i++) {
if (mysteryWord[i] != ' ') {
ret = ret + 1;
}
}
return ret;
}
/**
* Randomline function
* first finds the length of the file ptrFile.File length stored in 'count'
* Second creates a random number with a max value of 'count'.Random number called 'random'
* Third uses fseek function to go to postion of value 'random'.
* fseek may not have been at the begining of a line so it is the next line that is read.
*
* As I do not know how large the line is 60 is allocated to printLine.
* stringTrimmer() is called and returns a string without new line chars and of a correct size
* printLines memory is then freed as it is now needed anymore.
*
* tempLine reads the fraction of a line 'random' points to it is then freed.
*
* 'finalLine' is returned as it is the random line from the file which has been trimmer
*
*
* @param ptrFile
* @param address
* @return
*/
char *Randomline(FILE *ptrFile, char *address)
{
ptrFile = fopen(address, "r");
int count = 0;
char *append;
int random = 0;
char word[wordLength];
int c = 0;
int a = 0;
char *printLine = malloc(Size);
char *tempLine = malloc(Size);
char *finalLine;
fseek(ptrFile, 0, SEEK_END);
count = ftell(ptrFile);
srand(time(NULL));
random = rand() % count;
fseek(ptrFile, random, SEEK_SET);
fgets(tempLine, 60, ptrFile); // skip a line incase random place is in middle of line
fgets(printLine, 60, ptrFile);
fclose(ptrFile);
finalLine = stringTrimmer(printLine); // memory allocated in function is free in main method
free(printLine);
return finalLine;
}
/**
* This function basically reads in a text file and returns the first line
* of that file.
* @param ptrFile-This is a pointer to where the file is.
* @param address - This is the address of the file needed to open ptrFile.
* @return - The function returns the first line of the file.
*/
char *Catergory(FILE *ptrFile, char *address) {
ptrFile = fopen(address, "r");
char *ret = malloc(Size);
char *finalLine;
fgets(ret, 60, ptrFile);
fclose(ptrFile);
for (int i = 0; i < 60; i++) {
if (ret[i] == '\n') {
ret[i] = '\0';
}
}
finalLine = stringTrimmer(ret);
return finalLine;
}
/**
* due to the varying length of the mystery word different amount of spaces
* have to printed on each line this function stops the Engine() from become to big
* @param number
*/
void printSpace(int number) {
for (int i = 0; i < number; i++)
{
printf(" ");
}
printf("*");
}
/**
* due to the varying length of the mystery word different amount of spaces
* have to printed on each line this function stops the Engine() from become to big
* @param number
*/
void printOneSpace(int number) {
for (int i = 0; i < number; i++)
{
printf(" ");
}
printf("*");
}
/**
*
* @param input
* @return
*
* stringTrimmer takes in a string that has been read from a file
* and creates a new string without the newline that has been read from the file
* also the amount of space allocated to the line read in is 60
* this creates a string with correct memory allocation.
*
*/
char *stringTrimmer(char *input) {
int counter = 0;
int size = strlen(input);
int a = 0;
while (isprint(input[counter]))
{
counter++;
}
char *output = malloc(counter + 1);
for (int i = 0; i <= size; i++) {
if (isprint(input[i]) && a < counter) {
output[a] = input[i];
a++;
}
}
output[counter + 1] = '\0';
return output;
}
/**
*
* @param spaces
* printTop prints everything on the screen up until
* the hangman figure
*/
void printTop(int spaces) {
printf(" ");
for (int i = 0; i < spaces; i++)
{
printf("* ");
}
printf("\n");
printf(" * HangMan ");
for (int i = 0; i < spaces - 8; i++) {
printf(" ");
}
printf("*\n");
printf(" * ");
printSpace(spaces - 2);
printf("\n");
}
/**
*
* @param spaces
* @param lifeLost
* Screen is to show when the user has won
*/
void printWin(int spaces, int lifeLost) {
printTop(spaces);
printHangMan(lifeLost, spaces);
printf(" * ");
printSpace(spaces - 2);
printf("\n");
printf(" * ");
printSpace(spaces - 2);
printf("\n");
printf(" * You Win! ");
printSpace(spaces - 8);
printf("\n");
printf(" * ");
printSpace(spaces - 2);
printf("\n");
printf(" ");
for (int i = 0; i < spaces; i++) {
printf("* ");
}
}
/*The printLost method takes in the amount of spaces and the lifeLost
*Its function is to print out the screen when user has lost
*/
void printLost(int spaces, int lifeLost) {
printTop(spaces);
printHangMan(lifeLost, spaces);
printf(" * ");
printSpace(spaces - 2);
printf("\n");
printf(" * ");
printSpace(spaces - 2);
printf("\n");
printf(" * You Lose! ");
printSpace(spaces - 8);
printf("\n");
printf(" * ");
printSpace(spaces - 2);
printf("\n");
printf(" ");
for (int i = 0; i < spaces; i++) {
printf("* ");
}
}
void printRest(int spaces, int lifeLost, char cat[], char HiddenWords[], char wrongChars[]) {
printHangMan(lifeLost, spaces);
printf(" * %s ", wrongChars);
if (lifeLost > 0) printf(" ");
printOneSpace(((spaces - 3)*2) - lifeLost);
printf("\n * ");
printSpace(spaces - 2);
printf("\n * %s ", cat);
printOneSpace((spaces - strlen(cat))*2+1);
printf("\n * %s",HiddenWords);
printOneSpace((spaces*2-strlen(HiddenWords)-4));
printf("\n");
printf(" ");
for (int i = 0; i < spaces; i++)
{
printf("* ");
}
}
int isFile(FILE *fptr, char *address) {
fptr = fopen(address, "r");
if (fptr == NULL) {
return 1;
} else {
fclose(fptr);
return 0;
}
}
char **fileArray(char address[])
{
DIR *dir;
struct dirent *entry;
static char *a[10];
if ((dir = opendir(address)) == NULL) {
perror("opendir() error");
} else {
puts("contents of root:");
for (int i = 0; ((entry = readdir(dir)) != NULL) && i <= 10; i++) {
if (stringCont(".txt", entry->d_name) == 1)
{
a[i] = entry->d_name;
printf("%s \n", a[i]);
}
}
closedir(dir);
}
return a;
}
/*/
*
* Check if str2 contains str1
* return 1 if true
*/
int stringCont(char *str1, char *str2) {
int str2Len = strlen(str2);
int counter = 0;
int str1Len = strlen(str1);
for (int i = 0; i < str2Len; i++) {
counter = i;
for (int a = 0; str1[a] == str2[counter]; a++) {
counter++;
}
if ((counter - i) > str1Len) {
return 1;
}
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>There's a lot of code here (the poor indentation in making it harder to read), but I'll skim through and recommend several things I've found.</p>\n\n<ul>\n<li><p>Some of your indentation is off. Remember to have all code within curly braces indented, preferably by four spaces. More importantly, keep this <em>consistent</em> throughout the program.</p></li>\n<li><p>You're mixing lowercase and uppercase naming with your functions. Choose only one and <em>keep it consistent</em>. Lowercase is common for functions in C, but it's mostly personal preference.</p></li>\n<li><p>You can eliminate <em>all</em> of those function prototypes by defining <code>main()</code> below the others. This works because <code>main()</code> will already be aware of their definitions when calling them.</p></li>\n<li><p>Your large hard-coded displays clutter up your code and are not necessary for a console program. Just a simple menu for the user will work.</p></li>\n<li><p><code>printHangMan()</code> is <em>really</em> long and should be simplified if you still want such an output.</p></li>\n<li><p>Prefer to call <code>srand()</code> at the top of <code>main()</code>. This will make it easy to maintain and will ensure that it's called only once. If called multiple times, it reset the seed each time, resulting in the \"same\" random values when calling <code>rand()</code>.</p></li>\n<li><p>I don't think your space-printing functions are necessary, or at least <code>printOneSpace()</code> (you could just output this inline). You shouldn't output a lot of spaces if it'll clutter up your code and output.</p></li>\n<li><p>For printing an <em>unformatted</em> line that should also end with a newline, use <code>puts()</code> instead of <code>printf()</code>. For similar lines <em>without</em> a newline, use <code>fputs()</code>. More info about that <a href=\"https://stackoverflow.com/questions/2454474/what-is-the-difference-between-printf-and-puts-in-c\">here</a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:05:07.653",
"Id": "46500",
"ParentId": "46453",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T13:21:15.517",
"Id": "46453",
"Score": "5",
"Tags": [
"c",
"game",
"memory-management",
"console",
"hangman"
],
"Title": "My HangMan Game"
} | 46453 |
<p>As you're probably aware, PHP doesn't support type hinting for scalar types.
I feel this might be good practice to build into my framework, although I'm aware some of you might disagree seeing as PHP is a loosely-typed language.</p>
<p>But I'd like some feedback on the implementation of this.
Do you think it's efficient, pointless? Or could it be achieved in a better way?</p>
<p>This works by causing an error.
By specifying a typehint (integer), PHP is expecting a class/object called "integer", so it's giving an error as we are passing a "real integer"/scalar value".</p>
<p>Giving this error,</p>
<blockquote>
<p>Argument 1 passed to <code>test()</code> must be an instance of integer, integer given.</p>
</blockquote>
<p>So with a custom error handler function, I can use preg_match() to find the expected & given types, and just compare them via the name.</p>
<h2>The code</h2>
<pre><code><?php
ini_set('display_errors', 'on');
error_reporting(E_ALL);
function typehint($level, $message){
if($level == E_RECOVERABLE_ERROR){
if(preg_match('/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/', $message, $match)){
if($match[4] == $match[5]){
return true;
}
}
}
return false;
}
set_error_handler('typehint');
function test(integer $value){
var_dump($value);
}
for($int = 0; $int < 1000; $int++){
test(23);
}
?>
</code></pre>
<p>It seems to work ok, but I'm not sure if using <code>preg_match()</code> on every function argument is a good idea?</p>
<p>Here's the benchmarks, on 1000 function calls. (1 typeint per function)</p>
<pre><code>Type-hinting No Type-hinting
0.015 0.0017
0.0169 0.002
0.0172 0.002
0.0148 0.0019
0.0159 0.0029
0.0157 0.0019
0.0149 0.0018
0.0161 0.0029
0.0167 0.002
0.0173 0.0018
0.0149 0.0019
0.0156 0.0019
0.0153 0.0029
0.0182 0.0023
0.0151 0.0029
0.0163 0.0017
0.0179 0.0018
0.0159 0.0018
0.0154 0.0027
0.0149 0.0023
Average Average
0.016 0.002155
</code></pre>
<p>So just after some thoughts on this really... good or bad?</p>
<p><strong>EDIT:</strong>
Using <code>strstr()</code> seems to be a little quicker, although I have to specify what types to check for. Which is a small number anyway. Average time: 0.009595.</p>
<pre><code>function typehint($level, $message){
if($level == E_RECOVERABLE_ERROR){
$integer = 'must be an instance of integer, integer given';
$string = 'must be an instance of string, string given';
if(strstr($message, $integer) !== false OR strstr($message, $string) !== false){
return true;
}
}
return false;
}
</code></pre>
| [] | [
{
"body": "<p><em>\"So just after some thoughts on this really... good or bad?\"</em></p>\n\n<p>Bad, really bad, I'm afraid. You're trying to make the language do something it doesn't <em>want</em> to do, or even: can't do. You're gluing feathers to a fish's fins, and throwing it up into the air, so it can mimic a bird's behaviour.<br>\nYour test code shows a <em>dramatic</em> decrease of speed (after switching to <code>strstr</code>, still ~5 times slower than usual). And you're only testing your code with <strong>valid</strong> input. Besides, have you even checked if you can get this function to return what it needs to return, and to <em>Where</em>?</p>\n\n<p>The simple fact of the matter is this: <em>each</em> function call with your improvised (hacked) type-hints will issue an error, even if the type is correct.<Br>\nIt will, however, issue a notice in these cases, too:</p>\n\n<pre><code>function test(integer $foo)\n{\n return $foo;\n}\ntest('123');\n</code></pre>\n\n<p>How will you recover from this error? Are you going to add:</p>\n\n<pre><code>if (settype($argument, $expected) == $argument)\n{\n call_user_func_array($function, array($argument));\n}\n</code></pre>\n\n<p>to your error handler? and how are you going to deal with functions that take arrays of ints, or what if the user passes <code>null</code>?<Br>\nThere's just too many things to consider here.</p>\n\n<p>Your approach also poses problems when you scale things up a little: Have you thought about what would happen if you used this code in tandem with a framework, that uses namespaces, sets all sorts of handlers all over the place, and uses complicated autoloading trickery?<br>\nEven simple autoloading would mean that PHP sets out to look for this <code>integer</code> class. That means calling the autoloader, when that turns out to be unsuccessfull, PHP will of course use the include paths, and a lot of I/O disk access is the result. Disk I/O is a speed killer, as we all know.</p>\n\n<p>Note that lookups of files that aren't found <em>are not cached!</em>, so each type-hint <strong><em>will</em></strong> result in disk access. Whomever is hosting this code, if it ever got used in even a medium traffic site, will <em>not</em> be happy.<br>\nPerhaps this has changed with PHP5.5, but most hosting services are yet to upgrade.</p>\n\n<p>Each function call, in your simple example, is already approx. 5 times slower than a normal one. Add the overhead of a custom autoloader, several layers of error/exception handlers to that, and you'll see the avg time per function call drop even more (probably converging on the initial times you had). Simply because autoloaders often access the disk, too, with <code>file_exists</code> calls, using the include path to scan for files who's name resembles that of the class that needs to be loaded, only to fail, and have PHP do the same disk operations again.<Br>\nThen, like the example I listed: getting ints from a db, or user input means that these numbers are all passed around as strings, but are perfectly castable/usable as integers.</p>\n\n<p>Suppose you were able to get the called function, cast the arguments accordingly and call the function again, what would happen? Well, the function gets called again, so another error is triggered, and your handler, which is now the caller of the function will be called twice.<br>\nOf course, the second time, owing your intervention, the types will match this time, but that's <em>4</em> function calls (5 including <code>call_user_func_array</code>) + 2 errors being raised to complete a single call:</p>\n\n<pre><code>Original caller /->fails, PHP====\\\\\n \\\\ //``!AUTOLOADER!``<=\\\\ ||\n \\\\ || \\\\ \\/\n \\=======> function -------> error \\==>DISK I/O !!TWICE!! per call\n \\| /\\ \\\\\n ?? || \\==> handler, type checking + casts\n || || || /\\\n || ||call_user_func_array|| |\n ?? |======================| |\n || \\\\ error2 |\n || \\----------------------\n || ||\n ?? \\/\n || suppose it returns, still disk I/O and\n || ||\n || good luck getting back there //\n \\\\=========================================/\n</code></pre>\n\n<p>An that's just assuming no intern gets the brilliant brain-wave to actually create a <code>string</code> or <code>integer</code> class or interface!</p>\n\n<p>Even if you manage to get all of this working, a recoverable error isn't <em>guaranteed</em> to have anything to do with your special-case type-hints. Your handler was created with a specific type of error in mind, which -logic dictates- should be an <code>E_USER_NOTICE</code>.</p>\n\n<p>Of course, you can't force the language to emit such an error when a non-custom error is encountered.</p>\n\n<p>Ah well, you could try to work on this a bit more, if you want to, but I'd say you're better of spending that time to refactoring your functions like so:</p>\n\n<pre><code>/**\n * my test func - EXPECTS INTEGER\n * Any decent IDE uses these doc-blocks\n * @param int $integer\n * @return int\n **/\nfunction test($int)\n{\n $int = (int) $int;//cast to be sure\n //code\n return ++$int;\n}\n</code></pre>\n\n<p>That'd be a better way to spend your time, and just ensure people you work with have a decent IDE, that parses the doc-blocks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T13:46:05.767",
"Id": "46551",
"ParentId": "46458",
"Score": "7"
}
},
{
"body": "<p>Yes, Now its possible, After a long discussion, a proposal to implement type hinting for scalar function parameters and return values was just approved with the highest vote count so far, check for details :</p>\n\n<p>Scalar type hinting consists of declaring the types of function parameters and return values that can be of the types int, float, string and bool.This allows the PHP runtime engine to check if the types of values passed to parameter functions and return values are of the expected types in order to detect eventual programming mistakes. Type hinting for objects, arrays and callables was already allowed in past PHP versions. The current implementation introduces five new reserved words: int, float, bool, string and numeric. These were not previously reserved, because casting is a special case in the lexer.</p>\n\n<pre><code>Example :\nfunction test(float $a) {\n var_dump($a); \n}\n\ntest(1); // float(1)\ntest(\"1\"); // float(1)\ntest(1.0); // float(1)\ntest(\"1a\"); // E_RECOVERABLE_ERROR\ntest(\"a\"); // E_RECOVERABLE_ERROR\ntest(\"\"); // E_RECOVERABLE_ERROR\ntest(1.5); // float(1.5)\ntest(array()); // E_RECOVERABLE_ERROR\ntest(new StdClass); // E_RECOVERABLE_ERROR\n</code></pre>\n\n<p>You have also an option to declare into source file where you can allow Scaler type hinting.It must be 1st line of your config script and can’t be declared elsewhere in the same file.</p>\n\n<p>Like : declare(strict_types=1);\nAt runtime, when the PHP engine tries to return a value, it will check if doesn’t match as declared it will throw a fatal error like, Fatal error: Argument 1 passed to increment() must be of the type integer, string given</p>\n\n<p>With this new features of declaration, you can write more robust applications by detecting early programming mistakes caused by passing values of the wrong types to functions.</p>\n\n<p>Automatic changes of types may also happen. For example, int types can be change into float type parameters automatically,</p>\n\n<pre><code>function test(float $x){\n var_dump($x);\n}\ntest(10); // works fine\n</code></pre>\n\n<p>Declaring the Return Type</p>\n\n<p>We can declare the return types adding a colon followed by the expected type between the last parenthesis and the first bracket in the function declaration.</p>\n\n<p>For functions that do not return any value, nothing should be added in the return type declaration section.</p>\n\n<pre><code>function mustReturnInt(): int { ... }\nfunction mustReturnString(): string { ... }\nfunction mustReturnBool(): bool { ... }\nfunction mustReturnFloat(): float { ... }\nfunction doesNotReturnAnything() { ... }\n</code></pre>\n\n<p>A Little Bit more Complex Example</p>\n\n<pre><code>declare(strict_types=1); \nclass StrictTypesTestingClass { \npublic function returnSameInt(int $value): int { return $value; } \npublic function returnSameFloat(float $value): float { return $value; } \npublic function returnSameString(string $value): string { return $value; } \npublic function returnSameBool(bool $value): bool { return $value; } } \n$check = new StrictTypesTestingClass(); // calls that work print $check->returnSameInt(10); \nprint $check->returnSameFloat(10.0); \nprint $check->returnSameString(\"test\"); \nprint $check->returnSameBool(true) ? 'true' : 'false'; // calls that throw exceptions \nprint $check->returnSameInt(\"10\"); \nprint $check->returnSameFloat(\"10.0\"); \nprint $check->returnSameString(10);\nprint $check->returnSameBool(\"true\");\n</code></pre>\n\n<p>Behavior of Weak Type Checking and Type Conversion : The weak type checking mode can be used with the statement declare(strict_types=0); or the absence of the strict types declaration. There are a few of points to take into account: Weak type checked calls to an extension or built-in PHP function have the same behaviour as in previous PHP versions The weak type checking rules for new scalar type declarations are mostly the same as those of extension or built-in PHP functions. NULL is a special case in order to be consistent with the current type declarations for classes, callables and arrays. NULL is not accepted by default, unless it is a parameter and is explicitly given a default value of NULL, for instance: <code>function sample(int $a = NULL);</code></p>\n\n<p>There are a lots of advantages to this approach. You get type safety. Which means that you can finally statically analyze code! You can detect bugs where you accidentally take a string from one function and pass it as an integer to another.For me, a developer that uses PHP on a daily basis and sees Java as a reference for OOP languages, this is great progress for PHP.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-23T07:57:14.237",
"Id": "152560",
"Score": "1",
"body": "Great to see that scalar type-hinting is coming, but would you mind awfully linking to the actual proposal/vote page, so people can read what was discussed, and can see when it'll be added (probably PHP-NG/PHP7, but who knows...)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-23T07:38:51.973",
"Id": "84771",
"ParentId": "46458",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T14:00:31.307",
"Id": "46458",
"Score": "2",
"Tags": [
"php"
],
"Title": "Type hinting for scalar types"
} | 46458 |
<p>I was given a task where given a string of '0's and '1's, return the longest substring where the count of '0's and '1's are equal. I was told also that the code should be <em>O(n)</em> and space <em>O(1)</em>. </p>
<p>Below is what I came up with:</p>
<pre><code>def max_equal_sub(s):
'''
I get the substrings by iterating over the starts and the ends for each start. For each
of these, check if the counts are equal.
'''
return max((s[b:e] for b in range(len(s)) for e in range(b, len(s)) if s[b:e].count('1') == s[b:e].count('0')), key=len)
def main():
TESTS = ('000', '1111', '001010101', '0001010101', '01010101', '000000111010101',
'0000001110101011', '00000011101010111111111111111')
for binstr in TESTS:
print(max_equal_sub(binstr))
if __name__ == '__main__':
main()
</code></pre>
<p>This code is all working fine, but I was told that this runs at <em>O(n<sup>2</sup>)</em>, not <em>O(n)</em>. </p>
<p>Following that I have some questions:</p>
<ol>
<li>What makes it <em>O(n<sup>2</sup>)</em>, and how can I make it so that it is <em>O(n)</em>.</li>
<li>I was told that it needed to be 'space <em>O(1)</em>'. Does it run at that? What would make it run at space O(1) and why?</li>
<li>In the function <code>max_equal_sub</code>, would it be more efficient to put <code>len(s)</code> into a variable to avoid calling it again and again?</li>
<li>In the function <code>max_equal_sub</code>, I do <code>s[b:e]</code> three times. Surely there is a more efficient way?</li>
</ol>
<hr>
<p>(Optional, but favoured):</p>
<ul>
<li>Are there any other things I could do to make it faster?</li>
<li>You could make it PEP8-compliant along the way if you wish.</li>
<li>Any other recommendations, perhaps regarding program logic.</li>
</ul>
| [] | [
{
"body": "<p>Taking this from an algorithmic perspective, rather than a python perspective (I don't know python well enough to write something sensible in it).</p>\n\n<p>Your algorithm can be expressed as the logic:</p>\n\n<ol>\n<li>Create a virtual list of balanced strings</li>\n<li>Starting from every position in the input string...\n<ol>\n<li>find every substring from that point.</li>\n<li>check to see whether that substring is balanced</li>\n<li>if it is balanced, add it to the virtual list.</li>\n</ol></li>\n<li>from the virtual list, pull the longest substring.</li>\n</ol>\n\n<p>Assuming the list remains virtual (yielded instead of real), then your algorithm is essentially space-complexity <em>O(1)</em>. If the virtual list is really generated, then the space complexity is <em>O(n<sup>2</sup>)</em></p>\n\n<p>The time complexity is something more than <em>O(n<sup>2</sup>)</em>. Probably closer to <em>O(n<sup>3</sup>)</em>. For each <code>b</code> value ( <em>O(n)</em> ) you find all <code>e</code> values (also <em>O(n)</em> ), and then after doing that, you count each 1 and each 0, which is another two <em>O(n)</em> operations.</p>\n\n<p>So, your code runs at <strong><em>O(n<sup>3</sup>)</em></strong> not <em>O(n<sup>2</sup>)</em></p>\n\n<p>Code Review is not really about helping you rewrite the code, but, there are some changes I can recommend...</p>\n\n<p>Firstly, in complexity analysis, doing two <em>O(n)</em> operations one after the other, is still time-complexity of <em>O(n)</em> ( time complexity of <em>O(n)</em> means that if you double the size of the input data, the time to execute will double.... and that is true if you have 1 <em>O(n)</em> operation or 100 <em>O(n)</em> operations one after the other).</p>\n\n<p>Use this to your advantage.</p>\n\n<p>I can't spend the time to do it all for you, and I am not even certain how to arrive at a fully <em>O(n)</em> solution, but the process you should probably follow is:</p>\n\n<ol>\n<li>scan all the characters once, and count the 1's and count the 0's - <em>O(n)</em></li>\n<li>find out which one is more common (difference between overall counts) - <em>O(1)</em>\n<ul>\n<li>call the common character C</li>\n<li>call the uncommon character U</li>\n</ul></li>\n<li>scan all characters again, and calculate - <em>O(n)</em>\n<ul>\n<li>where the longest sequence of C's is, and how long it is</li>\n</ul></li>\n<li><p>scan all the characters again, and count the number of U characters before, and after the longest C sequence. <em>O(n)</em></p></li>\n<li><p>Decide whether it is possible to contain the complete longest C sequence in the result. </p></li>\n<li>..... from here it gets fuzzy, and I m not sure you can keep it to <code>O(n)</code>, but you get the idea.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:09:50.803",
"Id": "46462",
"ParentId": "46459",
"Score": "3"
}
},
{
"body": "<p>You Could just loop once over the array, starting with a net count 0 and then incrementing by 1 if 1, else decrementing it by 1.</p>\n\n<p>First create an empty map, then do the loop:\nAt each point in the loop, after updating the net count check if it exists in the map,</p>\n\n<p>If it does not exist\n add it to the map with key =net_count and value=the current index.</p>\n\n<p>If it does exist, then calculate</p>\n\n<pre><code>dist = current_index - map[net_count]\nIf dist > current_maximum\n current_maximum = dist\n</code></pre>\n\n<p>This would be O(n) in time and in space O(1) in the best case (a 0 1 0 1) in the best case, in the worst case it would be O(n) when all zeroes our ones, on average it is as Janne Karila points out approximately 1.6 * sqrt(n) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:06:48.660",
"Id": "81338",
"Score": "0",
"body": "That would probably be log n memory on average."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:20:27.970",
"Id": "81359",
"Score": "0",
"body": "Thank you Suor, I am not sure, you are possible right indeed. It would be great if someone could share more light on this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:08:29.430",
"Id": "81374",
"Score": "1",
"body": "My experimental result is that the average final size of the dict is approximately 1.6 * sqrt(n)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T07:39:35.900",
"Id": "81884",
"Score": "0",
"body": "Square root makes sense if you compare this to brownian motion."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:39:10.920",
"Id": "46548",
"ParentId": "46459",
"Score": "2"
}
},
{
"body": "<p>This is time O(n) and space O(1). I was going to describe the algorithm, but seeing the code is easier.</p>\n\n<p>(forgive any clumsy python - I'm a Java dev):</p>\n\n<pre><code>def longestBalancedSubstring(input) :\n\n zerocount = onecount = max = 0\n previous = input[0]\n i=0\n\n while i < len(input):\n current = input[i]\n if(current==previous):\n if(current=='0'):\n zerocount = zerocount + 1\n else:\n onecount = onecount + 1\n if(min(zerocount, onecount) > max):\n max = min(zerocount, onecount)\n result = input[i-(max*2)+1:i+1]\n if(current!=previous):\n if(current=='0'):\n zerocount = 1\n else:\n onecount = 1\n previous = input[i]\n i = i+1\n return result \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T06:01:08.857",
"Id": "81448",
"Score": "0",
"body": "Returns `11` for `0110`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:23:51.127",
"Id": "81676",
"Score": "0",
"body": "This solution achieves O(1) space complexity by only keeping count of *consecutive* zeros and ones before the current position. It cannot find substrings with interspersed zeros and ones. (Also, there are bugs in corner cases, but those could be fixed)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:47:49.023",
"Id": "46599",
"ParentId": "46459",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T14:28:33.340",
"Id": "46459",
"Score": "8",
"Tags": [
"python",
"optimization",
"algorithm",
"strings",
"complexity"
],
"Title": "Longest 'balanced' substring"
} | 46459 |
<blockquote>
<p>Write a program to do addition of intervals to an interval store.</p>
<p>An interval is represented by an array of two elements - the lower and
the upper bound (you can assume integers). Assume that intervals are
constructed properly (e.g. the lower bound is not greater than the
upper bound, etc.).</p>
<p>Implement the #add method that will add a new interval, handling the
merges properly.</p>
<p>Example:</p>
<pre><code>> store = IntervalStore.new
[]
> store.add(1, 2)
[[1, 2]]
> store.add(5, 6)
[[1, 2], [5, 6]]
> store.add(1, 4)
[[1, 4], [5, 6]]
> store.add(1, 2)
[[1, 4], [5, 6]]
> store.add(3, 5)
[[1, 6]]
> store.add(0, 7)
[[0, 7]]
</code></pre>
</blockquote>
<p>Here is my Python code. It works but is not perfect.</p>
<pre><code>class IntervalStore(object):
def __init__(self):
self.store = []
def filter_result(self, flatten_store, low_index, upp_index):
useless_values = filter(lambda value: low_index < flatten_store.index(value) < upp_index, flatten_store)
flatten_store = filter(lambda value: value not in useless_values, flatten_store)
self.store = []
for i, k in zip(flatten_store[0::2], flatten_store[1::2]):
self.store.append([i, k])
def add(self, low, upp):
flatten_store = [number for pair in self.store for number in pair]
low_index, upp_index = self.index_of(low, flatten_store), self.index_of(upp, flatten_store)
if low_index >= 0 and upp_index >= 0:
if low_index % 2 != 0:
low_index -= 1
if upp_index % 2 == 0:
upp_index += 1
elif low_index >= 0 > upp_index:
if low_index % 2 != 0:
low_index -= 1
flatten_store.append(upp)
flatten_store = sorted(flatten_store)
upp_index = self.index_of(upp, flatten_store)
if upp_index % 2 != 0:
upp_index += 1
elif low_index < 0 <= upp_index:
if upp_index % 2 == 0:
upp_index += 1
flatten_store.append(low)
flatten_store = sorted(flatten_store)
low_index = self.index_of(low, flatten_store)
if low_index % 2 != 0:
low_index -= 1
upp_index += 1
else:
flatten_store.append(low)
flatten_store.append(upp)
flatten_store = sorted(flatten_store)
low_index, upp_index = self.index_of(low, flatten_store), self.index_of(upp, flatten_store)
if low_index % 2 != 0:
low_index -= 1
if upp_index % 2 == 0:
upp_index += 1
self.filter_result(flatten_store, low_index, upp_index)
def index_of(self, value, list):
try:
return list.index(value)
except ValueError:
return -1
</code></pre>
<p>same as Ruby code:</p>
<pre><code>class IntervalStore
def initialize
@store = []
end
def to_s
"[#{@store.map{ |i| "[#{i.first}, #{i.last}]" }.join(', ')}]"
end
# TODO - implement this method
def add(low, upp)
flatten_store = @store.flatten
low_index, upp_index = flatten_store.index(low), flatten_store.index(upp)
if low_index and upp_index
low_index -=1 if low_index.odd?
upp_index +=1 if upp_index.even?
elsif low_index and !upp_index
low_index -= 1 if low_index.odd?
(flatten_store << upp).sort!
upp_index = flatten_store.index(upp)
upp_index += 1 if upp_index.odd?
elsif !low_index and upp_index
upp_index += 1 if upp_index.even?
(flatten_store << low).sort!
low_index = flatten_store.index(low)
low_index -= 1 if low_index.odd?
upp_index += 1
else
(flatten_store << low << upp).sort!
low_index, upp_index = flatten_store.index(low), flatten_store.index(upp)
low_index -= 1 if low_index.odd?
upp_index += 1 if upp_index.even?
end
filter_result = filter_store(flatten_store, low_index, upp_index)
format_result(filter_result)
end
def format_result(rest)
@store = []
rest.each_slice(2) { |pair_values| @store << pair_values }
@store
end
def filter_store(flatten_store, low_index, upp_index)
flatten_store.clone.delete_if do |value|
flatten_store_index = flatten_store.index(value)
low_index < flatten_store_index and flatten_store_index < upp_index
end
end
end
</code></pre>
<p>I want to know how you would do it in other ways to make it smarter.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:02:28.967",
"Id": "81191",
"Score": "5",
"body": "In the future, please consider asking about [tag:python] and [tag:ruby] in separate questions that mention each other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T07:32:31.137",
"Id": "81276",
"Score": "3",
"body": "An important question would be how efficient you want this to be. Trivial implementations using arrays are pretty slow; more sofisticated solutions use interval trees (http://en.wikipedia.org/wiki/Interval_tree)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:07:49.923",
"Id": "82247",
"Score": "0",
"body": "@tokland That should be an answer!"
}
] | [
{
"body": "<p>If you have range [a,b], and want to add a range [c,d], there are 6 possible scenarios if you make the assumption, <code>a < b, c < d</code></p>\n\n<pre><code>b < c - undershoot\na < c, b >= c, b <= d - left overlap\na <= c, b >= d - total overlap\na >= c, b <= d - subsection\na > c, b > d - right overlap\na > d - overshoot\n</code></pre>\n\n<p>The first and the last cases simply add a new range, while left/right/total overlap edit the current range... and subsection can be ignored.</p>\n\n<p>My solution is to edit the function add, such that it follows this algorithm:</p>\n\n<ul>\n<li>1 - look at all ranges </li>\n<li>2 - if subsection found return </li>\n<li>3 - if left/right/total overlap found remove the current range being evaluated from the range list, merge the two ranges, then call add with the larger range.</li>\n<li>4 - if ends up being an over/under shoot for all ranges, add the range</li>\n</ul>\n\n<p></p>\n\n<pre><code>class IntervalStore(object):\n def __init__(self):\n self.range_list = []\n def __str__(self):\n return str(self.range_list)\n\n def __repr__(self):\n return str(self)\n\n def add(self, low, high):\n for interval in self.range_list:\n if interval[0] <= low and interval[1] >= high:\n return\n if interval[0] > high or interval[1] < low:\n continue\n else:\n self.range_list.remove(interval)\n self.add(min([interval[0], low]), max([interval[1], high]))\n return\n if len(self.range_list) == 0:\n self.range_list.append( [low, high])\n else:\n insert_index = 0\n while insert_index < len(self.range_list) and high > self.range_list[insert_index][0]:\n insert_index += 1\n self.range_list.insert(insert_index, [low, high])\n</code></pre>\n\n<p><strong>EDIT</strong> If you wanted to avoid an error regarding <code>low > high</code> input, then add\n<code>low, high = sorted([low,high])</code> at the beginning of the <code>add</code> function.</p>\n\n<p>Also add <code>if low == high: return</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:49:36.367",
"Id": "81224",
"Score": "0",
"body": "Good analysis! However, I wouldn't do the `if low==high: return` thing because it could be used for single element : [i, i] = {i}. Also, if i were you I'd write the inside of the loop without a continue as it seems quite easy to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T23:32:26.780",
"Id": "81238",
"Score": "0",
"body": "@Josay I would interpret a single element `i` is captured in range [ i , i+1] because the delata (i +1) - i = 1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:45:56.680",
"Id": "46484",
"ParentId": "46463",
"Score": "6"
}
},
{
"body": "<p>I'll stick to the ruby code, as python isn't my strong suit. But I imagine it wouldn't take much to make the approach below more pythonic.</p>\n\n<p>There is <em>a lot</em> going on that <code>#add</code> method. A lot more than there needs to be. I'd create a more specific <code>Interval</code> class to go along with <code>IntervalStore</code>.</p>\n\n<p>I'd subclass <code>Range</code> to model the intervals, and give that subclass some methods that let's it check for overlaps and performs the merging. Subclassing <code>Array</code> is also an option, but <code>Range</code> has a couple of useful methods already, and besides, it's defined by its upper and lower bounds - like an interval. Only thing to note is that <code>Range</code> objects are immutable, so any merging will have to return a new instance, rather than modify an existing one. </p>\n\n<p>This will make the <code>IntervalStore</code> class a lot simpler, now that can deal with objects that know what they are.</p>\n\n<p>For there, the steps when adding a new interval are:</p>\n\n<ol>\n<li>Appending: Push the interval to the internal array</li>\n<li>Sorting: Sort the array</li>\n<li>Coalescing: Loop through and check if two consecutive intervals can be merged into one</li>\n</ol>\n\n<p>Based on all that, I get this <code>Interval</code> class:</p>\n\n<pre><code>class Interval < Range\n # Check if another interval overlaps this one\n def overlap?(other)\n cover?(other.min) || cover?(other.max)\n end\n\n # Return a new Interval by merging this one with another\n def merge(other)\n Interval.new([min, other.min].min, [max, other.max].max)\n end\n\n # Simplified array representation\n def to_a\n [min, max]\n end\nend\n</code></pre>\n\n<p>And for <code>IntervalStore</code>:</p>\n\n<pre><code>class IntervalStore\n def initialize\n @intervals = []\n end\n\n def add(min, max)\n @intervals.push(Interval.new(min, max))\n @intervals.sort_by!(&:min)\n @intervals = @intervals.inject([]) do |merged, interval|\n if merged.any? && merged.last.overlap?(interval)\n merged << merged.pop.merge(interval)\n else\n merged << interval\n end\n end\n end\n\n # Returns an array representation\n def to_a\n @intervals.map(&:to_a)\n end\nend\n</code></pre>\n\n<p>And bingo.</p>\n\n<hr>\n\n<p>Update: If you want a solution that's true to the very letter of the task, here's one:</p>\n\n<pre><code>class IntervalStore < Array\n def initialize\n super\n end\n\n def add(low, high)\n push([low, high])\n sort_by!(&:first)\n collapse\n end\n\n private\n\n def collapse\n collapsed = inject([]) do |merged, interval|\n can_merge = merged.any? && overlap?(merged.last, interval)\n merged << (can_merge ? merge(merged.pop, interval) : interval)\n end\n clear.concat(collapsed)\n end\n\n def overlap?(a, b)\n a = Range.new(*a) # just for the `cover?` method\n a.cover?(b.first) || a.cover?(b.last)\n end\n\n def merge(a, b)\n [ [a.first, b.first].min , [a.last, b.last].max ]\n end\nend\n</code></pre>\n\n<p>Personally, I don't like it quite as much, apart from its conciseness. I'm subclassing <code>Array</code> to have <code>IntervalStore</code> exactly match the \"output\" in the task (just for the heck of it), but I wouldn't recommend that - it's an array now, so if you call, say, <code>flatten!</code> on it, everything screws up. The class now also contains a few non-OOPish functions that don't operate on <code>self</code> in any way.</p>\n\n<p>But all that aside, the point is that you <em>literally</em> get this:</p>\n\n<pre><code>store = IntervalStore.new # => []\nstore.add(1, 2) # => [[1, 2]]\nstore.add(5, 6) # => [[1, 2], [5, 6]]\nstore.add(1, 4) # => [[1, 4], [5, 6]]\nstore.add(1, 2) # => [[1, 4], [5, 6]]\nstore.add(3, 5) # => [[1, 6]]\nstore.add(0, 7) # => [[0, 7]]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:12:17.520",
"Id": "46491",
"ParentId": "46463",
"Score": "5"
}
},
{
"body": "<p>Here is another way of doing it. (I have omitted comments on your code because I have nothing to add to @Uri's excellent answer.)</p>\n\n<p><strong>Code</strong></p>\n\n<p>First define an <code>Interval</code> class. This allows us to keep intervals as single objects in the main class, without having to fuss much with end points of intervals.</p>\n\n<pre><code>class Interval\n attr_reader :left, :right\n\n def initialize(left,right)\n @left = left\n @right = right\n end\n\n # Is self entirely to the left of other?\n def < (other)\n self.right < other.left\n end\n\n # Is self entirely to the right of other?\n def > (other)\n self.left > other.right\n end\n\n # Return the lessor of the left end of self and the left end of other\n def left_most(other)\n [self.left, other.left].min\n end \n\n # Return the greater of the right end of self and the right end of other\n def right_most(other)\n [self.right, other.right].max\n end\n\n # How intervals are to be displayed \n def inspect\n \"#{self.left}..#{self.right}\"\n end\nend\n</code></pre>\n\n<p>The main class:</p>\n\n<pre><code>class IntervalStore\n attr_reader :intervals\n\n def initialize\n # Array to hold Interval objects\n @intervals = []\n end\n\n def add(left, right)\n # Create an Interval object \n interval_to_add = Interval.new(left,right)\n\n if @intervals.empty?\n @intervals = [interval_to_add]\n return\n end\n\n # intervals in @intervals entirely to the left of interval_to_add\n before = @intervals.find_all {|i| i < interval_to_add }\n # intervals in @intervals entirely to the right of interval_to_add\n after = @intervals.find_all {|i| i > interval_to_add }\n\n # We will replace all intervals between the before and after\n # intervals (if any) with an interval new_interval\n\n if (before.size==@intervals.size || after.size==@intervals.size)\n # Case where all intervals are to the left of interval_to_add or to the\n # right of interval_to_add\n new_interval = interval_to_add\n else\n # before.size is the offset of the left-most interval in @intervals\n # that is not in before\n # @intervals.size-after.size-1 is the offset of the right-most\n # interval in @intervals that is not in after\n new_interval = Interval.new(interval_to_add.left_most(@intervals[before.size]),\n interval_to_add.right_most(@intervals[@intervals.size-after.size-1]))\n end\n @intervals = before + [new_interval] + after\n end\nend\n</code></pre>\n\n<p>Notice that this approach keeps the intervals in sorted order.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>is = IntervalStore.new\nis.add(2 , 5) #=> [2..5]\nis.add(6 , 8) #=> [2..5, 6..8]\nis.add(8 ,10) #=> [2..5, 6..10]\nis.add(0 , 1) #=> [0..1, 2..5, 6..10]\nis.add(1 , 7) #=> [0..10]\nis.add(0 , 1) #=> [0..10]\nis.add(1 ,11) #=> [0..11]\nis.add(-1,10) #=> [-1..11]\nis.add(-2,12) #=> [-2..12]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T19:28:29.520",
"Id": "83438",
"Score": "0",
"body": "Nice solution, I would consider renaming the variables though, as `int` is a loaded name, and can be confusing when talking about intervals of ints..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T20:03:03.430",
"Id": "83443",
"Score": "1",
"body": "Good suggestion, @Uri. I changed all the `int`'s to `interval`. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T05:32:04.487",
"Id": "46612",
"ParentId": "46463",
"Score": "5"
}
},
{
"body": "<p>Others have suggested different strategies, I'll comment on your code:</p>\n\n<p><strong>Meaningful naming</strong><br>\n<code>low</code> and <code>upp</code> are abbreviations, which are rather ambiguous. Better call them <code>lower_limit</code> and <code>upper_limit</code>. The name of the method (<code>add</code>) adds to the confusion, since it is not apparent <em>what</em> exactly are you adding. <code>add_interval</code> is more descriptive.</p>\n\n<p>Method names should be actions (<code>add_XXX</code>, <code>format_XXX</code>, <code>filter_XXX</code>), but variable names should be nouns (<code>flattened_store</code> instead of <code>flatten_store</code>). This is especially important in ruby, where the same syntax might either call a method or refer to a local variable.</p>\n\n<p><strong>Make your code human-readable</strong><br>\nThe innards of your <code>add</code> method are quite 'magic'. For the casual reader there is no way to understand <em>why</em> what you do there works. A lot of <code>.odd?</code>s and <code>.even?</code>s, and <code>+= 1</code> and <code>-= 1</code> with no rhyme or reason.<br>\nBuild your solution in a way that a reader who is not familiar with it will understand <em>what</em> you are trying to do. Otherwise, she won't be able to maintain your code when needed. You won't be able to maintain it to in a couple of months, or even weeks.<br>\nBreak it up to meaningful helper methods. Try to keep meaningful structures (if you are concerned with whether the ID is odd or even, maybe a better solution will not include flattening the store in the first place?).<br>\nIf you find that you are still left with unintelligible code (and only as a last resort!) a couple of comments explaining what you are doing and why may be very helpful.</p>\n\n<p><strong>Redundant logic</strong> </p>\n\n<ul>\n<li>Your <code>to_s</code> method is totally redundant, as <code>@store.to_s</code> will result in <em>exactly</em> the same string. </li>\n<li><p><code>format_result</code> could be simplified to</p>\n\n<pre><code>def format_result(rest)\n @store = rest.each_slice(2).to_a\nend\n</code></pre></li>\n<li><code>.clone.delete_if</code> could be simplified to <code>.reject</code>. </li>\n<li><p><code>filter_store</code> as a whole could be simplified to </p>\n\n<pre><code>def filter_store(flatten_store, low_index, upp_index)\n flatten_store[0..low_index] + flatten_store[high_index..-1]\nend\n</code></pre></li>\n</ul>\n\n<p><strong># TODO - implement this method</strong><br>\nI guess you already did that - you can safely delete the comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T16:09:11.450",
"Id": "81953",
"Score": "1",
"body": "All good points, Uri, and well-stated. Identifying problems and weaknesses in existing code is probably more important to learning than is the suggestion of alternatives."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:17:04.083",
"Id": "46798",
"ParentId": "46463",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46798",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:26:44.420",
"Id": "46463",
"Score": "7",
"Tags": [
"python",
"algorithm",
"ruby",
"interval"
],
"Title": "Adding intervals to an interval store"
} | 46463 |
<p>I have to parse a file line-by-line and in single line I have split by ",". The first string is the name and the second is the count.</p>
<p>Finally, I have to display the Key and Count, for example:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Peter,2
Smith,3
Peter,3
Smith,5
</code></pre>
</blockquote>
<p>I should display as Peter 5 and Smith 8.</p>
<p>I confused about choosing between <code>BufferedReader</code> vs <code>Scanner</code>. I went through <a href="https://stackoverflow.com/questions/2231369/scanner-vs-bufferedreader">this link</a> and came up with these two approaches. I would like to get your reviews.</p>
<ol>
<li><h3><code>BufferedReader</code></h3>
<pre class="lang-java prettyprint-override"><code>private HashMap<String, MutableLong> readFile(File file) throws IOException {
final HashMap<String, MutableLong> keyHolder = new HashMap<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"))) {
for (String line; (line = br.readLine()) != null;) {
// processing the line.
final String[] keyContents = line
.split(KeyCountExam.COMMA_DELIMETER);
if (keyContents.length == 2) {
final String keyName = keyContents[0];
final long count = Long.parseLong(keyContents[1]);
final MutableLong keyCount = keyHolder.get(keyName);
if (keyCount != null) {
keyCount.add(count);
keyHolder.put(keyName, keyCount);
} else {
keyHolder.put(keyName, new MutableLong(count));
}
}
}
}
return keyHolder;
}
private static final String COMMA_DELIMETER = ",";
private static volatile Pattern commaPattern = Pattern.compile(COMMA_DELIMETER);
</code></pre>
<p>I have used <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableLong.html" rel="nofollow noreferrer"><code>MutableLong</code></a>, since I don't want to create a <code>BigInteger</code> each time. Again, it may be a very big file and I don't have control on how max a key can occur.</p></li>
<li><h3><code>Scanner</code> and two delimiters</h3>
<pre class="lang-java prettyprint-override"><code>private static final String LINE_SEPARATOR_PATTERN = "\r\n|[\n\r\u2028\u2029\u0085]";
private static final String LINE_PATTERN = ".*(" + LINE_SEPARATOR_PATTERN
+ ")|.+$";
private static volatile Pattern linePattern = Pattern.compile(LINE_PATTERN);
</code></pre></li>
</ol>
<p>I have went through the <code>hasNext</code> in <code>Scanner</code>, and to me, there is no harm in switching the <code>Pattern</code>. And I believe from Java 7, <code>Scanner</code> does have a limited buffer and can be enough for this kind of file.</p>
<p>Does anyone prefer Approach 2 over Approach 1, or do we have any other option than this? I just did sop for testing purpose. Obviously the same code in approach 1 would replace here. Using <code>split</code> in Approach 1 would create multiple <code>String</code> instances, which can be avoided here, by scanning a <code>char</code> sequence.</p>
<pre class="lang-java prettyprint-override"><code>private HashMap<String, BigInteger> readFileScanner(File file)
throws IOException {
final HashMap<String, BigInteger> keyHolder = new HashMap<>();
try (Scanner br = new Scanner(file, "UTF-8")) {
while (br.hasNext()) {
br.useDelimiter(commaPattern);
System.out.println(br.next());
System.out.println(br.next());
br.useDelimiter(linePattern);
}
}
return keyHolder;
}
</code></pre>
| [] | [
{
"body": "<p><strong>Which iterator to use</strong><br>\nI believe it is a matter of taste which iterator to use, though I find the first option is better because:</p>\n\n<ul>\n<li>It is more readable - you understand what is going on at every line - your <code>readLine()</code> each time, and then <code>split()</code> it. In the second option you keep changing the delimiter which is not very intuitive or readable, and the code reader would have to be familiar with <code>Scanner</code> to understand what is going on.</li>\n<li>It is less brittle - in the first option you actually check the validity of your input (that it has two elements in each line). In the second option, you can't really do that, and if you get a corrupt file, you are going to get unexpected results.</li>\n</ul>\n\n<p><strong>Mutable Long?</strong><br>\nI did not follow you explanation about <code>MutableLong</code>, for one thing since I can't see that it even supports <code>BigInteger</code>... Also, when in each line you have numbers in the range of <code>2</code> and <code>5</code>, how big you expect the files to be? The max <code>long</code> number is <code>9,223,372,036,854,775,807</code>...</p>\n\n<p><strong>Magic Constants</strong><br>\nA constant like <code>COMMA_DELIMETER = \",\"</code> is not very useful. Using the literal is readable enough, and resolves any ambiguity it might have by hiding it in a constant:</p>\n\n<pre><code>keyContents = line.split(\",\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:27:02.840",
"Id": "81180",
"Score": "0",
"body": "Agreed with magic Constants. Thanks for the your view on Option 1 and Option 2. I do even prefer the first one. Only thing i worried is , readLine would create new String and Split would create two more Strings . so for a line it would create 3 Strings. If the file is huge it would be expensive spending cycle in GC. How ever will it do always new String / intern from pool ( i dont know)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:30:52.287",
"Id": "81181",
"Score": "0",
"body": "And for the Mutable Long. Same Reason. BigInteger is not Mutable, so each time when the same key found it would create another one. That why went to Mutable Long. I could have used AtomicLong but it has more than what i needed. so i choosed MutableLong from apache it just wraps the long"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:38:04.827",
"Id": "81183",
"Score": "1",
"body": "Scanner will create two strings too. Anyway native long what is wrong with it? It's 64bit and you avoid object overhead and the part to check if it's null. (P.S AtomicLong is a total different thing!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:41:41.813",
"Id": "81184",
"Score": "0",
"body": "Yes. but i cant use native long since i have to keep the count in map (any storage) . so i have to use Object wrapped by long any way"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:19:53.483",
"Id": "46474",
"ParentId": "46465",
"Score": "5"
}
},
{
"body": "<p>I think that splitting a string on commas is the worse approach for serious CSV parsing.</p>\n\n<p>There is no single standard <a href=\"/questions/tagged/csv\" class=\"post-tag\" title=\"show questions tagged 'csv'\" rel=\"tag\">csv</a> format, but <a href=\"http://www.ietf.org/rfc/rfc4180.txt\">RFC 4180</a> comes close to being a <em>de facto</em> standard. As described in Section 2, CSV fields may be double-quoted (and if so, a literal <code>\"</code> would be represented as a pair of <code>\"</code> characters). Simply splitting a line on commas does not give you the ability to ever implement support for interpreting quoting.</p>\n\n<p>With a <code>Scanner</code>, you can use tools such as <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#useDelimiter(java.util.regex.Pattern)\"><code>useDelimiter(Pattern)</code></a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#findInLine(java.util.regex.Pattern)\"><code>findInLine(Pattern)</code></a> to simultaneously look for <code>\"</code> and <code>,</code> characters, giving you a chance to write a real parser based on the ABNF grammar in RFC 4180.</p>\n\n<p>Of course, unless are deliberately <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a>, you should just use an existing library, such as <a href=\"http://commons.apache.org/proper/commons-csv/\">Apache Commons CSV</a> or <a href=\"http://opencsv.sourceforge.net\">opencsv</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:02:51.710",
"Id": "81192",
"Score": "0",
"body": "Thanks , i may be misguided by adding CSV in the Question. It is just comma Separated and no Quotes involved. I agreed that i should avoid reinvent and use opencsv / Apache Commons. Assume i am given only to use native API . in that case if i understood correctly you prefer to use Scanner and findInLine(Pattern)- correct me if i wrong"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:20:05.567",
"Id": "81197",
"Score": "2",
"body": "I particularily agree with the suggestion to use the apache commons CSV library; after all, he already is using apache commons with the `MutableLong` anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T19:06:46.053",
"Id": "81203",
"Score": "0",
"body": "[SuperCSV](http://supercsv.sourceforge.net/) is also a good choice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:56:11.170",
"Id": "46480",
"ParentId": "46465",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:53:06.280",
"Id": "46465",
"Score": "10",
"Tags": [
"java",
"parsing",
"comparative-review",
"csv"
],
"Title": "Parsing CSV file with BufferedReader vs Scanner"
} | 46465 |
<p>I have been working on a certain task these days and after several hours of torture, I have done it! However, I believe the code that I have "crafted" is quite difficult to be understood and to be honest, I wouldn't be able to understand it if I wasn't the one who made it. Anyways, this is my code. I would like to receive some advice about what I could do to make it a little bit more simple and, by any chance, shorter:</p>
<pre><code> using System;
class BitExchangeAdvanced
{
static void Main()
{
int num1, num2, p, q, k, loop;
uint n, n1, bit;
while (true)
{
// input number
Console.WriteLine("Input n:");
if (uint.TryParse(Console.ReadLine(), out n))
{
if (n >= 0)
{
break;
}
}
}
// input first position
while (true)
{
Console.WriteLine("Input p:");
if (int.TryParse(Console.ReadLine(), out p))
{
if (p >= 0)
{
break;
}
}
}
// input second position
while (true)
{
Console.WriteLine("Input q:");
if (int.TryParse(Console.ReadLine(), out q))
{
if (q >= 0)
{
break;
}
}
}
// input the limit
while (true)
{
Console.WriteLine("Input k:");
if (int.TryParse(Console.ReadLine(), out k))
{
if (k > 0)
{
break;
}
}
}
// check which position is first
if (p>q)
{
num1 = q;
num2 = p;
}
else
{
num1 = p;
num2 = q;
}
// the loop is used in the "for" loop
loop = num1;
// check if the inpputs are valid for completing the operation
if (num2 - num1 < k || num1 + k > 32 || num2 + k > 32)
{
Console.WriteLine("Overlapping or out of range");
}
else
{
// use "for" in order to complete the formula {p, p+1, …, p+k-1}
for (num1 = loop; num1 < (loop + k); num1++)
{
bit = (n >> num1) & 1; // check the first value
if (bit == 1)
{
n1 = (bit << num1 + (num2 - num1)) | n; // input the value to its analog in num2
bit = (n >> num1 + (num2 - num1)) & 1; // complete the opposite operation
if (bit == 1)
{
n1 = (bit << num1) | n1;
}
else
{
n1 = ~((bit + 1) << num1) & n1;
}
}
else
{
n1 = ~((bit + 1) << num1 + (num2 - num1)) & n; // same as the above but with different operations
bit = (n >> num1 + (num2 - num1)) & 1; // complete the opposite operation again
if (bit == 1)
{
n1 = (bit << num1) | n1;
}
else
{
n1 = ~((bit + 1) << num1) & n1;
}
}
n = n1;
num2 = num2 + 1; // completes the second formula {q, q+1, …, q+k-1}
}
Console.WriteLine("The result is: {0}", n); // print the result
}
}
}
</code></pre>
<p>The task is: Write a program that exchanges bits {p, p+1, …, p+k-1} with bits {q, q+1, …,q+k-1} of a given 32-bit unsigned integer. The first and the second sequence of bits may not overlap.</p>
| [] | [
{
"body": "<p>I tried to answer when this question was on SO, but you removed and reposted it here.. so here's a non-code-review. This is not a comment on your code, but a suggestion for an entirely different approach.</p>\n\n<p>That's much more complicated then it has to be.</p>\n\n<p>Look into delta swaps. <code>delta(x, m, d)</code> takes an input <code>x</code>, a mask <code>m</code> and a distance <code>d</code> (the delta), and swaps non-overlapping pairs of bits such that one of the pair is indicated by the mask and the other of the pair is <code>d</code> places towards the most significant bit.</p>\n\n<p>It sounds more complicated than it is: (this is pseudo code, and not tested, you can look up the real definition in The Art of Computer Programming 4A, Bitwise tricks and techniques)</p>\n\n<pre><code>delta(x, m, d) =\n let temp = x ^ ((x >> d) & m)\n in x ^ temp ^ (temp << d)\n</code></pre>\n\n<p>If you recast your problem in terms of <code>delta</code>, the only trouble is getting the mask and the distance. The distance is just <code>abs(p - q)</code>. Generating a mask from some position to an other is a common problem (it has been asked on SO several times) and not too hard.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:35:45.240",
"Id": "46470",
"ParentId": "46469",
"Score": "3"
}
},
{
"body": "<p>I <em>think</em> this is suggesting roughly (maybe exactly) the same technique as @harold does in his answer, but I'm not entirely certain that I understand his answer, so I can't say with certainty whether it's the same or not.</p>\n\n<p>I'd consider two facts in coming to an answer. First, that where two bits are identical, we don't need to do anything to swap them--i.e., swapping a 1 with a 1 or a 0 with a 0 doesn't change anything.</p>\n\n<p>Therefore, we only need to do anything where the bits are not equal to each other. In this case, we have to flip both bits--i.e., the one that was a 0 has to become a 1, and the one that was a 1 has to become a 0.</p>\n\n<p>At least to me, that immediately brings an exclusive-or to mind. An exclusive-or produces a 1 if one input or the other (but not both) is a 1. Looking at it slightly differently, it produces a 1 if the bits are not equal to each other, and a 0 if they are equal to each other. Looked at from yet a slightly different angle, an XOR with 0 leaves a bit unchanged, and an XOR with 1 always flips the bit (changes a 0 to a 1, or a 1 to a 0).</p>\n\n<p>With that in hand, the job becomes fairly simple: we start by XORing the bits in the two ranges. This gives us 0s where they contain identical bits (meaning we want to leave them unchanged). It gives us 1s where they contain differing bits (meaning we want to flip the bits in both ranges). </p>\n\n<p>We then XOR that mask with the bits in each range. That leaves the bits in each range unchanged where they were identical to start with, and flips the bits in each range where they were different.</p>\n\n<p>For example, let's consider swapping the first 4 bits of a byte with the second 4 bits:</p>\n\n<pre><code>first four: 0 1 0 1\nlast four: 0 1 1 0\n</code></pre>\n\n<p>When we XOR these, we get: </p>\n\n<pre><code>mask: 0 0 1 1\n</code></pre>\n\n<p>We then XOR that back with each of the input ranges:</p>\n\n<pre><code>first four: 0 1 0 1\nmask: 0 0 1 1\nresult: 0 1 1 0\n\nlast four: 0 1 1 0\nmask: 0 0 1 1 \nresult: 0 1 0 1\n</code></pre>\n\n<p>And now the first four have the same values as the last four did to start with (and vice versa).</p>\n\n<p>Looking more specifically at your code, it has a fair number of places I think it could be made simpler and probably shorter. You start by reading four numbers, each with a block of code like this:</p>\n\n<pre><code>while (true)\n{\n // input number\n\n Console.WriteLine(\"Input n:\");\n if (uint.TryParse(Console.ReadLine(), out n))\n {\n if (n >= 0)\n {\n break;\n }\n }\n}\n</code></pre>\n\n<p>The only things that change from one of these to the next are the string you display and the identity of the variable you're reading. This is an ideal candidate for being turned into a function. The function needs to read a number (just as you've done it above) and return the value when it's successful. Then the code in main will just call that function for each of the numbers it needs to read:</p>\n\n<pre><code>n = read_number(\"Input n:\");\np = read_number(\"Input p:\");\nq = read_number(\"Input q:\");\nk = read_number(\"Input k:\");\n</code></pre>\n\n<p>It's probably possible to avoid having to pass the string as well--you'd pass the variable itself, and figure out the name of that variable using reflection to build your string. That takes some rather more advanced use of .NET though, and I wouldn't advise it for now.</p>\n\n<p>When it comes to finding which range is first:</p>\n\n<pre><code>if (p>q)\n{\n num1 = q;\n num2 = p;\n}\nelse\n{\n num1 = p;\n num2 = q;\n}\n</code></pre>\n\n<p>I think I'd just use <code>p</code> and <code>q</code>, but swap them if they're out of order:</p>\n\n<pre><code>if (p>q) {\n temp = p;\n p = q;\n q = temp;\n}\n</code></pre>\n\n<p>(...and wish you were using C++, so you didn't have to re-implement basic operations like this for the 4 billionth time).</p>\n\n<p>I've already advised a complete rewrite of the swapping code itself, so I guess there's not much point in reviewing that part of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T19:41:05.837",
"Id": "81210",
"Score": "0",
"body": "Thank you for your overall suggestions. I shall try to rework my code in order to make it better according to your statements. They helped me a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:23:02.457",
"Id": "46475",
"ParentId": "46469",
"Score": "6"
}
},
{
"body": "<pre><code>int num1, num2, p, q, k, loop;\nuint n, n1, bit;\n</code></pre>\n\n<p>You shouldn't declare all your variables in one place. Declare them where they're first used.</p>\n\n<p>Also, the names are quite confusing. You're not trying to save bytes, you're trying to write understandable program, so avoid names that don't say anything about the variable, instead use descriptive names.</p>\n\n<p>For example, based on a comment later, you could use <code>firstPosition</code> or <code>position1</code> instead of <code>p</code>.</p>\n\n<hr>\n\n<pre><code>while (true)\n{\n Console.WriteLine(\"Input p:\");\n if (int.TryParse(Console.ReadLine(), out p))\n {\n if (p >= 0)\n {\n break;\n }\n }\n}\n</code></pre>\n\n<p>This same code is repeated several times almost verbatim. You should try to avoid that (it's called Don't Repeat Yourself, or DRY for short) and instead write a method to encapsulate this. For example:</p>\n\n<pre><code>public static int ReadInt(string name)\n{\n int value;\n\n while (true)\n {\n Console.WriteLine(\"Input p:\");\n if (int.TryParse(Console.ReadLine(), out value) && value >= 0)\n return value;\n }\n}\n</code></pre>\n\n<p>Also, I'm confused about your usage of <code>int</code> and <code>uint</code>: Why do you use both, but sometimes use <code>int</code> for numbers that cannot be negative?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:27:07.163",
"Id": "46476",
"ParentId": "46469",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46475",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:26:40.070",
"Id": "46469",
"Score": "7",
"Tags": [
"c#",
"bitwise"
],
"Title": "Bit exchange operation"
} | 46469 |
<p>Based on <a href="https://codereview.stackexchange.com/q/46397/507">Dynamically call lambda based on stream input: Try 2</a></p>
<p>This fixes most of the points pointed out by <a href="https://codereview.stackexchange.com/a/46448/507">@Morwenn</a>.</p>
<p>It has been generalized so anybody can call it.<br>
The only extra part needed by the code is a function to retrieve values from a stream. This is passed as a template argument to <code>callFunctor()</code> see the example below.</p>
<p>An example of how to use it:<br>
Here I use <code>std::stringstream</code> as the input to be used for this example. In my own version I have a DB socket streaming rows from a MySQL DB and the lambda is called for each row. The point is the current version of <code>callFunctor()</code> can be used in any general environment (I hope somebody finds it useful).</p>
<h3>main.cpp</h3>
<pre><code>#include "detail_caller.h"
#include <iostream>
#include <sstream>
struct GetStreamValue
{
// The input type to this method must match
// the type of the first argument to `callFunctor`
// As you will be passed the stream and asked to pull
// a specific type from it.
template<typename R>
static R get(std::istream& stream)
{
R result;
stream >> result;
return result;
}
};
int main()
{
std::stringstream data("10 13 Loki 4.5");
callFunctor<GetStreamValue>(
data,
[](int val1, int val2, std::string const& val3, float val4)
{
std::cout << "Got(" << val1 << ", "
<< val2 << ", "
<< val3 << ", "
<< val4 << ")\n";
}
);
}
</code></pre>
<h3>detail_caller.h</h3>
<pre><code>#ifndef THORSANVIL_DETAIL_CALLER_H
#define THORSANVIL_DETAIL_CALLER_H
#include <utility>
template <typename T>
struct CallerTraits
: public CallerTraits<decltype(&T::operator())>
{};
template<typename C, typename ...Args>
struct CallerTraits<void (C::*)(Args...) const>
{
static constexpr int size = sizeof...(Args);
typedef std::make_integer_sequence<int, size> Sequence;
typedef std::tuple<std::decay_t<Args>...> AllArgs;
};
template<typename StreamValueGetter, typename Action, typename Stream, int... S>
void expandArgsAndCallFunctor(Stream& stream, Action action, std::integer_sequence<int, S...>)
{
typedef CallerTraits<decltype(action)> Trait;
typedef typename Trait::AllArgs ArgumentTuple;
// ArgumentTuple arguments(StreamValueGetter::template get<typename std::tuple_element<S, ArgumentTuple>::type>(stream)...);
// action(std::get<S>(arguments)...);
// The above two commented out lines
// Represent the logic of the following line which retrieves
// and calls the arguments in a single line thus avoiding temporaries.
action(StreamValueGetter::template get<typename std::tuple_element<S, ArgumentTuple>::type>(stream)...);
}
template<typename StreamValueGetter, typename Action, typename Stream>
void callFunctor(Stream& stream, Action action)
{
typedef CallerTraits<decltype(action)> Trait;
typedef typename Trait::Sequence Sequence;
expandArgsAndCallFunctor<StreamValueGetter>(stream, action, Sequence());
}
#endif
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:23:56.093",
"Id": "81178",
"Score": "0",
"body": "Which C++14-only features, if any, are you using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:24:49.357",
"Id": "81179",
"Score": "0",
"body": "Apparently `std::decay_t` and `std::integer_sequence`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T01:12:39.730",
"Id": "81244",
"Score": "0",
"body": "`std::decay_t` is part of C++11: http://en.cppreference.com/w/cpp/types/decay"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:07:00.493",
"Id": "81256",
"Score": "1",
"body": "@Yuushi: c++11 => std::decay c++14 => std::decay_t"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:21:01.073",
"Id": "81258",
"Score": "0",
"body": "Ah, you're right, my mistake."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:24:41.070",
"Id": "81259",
"Score": "0",
"body": "@Yuushi: Its not as if I knew. Morwenn told me as part of the review for `Try2`."
}
] | [
{
"body": "<p>I was about to add more things to my answer on your previous post and noticed meanwhile that your already asked a following question (that's almost too fast! :o). I have done some additional reading about C++14 and integer sequences. And I have found some things in the standard that could help to improve your code again.</p>\n\n<p>I realized at some point that you were using <code>int</code> as the <code>value_type</code> of <code>std::integer_sequence</code>. However, you initialize your <code>static constexpr int size</code> with the result of <code>sizeof...</code> and <code>sizeof...</code> returns a <code>std::size_t</code>, not an <code>int</code>.</p>\n\n<p>Then I remembered that, along with <code>std::integer_sequence</code>, there is a <code>typedef</code> for <code>std::integer_sequence<std::size_t, N></code> which is called <code>std::index_sequence</code> and which has been made to solve the kind of problem that your are trying to solve. Therefore, you should every occurrence of <code>int</code> by <code>std::size_t</code> and of <code>std::integer_sequence<int, N></code> by <code>std::index_sequence<N></code>.</p>\n\n<hr>\n\n<p>Moreover, you don't need to create a <code>typedef</code> for <code>Sequence</code> in <code>CallerTraits</code>: you can deduce this class directly in <code>callFunctor</code> thanks to <code>CallerTraits<>::size</code>:</p>\n\n<pre><code>template<typename StreamValueGetter, typename Action, typename Stream>\nvoid callFunctor(Stream& stream, Action action)\n{\n using Sequence = std::make_index_sequence<CallerTraits<Action>::size>;\n expandArgsAndCallFunctor<StreamValueGetter>(stream, action, Sequence());\n}\n</code></pre>\n\n<p>Note that I also replaced <code>decltype(action)</code> by <code>Action</code> since it is the same type.</p>\n\n<hr>\n\n<p>Also, you can get rid of the <code>public</code> inheritance specifier for <code>CallerTraits</code> since you are using a <code>struct</code>. That does not change anything whatsoever.</p>\n\n<hr>\n\n<p>Here is your code once refactored. I don't provide a link to an online compiler since none of the ones available has a good enough C++14 support (you just need to add some light library components though):</p>\n\n<pre><code>template <typename T>\nstruct CallerTraits\n : CallerTraits<decltype(&T::operator())>\n{};\n\ntemplate<typename C, typename ...Args>\nstruct CallerTraits<void (C::*)(Args...) const>\n{\n static constexpr std::size_t size = sizeof...(Args);\n typedef std::tuple<std::decay_t<Args>...> AllArgs;\n};\n\ntemplate<typename StreamValueGetter, typename Action, typename Stream, std::size_t... S>\nvoid expandArgsAndCallFunctor(Stream& stream, Action action, std::index_sequence<S...>)\n{\n typedef CallerTraits<Action> Trait;\n typedef typename Trait::AllArgs ArgumentTuple;\n\n // ArgumentTuple arguments(StreamValueGetter::template get<typename std::tuple_element<S, ArgumentTuple>::type>(stream)...);\n // action(std::get<S>(arguments)...);\n\n // The above two commented out lines\n // Represent the logic of the following line which retrieves\n // and calls the arguments in a single line thus avoiding temporaries.\n action(StreamValueGetter::template get<std::tuple_element_t<S, ArgumentTuple>>(stream)...);\n}\n\ntemplate<typename StreamValueGetter, typename Action, typename Stream>\nvoid callFunctor(Stream& stream, Action action)\n{\n using Sequence = std::make_index_sequence<CallerTraits<Action>::size>;\n expandArgsAndCallFunctor<StreamValueGetter>(stream, action, Sequence());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:40:10.497",
"Id": "81201",
"Score": "0",
"body": "The choice to use `int` over `std::size_t` was deliberate. I am trying not to use unsigned types for anything but bitfields."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:44:57.783",
"Id": "81202",
"Score": "0",
"body": "@LokiAstari I understand your choice. Too bad that the standard only makes things easier for `unsigned` types :/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:12:36.427",
"Id": "46481",
"ParentId": "46473",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46481",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:07:51.067",
"Id": "46473",
"Score": "7",
"Tags": [
"c++",
"template",
"template-meta-programming",
"c++14"
],
"Title": "Dynamically call lambda based on stream input: Try 3"
} | 46473 |
<p>In <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a>, a template <a href="http://en.cppreference.com/w/cpp/language/parameter_pack" rel="nofollow">parameter pack</a> is a template parameter that accepts zero or more template arguments (non-types, types, or templates). A function parameter pack is a function parameter that accepts zero or more function arguments.</p>
<p>A template with at least one parameter pack is called a variadic template.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:29:34.263",
"Id": "46477",
"Score": "0",
"Tags": null,
"Title": null
} | 46477 |
In C++, a parameter pack is a parameter that accepts zero or more arguments. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:29:34.263",
"Id": "46478",
"Score": "0",
"Tags": null,
"Title": null
} | 46478 |
<p><img src="https://i.stack.imgur.com/j10XI.png" alt="enter image description here"></p>
<p>This code is super slow. I'm looking for advice on how to improve its performance.</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# rss feed indexing bot
#
import requests
import urlparse
import time
import cookielib
import psutil
import feedparser
import socket
import datetime
import sys
import urllibfthe reason for which
import re
import nltk
import unicodedata
import xmlrpclib
import thread
from contextlib import closing
from bs4 import BeautifulSoup as bs
from feedfinder import feeds as feedfinder # http://www.aaronsw.com/2002/feedfinder/
from dateutil import parser as dateparser
import threading
from multiprocessing import Process
from nltk.tokenize import RegexpTokenizer
import MySQLdb as mdb
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import pickle
def _pickle(obj):
return pickle.dumps(obj)
def _unpickle(this):
return pickle.loads(this)
# Requests handler for bot server
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Bot server functions
class functionFactory:
def div(self, x, y):
return x // y
# Restrict to a particular path.
class botServer(threading.Thread,RequestHandler,functionFactory):
try:
def run(self):
try:
server = SimpleXMLRPCServer( ( "localhost",8000 ), requestHandler=RequestHandler )
server.register_introspection_functions()
server.register_instance(functionFactory())
now = datetime.datetime.now()
print "Starting server thread %s" % (str(now))
server.serve_forever()
except Exception as error:
if "Address" in str(error):
print "Bot server is up"
except Exception as error:
print str(error)
serverThread = botServer()
serverThread.start()
client = xmlrpclib.ServerProxy('http://localhost:8000')
Q = client.div(100,2)
print Q
# DATABASE VARS
"""***************"""
HOST = 'localhost'
USER = 'root'
PASSWORD = 'foobar'
DATABASE = 'rss-bot'
"""****************"""
def _install():
con = mdb.connect(HOST, USER, PASSWORD, DATABASE);
with con:
cur = con.cursor()
#cur.execute("DROP TABLE IF EXISTS feeds")
cur.execute("DROP TABLE IF EXISTS articles")
cur.execute("CREATE TABLE articles (Id INT PRIMARY KEY AUTO_INCREMENT, title varchar(255), summary longtext, link varchar(255))")
#cur.execute("CREATE TABLE feeds (Id INT PRIMARY KEY AUTO_INCREMENT, URL VARCHAR(255))")
#cur.execute("ALTER TABLE `feeds` ADD UNIQUE( `URL`);")
cur.execute("ALTER TABLE `articles` ADD UNIQUE( `title`);")
cur.execute("ALTER TABLE `articles` ADD UNIQUE( `link`);")
con = mdb.connect(HOST, USER, PASSWORD, DATABASE,charset='utf8',use_unicode=True)
def insertFeed(url):
url = urllib.unquote(url)
if len(url) <= 255:
url = con.escape_string(url)
try:
with con:
cur = con.cursor()
cur.execute("INSERT INTO feeds(URL) VALUES('%s')" % (url))
except:pass
# strip of crap characters (based on the Unicode database
# categorization:
# http://www.sql-und-xml.de/unicode-database/#kategorien
PRINTABLE = set(('Lu', 'Ll', 'Nd', 'Zs'))
def filter_non_printable(s):
result = []
ws_last = False
for c in s:
c = unicodedata.category(c) in PRINTABLE and c or u'#'
result.append(c)
return u''.join(result).replace(u'#', u' ')
def insertArticle(title,link,summary):
try:
with con:
cur = con.cursor()
if title and link and summary:
summary = con.escape_string(summary)
title = con.escape_string(title)
link = con.escape_string(link)
cur.execute('INSERT INTO articles(title,link,summary) VALUES("%s","%s","%s")' % (title,link,summary))
except Exception as error:
print "Error in insertArticle"
print error
def pullFeeds():
with con:
feeds = []
cur = con.cursor()
cur.execute("SELECT * FROM feeds")
rows = cur.fetchall()
for row in rows:
feeds.append(row[1])
return feeds
newswords = nltk.corpus.brown.words(categories='news')
tokenizer = RegexpTokenizer(r'([A-z])+')
def is_news(text):
if text:
text = nltk.clean_html(text)
words = sorted(set(tokenizer.tokenize(text)))
try:
worthParsing = len(words) >=1
if worthParsing == True:
content = set([w for w in words if w.lower() in newswords])
if content and len(content) >=1:
return True
else:
return False
except Exception as error:
print "Exception %s\nin function is_news" % (str(error))
def parseQuery(term):
if term.decode('utf-8', 'ignore'):
try:
# search?q=foo&num=100&safe=off&client=ubuntu&channel=fs&ei=O2A_U8niLra3sATtnoH4DA&start=100&sa=N&biw=1065&bih=569
perams = urllib.urlencode({'client':'ubuntu',
'q':term,
'num':100,
'safe':'off',
'start':100,
'bih':569,
'ei':'O2A_U8niLra3sATtnoH4DA'
})
query = "https://www.google.com/search?%s" % (perams)
return query
except Exception as error:
print "Exception %s\nIn function parseQuery() " % (str(error))
return False
else: return False
def submitQuery(query):
if query:
try:
markup = requests.get(query).content
if markup:
return markup.decode('utf-8', 'ignore')
else:
return False
except Exception as error:
print "Exception %s\n In submitQuery" % (str(error))
else:
return False
def cleanLink(link):
return re.sub(' ','',link)
def GoogleLinkResults(raw):
if raw:
raw = raw.decode('utf-8', 'ignore')
try:
sites = bs(raw).select('cite')
urls = []
for site in sites:
link = cleanLink(site.text)
if link.startswith("http") and "." in link:
urls.append(link)
elif link.startswith("http") == False and "." in link:
urls.append("http://%s" % (cleanLink(link)))
return urls
except Exception as error:
print "Exception %s\nin finction GoogleLinkResults"% str(error)
else:
return False
def Google(terms):
try:
print "Google Link Results"
if terms:
terms = " ".join(re.findall('([A-z ]+)',terms))
print terms
links = GoogleLinkResults(submitQuery(parseQuery(terms)))
if links:
return links
except Exception as error:
print "Exception %s\n in function Google" % (str(error))
return False
delay = 0
def currentDelay(delay): return delay
def lastModified(reqHeader):
if 'last-modified' in reqHeader:
last_modified = reqHeader['last-modified']
return dateparser.parse(last_modified)
def extractLinks(markup,TYPE='all'):
try:
soup = bs(markup.decode('utf-8', 'ignore'))
_rel_urls = [] # Holds Relative url objects
_abs_urls = [] # Holds Absolute url objects
hrefs = sorted(set([ l for l in soup.find_all('a') if l and l.get('href') ]))
if hrefs:
for href in hrefs:
url = urlparse.urlparse(href.get('href'))
if url.netloc: # If url is absolute
_abs_urls.append(url)
else: # If the url is relative
_rel_urls.append(url)
if TYPE == "abs":
return _abs_urls
elif TYPE == 'rel':
return _rel_urls
else: # If no TYPE argument was passed return both absolute & relative urls
return _rel_urls + _abs_urls
else:
return False
except Exception as error:
print "Exception %s in function extractLinks" % (str(error))
return False
def isHTML(reqHeader):
return 'content-type' in reqHeader and reqHeader['content-type'].startswith('text/html')
def agent(url,delay=0):
cookiejar = cookielib.CookieJar()
UserAgent = """
Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:26.0)Gecko/20100101 Firefox/26.0
"""
headers = {
'user-agent':UserAgent,
'Accept': 'text/html',
'Accept-Language': 'en-US',
'Accept-encoding': 'gzip,deflate'
}
try:
time.sleep(delay)
with closing(requests.get(url, stream=True, headers=headers, cookies=cookiejar, timeout=1.50, allow_redirects=True)) \
as req:
if isHTML(req.headers) : return req.content
else: return None
except Exception as error:
print "Exception %s\nin function agent" % (str(error))
return None
def stack(seeds):
try:
stack = {}
stack['tocrawl'] = set([])
stack['crawled'] = set([])
stack['domains'] = set([])
for i in seeds: stack['tocrawl'].add(i)
return stack
except Exception as error:
print "Exception %s\nin function stack" % (str(error))
def getfeeds(url,ignore):
try:
temp = feedfinder(url)
feeds = []
if temp and len(temp) > 0:
for feed in temp:
if feed not in ignore:
feeds.append(feed)
print "PUSHING %s TO DATABASE" % (feed)
insertFeed(feed)
if len(feeds) > 0:
feed = feedparser.parse(feeds[0])['entries'][0]['title']
temp = Google("rss feed %s" % (feed))
if is_news(feed):
if temp:
for this in temp:
if this.startswith("http"):
this = "http://%s" % (urlparse.urlparse(this).netloc)
newfeeds = feedfinder(this)
if newfeeds:
for feed in newfeeds:
feeds.append(feed)
print "PUSHING %s TO DATABASE" % (feed)
insertFeed(feed)
return list(set(feeds))
except Exception as error:
print str(error)
return False
def acceptableTLD(link):
acceptable = ['.com','.net','.edu','.gov','.org']
link = link.lower()
return len([d for d in acceptable if link.endswith(d)]) >=1
def updateStack(urls,tocrawl,crawled,feeds):
total_feeds = []
for url in urls:
time.sleep(0)
#ip = socket.gethostbyname(url.netloc)
link = "http://%s" % (url.netloc)
foundfeeds = getfeeds(link,feeds)
if link not in crawled and link not in tocrawl and link:
tocrawl.add(link)
if foundfeeds:
for feed in foundfeeds:
if feed not in feeds:
print "Found Feed > %s " % (feed)
crawled.add(feed)
feeds.add(feed)
def crawler(seeds,delay):
try:
_stack = stack(seeds)
_tocrawl = _stack['tocrawl']
_crawled = _stack['crawled']
_domains = _stack['domains']
_feeds = set([])
while len(_tocrawl) > 0 :
link = _tocrawl.pop()
_crawled.add(link)
time.sleep(delay)
newLinks = extractLinks(agent(link,delay),'abs')
print "Crawling : %s" % (link)
print "Crawled : %d" % (len(_crawled))
print "Left to crawl : %d" % (len(_tocrawl))
print "Feeds found : %d" % (len(_feeds))
print "Delay : %d" % (delay)
if newLinks:
updateStack(newLinks,_tocrawl,_crawled,_feeds)
except KeyboardInterrupt:
print "Quiting..."
serverThread._Thread__stop()
time.sleep(5)
quit()
except Exception as error:
print "Exception %s\nin function crawler"
crawler(['http://msnbc.com'],delay)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:14:33.287",
"Id": "81517",
"Score": "1",
"body": "As the diagram shows, your system consists of several components, any of which may be slow. You should carry out some experiments to find the bottleneck."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T17:48:12.267",
"Id": "46479",
"Score": "2",
"Tags": [
"python",
"performance",
"web-scraping",
"rss"
],
"Title": "Prototype spider for indexing RSS feeds"
} | 46479 |
<p>For homework, I have to code a program in Python that effectively simulates a bank ATM.</p>
<pre><code>print('Welcome to Northen Frock Bank ATM')
restart=('Y')
chances = 3
balance = 67.14
while chances >= 0:
pin = int(input('Please Enter You 4 Digit Pin: '))
if pin == (1234):
print('You entered you pin Correctly\n')
while restart not in ('n','NO','no','N'):
print('Please Press 1 For Your Balance\n')
print('Please Press 2 To Make a Withdrawl\n')
print('Please Press 3 To Pay in\n')
print('Please Press 4 To Return Card\n')
option = int(input('What Would you like to choose?'))
if option == 1:
print('Your Balance is £',balance,'\n')
restart = input('Would You you like to go back? ')
if restart in ('n','NO','no','N'):
print('Thank You')
break
elif option == 2:
option2 = ('y')
withdrawl = float(input('How Much Would you like to
withdraw? \n£10/£20/£40/£60/£80/£100 for other enter 1: '))
if withdrawl in [10, 20, 40, 60, 80, 100]:
balance = balance - withdrawl
print ('\nYour Balance is now £',balance)
restart = input('Would You you like to go back? ')
if restart in ('n','NO','no','N'):
print('Thank You')
break
elif withdrawl != [10, 20, 40, 60, 80, 100]:
print('Invalid Amount, Please Re-try\n')
restart = ('y')
elif withdrawl == 1:
withdrawl = float(input('Please Enter Desired amount:'))
elif option == 3:
Pay_in = float(input('How Much Would You Like To Pay In? '))
balance = balance + Pay_in
print ('\nYour Balance is now £',balance)
restart = input('Would You you like to go back? ')
if restart in ('n','NO','no','N'):
print('Thank You')
break
elif option == 4:
print('Please wait whilst your card is Returned...\n')
print('Thank you for you service')
break
else:
print('Please Enter a correct number. \n')
restart = ('y')
elif pin != ('1234'):
print('Incorrect Password')
chances = chances - 1
if chances == 0:
print('\nNo more tries')
break
</code></pre>
<p>This program basically does what it is designed to do, but I want to learn how
to use the <code>def()</code> and do it this way.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-26T03:34:01.437",
"Id": "213587",
"Score": "0",
"body": "this program didnot run it is syntax error in elif option==2:"
}
] | [
{
"body": "<p>The best way to do this would be to take each of your sections, and give them each a function of their own. Also, when it's possible, separate user input functions from purely logic to improve readability!</p>\n\n<p>For example, it could start looking like this:</p>\n\n<pre><code>def verify_pin(pin):\n if pin == '1234':\n return True\n else:\n return False\n\ndef log_in():\n tries = 0\n while tries < 4:\n pin = input('Please Enter Your 4 Digit Pin: ')\n if verify_pin(pin):\n print(\"Pin accepted!\")\n return True\n else:\n print(\"Invalid pin\")\n tries += 1\n print(\"To many incorrect tries. Could not log in\")\n return False\n\ndef start_menu():\n print(\"Welcome to the atm!\")\n if log_in():\n # you will need to make this one yourself!\n main_menu()\n print(\"Exiting Program\")\n\nstart_menu()\n</code></pre>\n\n<p>Whenever you can avoid nesting, you should. This makes it easier to read.</p>\n\n<p>In this case you can clearly see logging in will open the main_menu (<em>which you will have to write</em>), and entering a correct pin is the only way to log in.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-06T19:27:35.390",
"Id": "46489",
"ParentId": "46482",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "46489",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:32:50.543",
"Id": "46482",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"homework",
"finance"
],
"Title": "Bank ATM program in Python"
} | 46482 |
<p>I'm looking for code review, optimizations and best practices.</p>
<p>Also verifying complexity to be O(n), where <em>n</em> is the string length.</p>
<pre><code>public final class InfixToPostfix {
private static final char PLUS = '+';
private static final char MINUS = '-';
private static final char MULTIPLY = '*';
private static final char DIVIDE = '/';
private static final char OPENBRACE = '(';
private static final char CLOSEBRACE = ')';
private InfixToPostfix() {
}
private static boolean isOperator(char c) {
return c == PLUS || c == MINUS || c == MULTIPLY || c == DIVIDE || c == OPENBRACE || c == CLOSEBRACE;
}
/**
* If op1 has a higher precedence than op2.
*
* @param op1 the first operator
* @param op2 the second operator
* @return true if op1 has a higher precendence.
*/
private static boolean higherPrecedence(char op1, char op2) {
switch (op1) {
case PLUS:
case MINUS:
return op2 == OPENBRACE;
case MULTIPLY:
case DIVIDE:
return op2 == PLUS || op2 == MINUS || op2 == OPENBRACE;
case OPENBRACE:
return true;
case CLOSEBRACE:
return false;
default: throw new IllegalArgumentException("The operator op1: " + op1 + " or operator op2: " + op2 + " is illegal.");
}
}
private static StringBuilder getOperators(Stack<String> operatorStack) {
final StringBuilder operators = new StringBuilder();
/* eg: a + (b * c), here a,b and +, (, were in their respective stacks, and current char was ) */
while (!operatorStack.isEmpty() && operatorStack.peek().charAt(0) != OPENBRACE) {
operators.append(operatorStack.pop());
}
/* pop of the remaining open brace. */
if (!operatorStack.isEmpty() && operatorStack.peek().charAt(0) == OPENBRACE) {
operatorStack.pop();
}
return operators;
}
/**
* Converts a valid infix to postfix expression
* It is the clients responsibility to provide with a valid infix expression, failing which yeilds invalid results.
*
* @param infix the infix expression
* @return the postfix expressions
*/
public static String toPostfix(String infix) {
final Stack<String> operatorStack = new Stack<String>();
final Deque<String> operandStack = new ArrayDeque<String>();
char c;
for (int i = 0; i < infix.length(); i++) {
c = infix.charAt(i);
if (c == ' ')
continue;
/* we either have an operator or we have have an operand. */
if (isOperator(c)) {
/* we either have a operator with higher or lower precedence.*/
/* eg: a + b * c, here * has higher precedence over +, where ab and + were in respective stacks &
current character was */
if (operatorStack.isEmpty() || higherPrecedence(c, operatorStack.peek().charAt(0))) {
operatorStack.push(c + "");
} else {
/* eg: a * b + c, here * has higher precendence over +, where a,b and * were in respective stacks &
current character was + */
String op2 = operandStack.pop();
String op1 = operandStack.pop();
StringBuilder sb = new StringBuilder();
sb.append(op1);
sb.append(op2);
sb.append(getOperators(operatorStack));
operandStack.push(sb.toString());
if (c != CLOSEBRACE) {
operatorStack.push(c + "");
}
}
} else {
/* current char is an operand. */
operandStack.push(c + "");
}
}
/* Output the remaining operators from the stack. */
while (!operatorStack.empty()) {
operandStack.push(operatorStack.pop());
}
final StringBuilder sb = new StringBuilder();
while (!operandStack.isEmpty()) {
sb.append(operandStack.removeLast());
}
return sb.toString();
}
public static void main(String[] args) {
assertEquals("AB*CD/+", InfixToPostfix.toPostfix("A * B+C / D"));
assertEquals("ABC+*D/", InfixToPostfix.toPostfix("A* (B+C) / D"));
assertEquals("ABCD/+*", InfixToPostfix.toPostfix("A * (B + C / D)"));
assertEquals("AB*C/", InfixToPostfix.toPostfix("A*B/C"));
assertEquals("AB+C-", InfixToPostfix.toPostfix("A+B-C"));
}
}
</code></pre>
| [] | [
{
"body": "<p><strong>Method comments vs. naming</strong><br>\nWhen the method and parameters are well names, in 9 out of 10 cases, the comment above the method is redundant. For example, <code>higherPrecedence(char op1, char op2)</code> - if you call <code>op1</code> <code>firstOperator</code> and <code>op2</code> <code>secondOperator</code> the comment above the method simply says the same thing as the method signature. Twice.</p>\n\n<p><strong>Be consistent and precise</strong><br>\n<code>higherPrecedence(\"+\", \"-\") == false</code>, but <code>higherPrecendence(\"-\", \"+\") == false</code> as well... this is a very surprising result, and might result in inconsistent results.<br>\nWhen you get to the <code>default</code> case you throw an Exception which states that either <code>op1</code> or <code>op2</code> are illegal, although you <em>know</em> that <code>op1</code> is the illegal one, since you don't even check if <code>op2</code> is an operator.</p>\n\n<p><strong>Magic Constants</strong><br>\nI find that <code>\"+\"</code> is much more descriptive than <code>PLUS</code>. These kind of constants add unnecessary ambiguity to your code, as they force the reader to go and check their actual value.<br>\nIf you do decide to use a constant, I would suggest a single constant <code>OPERATORS_BY_PRECEDENCE</code>, which will result in these methods:</p>\n\n<pre><code>private static final OPERATORS_BY_PRECEDENCE = \"(+-/*)\";\n\nprivate static boolean isOperator(char c) {\n return OPERATORS_BY_PRECEDENCE.indexOf(c) != -1;\n}\n\nprivate static boolean higherPrecendence(char firstOperator, char secondOperator) {\n return OPERATORS_BY_PRECEDENCE.indexOf(firstOperator) < \n OPERATORS_BY_PRECEDENCE.indexOf(secondOperator);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:13:48.933",
"Id": "81257",
"Score": "0",
"body": "Although I agree naming has room for improvement, there is a issue with solution you proposed. This problem says 'if precedence is the same, then go from left to right' which means - a+b-c is should be ab+c- and not abc-+ although the would compute to be the same"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:49:53.513",
"Id": "81261",
"Score": "0",
"body": "In that case I would propose that the method will return three states - higher priority, lower priority, or same priority"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:53:09.067",
"Id": "46497",
"ParentId": "46486",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T19:08:32.127",
"Id": "46486",
"Score": "3",
"Tags": [
"java",
"algorithm",
"converting",
"stack"
],
"Title": "Infix to postix conversion"
} | 46486 |
<p>So here it is, my <a href="/questions/tagged/linked-list" class="post-tag" title="show questions tagged 'linked-list'" rel="tag">linked-list</a> implementation in Java. I have coded against Java's <code>List<E></code> interface as if my <code>LinkedList<E></code> could replace the standard <code>java.util.LinkedList<E></code> and it should make no difference.<br>
I am however aware of that I did not implement <code>Deque<E></code>, as only implementing <code>List<E></code> is a task on its own already.<br>
This code has been implemented using Java 8.</p>
<pre><code>/**
*
* @author Frank van Heeswijk
* @param <E> Type of elements the list stores
*/
public class LinkedList<E> implements List<E> {
/** Fake head node, meaning that it is not part of the List<E> it represents. **/
private Node head;
/** Fake tail node, meaning that it is not part of the List<E> it represents. **/
private Node tail;
/** If this list is a sublist of a LinkedList, then the parent will be in this variable. **/
private LinkedList<E> parentList;
/** The amount of modifications that occured to this LinkedList so far. **/
private int modificationsCount;
/** The size of this LinkedList. **/
private int size;
public LinkedList() {
this(Collections.emptyList());
}
public LinkedList(final Collection<? extends E> collection) {
this.head = new Node(null);
this.tail = new Node(null);
connect(head, tail);
addAll(collection);
}
private LinkedList(final Node head, final Node tail, final int size, final LinkedList<E> parentList) {
this.head = head;
this.tail = tail;
this.size = size;
this.parentList = parentList;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return (size() == 0);
}
@Override
public boolean contains(final Object object) {
return iteratorToStream().anyMatch(elem -> elem.equals(object));
}
@Override
public Iterator<E> iterator() {
return listIterator();
}
@Override
public Object[] toArray() {
return iteratorToStream().toArray();
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(final T[] elemArray) {
Objects.requireNonNull(elemArray);
if (size() > elemArray.length) {
return (T[])toArray();
}
Iterator<E> iterator = iterator();
int index = 0;
while (iterator.hasNext()) {
Object next = iterator.next();
elemArray[index++] = (T)next;
}
for (int i = index; i < elemArray.length; i++) {
elemArray[i] = null;
}
return elemArray;
}
@Override
public boolean add(final E element) {
add(size(), element);
return true;
}
@Override
public boolean remove(final Object object) {
ListIterator<E> listIterator = listIterator();
while (listIterator.hasNext()) {
if (listIterator.next().equals(object)) {
listIterator.remove();
return true;
}
}
return false;
}
@Override
public boolean containsAll(final Collection<?> collection) {
Objects.requireNonNull(collection);
return collection.stream().allMatch(this::contains);
}
@Override
public boolean addAll(final Collection<? extends E> collection) {
return addAll(size(), collection);
}
@Override
public boolean addAll(final int index, final Collection<? extends E> collection) {
Objects.requireNonNull(collection);
assertIndexExclusive(index);
if (collection.isEmpty()) {
return false;
}
ListIterator<E> listIterator = listIterator(index);
collection.forEach(listIterator::add);
return true;
}
@Override
public boolean removeAll(final Collection<?> collection) {
Objects.requireNonNull(collection);
if (collection.isEmpty()) {
return false;
}
int deletions = 0;
ListIterator<E> listIterator = listIterator();
while (listIterator.hasNext()) {
E next = listIterator.next();
if (collection.stream().anyMatch(elem -> elem.equals(next))) {
listIterator.remove();
deletions++;
}
}
return (deletions > 0);
}
@Override
public boolean retainAll(final Collection<?> collection) {
Objects.requireNonNull(collection);
if (collection.isEmpty()) {
return false;
}
int deletions = 0;
ListIterator<E> listIterator = listIterator();
while (listIterator.hasNext()) {
E next = listIterator.next();
if (collection.stream().noneMatch(elem -> elem.equals(next))) {
listIterator.remove();
deletions++;
}
}
return (deletions > 0);
}
@Override
public void clear() {
if (isEmpty()) {
return;
}
connect(head, tail);
modifySize(-size());
}
@Override
public E get(final int index) {
assertIndex(index);
return listIterator(index).next();
}
@Override
public E set(final int index, final E element) {
if (this == element) {
throw new IllegalArgumentException();
}
assertIndex(index);
ListIterator<E> listIterator = listIterator(index);
E old = listIterator.next();
listIterator.set(element);
return old;
}
@Override
public void add(final int index, final E element) {
if (this == element) {
throw new IllegalArgumentException();
}
assertIndexExclusive(index);
ListIterator<E> listIterator = listIterator(index);
listIterator.add(element);
}
@Override
public E remove(final int index) {
assertIndex(index);
ListIterator<E> listIterator = listIterator(index);
E old = listIterator.next();
listIterator.remove();
return old;
}
@Override
public int indexOf(final Object object) {
ListIterator<E> listIterator = listIterator();
while (listIterator.hasNext()) {
if (listIterator.next().equals(object)) {
return listIterator.nextIndex() - 1;
}
}
return -1;
}
@Override
public int lastIndexOf(final Object object) {
ListIterator<E> listIterator = listIterator(size());
while (listIterator.hasPrevious()) {
if (listIterator.previous().equals(object)) {
return listIterator.previousIndex() + 1;
}
}
return -1;
}
@Override
public ListIterator<E> listIterator() {
return listIterator(0);
}
@Override
public ListIterator<E> listIterator(final int index) {
assertIndexExclusive(index);
ListIterator<E> listIterator;
if (isEmpty()) {
listIterator = listNodeIteratorEmpty();
}
else if (index <= size() / 2) {
listIterator = listNodeIteratorFromHead();
while (listIterator.hasNext() && index != listIterator.nextIndex()) {
listIterator.next();
}
}
else {
listIterator = listNodeIteratorFromTail();
while (listIterator.hasPrevious() && index != listIterator.nextIndex()) {
listIterator.previous();
}
}
return listIterator;
}
@Override
public List<E> subList(final int fromIndex, final int toIndex) {
if (fromIndex < 0 || toIndex > size() || fromIndex > toIndex) {
throw new IndexOutOfBoundsException();
}
if (toIndex - fromIndex == 0) {
return new LinkedList<>(head, head.next, 0, this);
}
ListIterator<Node> listIterator = new LinkedListNodeListIterator();
while (listIterator.hasNext() && fromIndex != listIterator.nextIndex()) {
listIterator.next();
}
Node fromNode = listIterator.next();
while (listIterator.hasNext() && toIndex != listIterator.nextIndex()) {
listIterator.next();
}
Node toNode = listIterator.previous();
return new LinkedList<>(fromNode.previous, toNode.next, toIndex - fromIndex, this);
}
@Override
public boolean equals(final Object other) {
if (other == null) {
return false;
}
if (!(other instanceof List<?>)) {
return false;
}
List<?> otherList = (List<?>)other;
if (size() != otherList.size()) {
return false;
}
Iterator<E> iterator = iterator();
Iterator<?> otherIterator = otherList.iterator();
while (iterator.hasNext() && otherIterator.hasNext()) {
E next = iterator.next();
Object otherNext = otherIterator.next();
if (!Objects.equals(next, otherNext)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(iteratorToStream().toArray());
}
@Override
public String toString() {
return "[" + iteratorToStream()
.map(object -> (object == null ? "null" : object.toString()))
.collect(Collectors.joining(", ")) + "]";
}
private void assertIndex(final int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException();
}
}
private void assertIndexExclusive(final int index) {
if (index < 0 || index > size()) {
throw new IndexOutOfBoundsException();
}
}
private void modifySize(final int deltaSize) {
size += deltaSize;
if (parentList != null) {
parentList.modifySize(deltaSize);
}
}
private void incrementModificationsCount() {
modificationsCount++;
if (parentList != null) {
parentList.incrementModificationsCount();
}
}
private Stream<E> iteratorToStream() {
return StreamSupport.stream(spliterator(), false);
}
private LinkedListListIterator listNodeIteratorEmpty() {
return new LinkedListListIterator(-1, head, 0, tail);
}
private LinkedListListIterator listNodeIteratorFromHead() {
return new LinkedListListIterator(-1, head, 0, head.next);
}
private LinkedListListIterator listNodeIteratorFromTail() {
return new LinkedListListIterator(size() - 1, tail.previous, size(), tail);
}
@SafeVarargs
private final void connect(final Node... nodes) {
if (nodes.length == 0 || nodes.length == 1) {
throw new IllegalArgumentException();
}
for (int i = 0; i < nodes.length - 1; i++) {
Node node = nodes[i];
node.next = nodes[i + 1];
nodes[i + 1].previous = node;
}
}
private class Node {
public E value;
public Node next;
public Node previous;
public Node(final E value) {
this.value = value;
}
public boolean hasNext() {
return (next != null);
}
public boolean hasPrevious() {
return (previous != null);
}
@Override
public String toString() {
return "(" + value + ")";
}
}
private class LinkedListListIterator implements ListIterator<E> {
private Node next;
private Node previous;
private int nextIndex;
private int previousIndex;
private boolean removeAllowed;
private boolean forward;
private int expectedModificationsCount;
public LinkedListListIterator(final int previousIndex, final Node previousNode, final int nextIndex, final Node nextNode) {
this.next = nextNode;
this.previous = previousNode;
this.nextIndex = nextIndex;
this.previousIndex = previousIndex;
this.expectedModificationsCount = modificationsCount;
}
@Override
public boolean hasNext() {
return (next != tail);
}
@Override
public E next() {
checkConcurrentModification();
if (!hasNext()) {
throw new NoSuchElementException();
}
previous = next;
next = next.next;
nextIndex++;
previousIndex++;
forward = true;
removeAllowed = true;
return previous.value;
}
@Override
public boolean hasPrevious() {
return (previous != head);
}
@Override
public E previous() {
checkConcurrentModification();
if (!hasPrevious()) {
throw new NoSuchElementException();
}
next = previous;
previous = previous.previous;
previousIndex--;
nextIndex--;
forward = false;
removeAllowed = true;
return next.value;
}
@Override
public int nextIndex() {
if (next == null) {
return size();
}
return nextIndex;
}
@Override
public int previousIndex() {
if (previous == null) {
return -1;
}
return previousIndex;
}
@Override
public void remove() {
checkConcurrentModification();
if (!removeAllowed) {
throw new IllegalStateException();
}
if (forward) {
previous = previous.previous;
previousIndex--;
nextIndex--;
}
else {
next = next.next;
}
connect(previous, next);
decrementSize();
incrementModificationsCount();
removeAllowed = false;
}
@Override
public void set(final E element) {
checkConcurrentModification();
if (!removeAllowed) {
throw new IllegalStateException();
}
Node old = (forward) ? previous : next;
old.value = element;
}
@Override
public void add(final E element) {
checkConcurrentModification();
Node node = new Node(element);
connect(previous, node, next);
previous = node;
previousIndex++;
nextIndex++;
incrementSize();
incrementModificationsCount();
removeAllowed = false;
}
private void incrementSize() {
modifySize(1);
}
private void decrementSize() {
modifySize(-1);
}
private void incrementModificationsCount() {
expectedModificationsCount++;
LinkedList.this.incrementModificationsCount();
}
private void checkConcurrentModification() {
if (modificationsCount != expectedModificationsCount) {
throw new ConcurrentModificationException();
}
}
}
private class LinkedListNodeListIterator implements ListIterator<Node> {
private Node previous = head;
private Node next = head.next;
private int previousIndex = -1;
private int nextIndex = 0;
@Override
public boolean hasNext() {
return (next != tail);
}
@Override
public Node next() {
previous = next;
next = next.next;
previousIndex++;
nextIndex++;
return previous;
}
@Override
public boolean hasPrevious() {
return (previous != head);
}
@Override
public Node previous() {
next = previous;
previous = previous.previous;
previousIndex--;
nextIndex--;
return next;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return previousIndex;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void set(final Node node) {
throw new UnsupportedOperationException();
}
@Override
public void add(final Node node) {
throw new UnsupportedOperationException();
}
}
}
</code></pre>
| [] | [
{
"body": "<h2>Lots of extra objects</h2>\n<p>The largest single criticism I have is the creation of LinkedLists where they are not necessary. Creating Objects in Java is a performance issue, especially when done often.</p>\n<p>Methods like the following:</p>\n<blockquote>\n<pre><code>@Override\npublic E get(final int index) {\n assertIndex(index);\n return listIterator(index).next();\n}\n</code></pre>\n</blockquote>\n<p>Create an object (the ListIterator) in order to get a member. This is overkill.</p>\n<p>This pattern is repeated often.</p>\n<p>Rule of thumb, if your code is going to act on just one member in the list, then using an iterator is probably not the best solution.</p>\n<h2>Iterator "implemented"</h2>\n<p>The bulk of your logic is implemented in the ListIterator. This is a backwards way of doing it. The Iterator should call methods bck in the list, and not the other way around.</p>\n<h2>assertIndexExclusive</h2>\n<p>This should be called assertIndexInclusive (it includes the range end).</p>\n<h2>Bug in subList</h2>\n<p>The following code:</p>\n<blockquote>\n<pre><code>public List<E> subList(final int fromIndex, final int toIndex) {\n .....\n if (toIndex - fromIndex == 0) {\n return new LinkedList<>(head, head.next, 0, this);\n }\n</code></pre>\n</blockquote>\n<p>is buggy. Your code will create the sublist in the wrong place if, for example, <code>fromIndx</code> and <code>toIndex</code> are both <code>1</code>.</p>\n<h2>Bugs in clear()</h2>\n<p>clear() is not modifying the modifiedCount. It should (but only if the list was not empty)</p>\n<h2>General, small things</h2>\n<ul>\n<li><code>iterator()</code> should be really fast and 'tight'. Iterators are used extensively for things like enhanced-for loops in Java. Borrowing a LinkedList is a heavy-weight solution for something that should be fast.</li>\n<li><code>head</code> and <code>tail</code> in your <code>LinkedList</code> could be final.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:44:45.640",
"Id": "46496",
"ParentId": "46490",
"Score": "8"
}
},
{
"body": "<p>You are using non-static inner classes for the items in your list (class <code>Node</code>). Using an inner class means every <code>Node</code> object has access to the enclosing object (<code>LinkedList</code> in your case).</p>\n\n<p>Since you do not use that access in the class <code>Node</code>, you are wasting memory for no gains. Every <code>Node</code> object you create for your list also has an invisible reference to the enclosing <code>LinkedList</code> object. This increases the required memory for storing a list by about 20% (for lists that contain more than a few items).</p>\n\n<p>This can be solved by using a static nested class instead. However, it's not possible to use the generic type (<code>E</code>) in the static class. But since the class is private, this is not required and can be changed to Object, as the class is not accessible from the outside (so your <code>LinkedList</code> class controls which object types are used, namely only the generic type).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:07:44.480",
"Id": "81754",
"Score": "1",
"body": "Good spot. As for the generic type of the Node, it can be declared with it's own generic type: `private static final class Node<N> { .... }` and then internally it will have `public N value;` and `Node<N> next;` .... etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:17:41.963",
"Id": "81756",
"Score": "0",
"body": "Good suggestion. A static nested class with its own generic type is probably the best way to go about this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:03:54.527",
"Id": "46731",
"ParentId": "46490",
"Score": "3"
}
},
{
"body": "<p>While your code is meant to reinvent the wheel, I would suggest a way that involves slightly less reinvention: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/AbstractSequentialList.html\" rel=\"nofollow\"><code>AbstractSequentialList</code></a>. This class implements all methods in the list interface just using the <code>ListIterator</code>, so you only need to actually nclude code for the <code>listIterator</code> and <code>size</code> methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:42:26.810",
"Id": "46734",
"ParentId": "46490",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "46496",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:06:03.677",
"Id": "46490",
"Score": "11",
"Tags": [
"java",
"linked-list",
"reinventing-the-wheel"
],
"Title": "LinkedList implementation implementing the List interface in Java"
} | 46490 |
<p>I was eventually going to add another computer and more options to this (i.e., Rock-paper-scissors-lizard-Spock) but I wanted to make sure I was using the best practice for this type of game. Any help would be appreciated. </p>
<pre><code># The traditional paper scissors rock game
import os
def clear():
os.system("clear")
clear()
print ("\n\nPaper, Rock, Scissors Game -(Best of five games)")
x = 0 ; l = 0 ; w = 0 ; d = 0 ; lt = 0 ; wt = 0 ; dt = 0
while x < 5:
x = x + 1
import random
class Computer:
pass
comp_is = Computer()
comp_is.opt = ('r','p','s')
comp_is.rand = random.choice(comp_is.opt)
if comp_is.rand == 'r':
comp = 'rock'
elif comp_is.rand == 'p':
comp = 'paper'
else:
comp = 'scissors'
class Human:
pass
human_is = Human
print
human_is.player = raw_input(' Enter your choice of\n r\
for rock\n p for paper or\n s for scissors ... ')
print
class Result:
pass
Result_is = Result
if comp_is.rand == human_is.player:
print ("draw - computer chose ", comp)
print
d = d + 1
dt = dt + 1
elif comp_is.rand == 'r' and human_is.player == 'p':
print (" player beats computer -computer chose ", comp)
print
w = w + 1
wt = wt + 1
elif comp_is.rand == 'p' and human_is.player == 's':
print (" computer chose ", comp)
print (" player beats computer-because scissors cuts paper")
print ()
w = w + 1
wt = wt + 1
elif comp_is.rand == 's' and human_is.player == 'r':
print (" computer chose ", comp)
print (" player beats computer-because rock breaks scissors")
w = w + 1
wt = wt + 1
else :
print (" computer wins - computer chose ", comp)
print
l = l + 1
lt = lt + 1
if x == 5:
print ()
print ()
print (" games won ... ", w)
print (" games lost ... ", l)
print (" games drawn ... ", d)
print ()
print (" Running total overall of games won ... ", wt)
print (" Running total overall of games lost ... ", lt)
print (" Running total overall of games drawn ... ", dt)
print ()
w = 0 ; l = 0 ; d = 0
again = input('Do you want to play again y for yes, n for no .. ')
if again == 'y':
x = 0
else:
print
if lt > wt:
print ("You are a miserable loser,\nYou have lost more than you have won,\nPoor show indeed ")
print ('finish')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T23:14:52.167",
"Id": "81236",
"Score": "0",
"body": "I started analyzing the improved version of your question, but it has been removed for some reason. Line-by-line analysis is gone, but I wrote my version of a program: http://codereview.stackexchange.com/questions/46508/rock-paper-scissors."
}
] | [
{
"body": "<p>There is much to improve. I recommend you read <a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP 8</a>, the official Python style guide. It includes many important tips like:</p>\n\n<ul>\n<li><p>Use consistent 4-space indentation</p></li>\n<li><p>Multiple statements on the same line are discouraged</p></li>\n</ul>\n\n<p>Furthermore:</p>\n\n<ul>\n<li><p>You should use <em>words</em> instead of single letters for your variable names. All those variables like <code>x, l, w, d, lt, wt, dt</code> aren't self-explaining. What is their purpose? Instead: <code>count_rounds, count_losses, count_wins, count_draws, …</code>.</p></li>\n<li><p>Your usage of object oriented features is <em>extremely</em> weird. Get rid of all <code>class</code>es for now.</p></li>\n<li><p>Instead of <code>x = x + 1</code> write <code>x += 1</code>.</p></li>\n<li><p>Your code is really complicated because it munges together the user interface (prompting the user for choices, displaying results) with the actual logic of your program. Put the logic into separate functions, e.g.</p>\n\n<pre><code>def beats(choice_a, choice_b):\n if choice_a == 'rock' and choice_b == 'scissors':\n return 'smashes'\n if choice_a == 'scissors' and choice_b == 'paper':\n return 'cuts'\n if choice_a == 'paper' and choice_b == 'rock':\n return 'wraps'\n else:\n return None\n</code></pre>\n\n<p>This could be used as</p>\n\n<pre><code>def result_string(computer, player):\n verb = beats(computer, player)\n if verb:\n return \"computer beats player because %s %s %s\" % (computer, verb, player)\n verb = beats(player, computer)\n if verb:\n return \"player beats computer because %s %s %s\" % (player, verb, computer)\n return \"draw\"\n</code></pre>\n\n<p>which in turn could be used as <code>print(result_string(computer_choice, player_choice))</code>.</p></li>\n</ul>\n\n<p>Please try to fix these issues and to clean up your code, then come back and ask a new question for a second round of review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:35:01.267",
"Id": "81221",
"Score": "0",
"body": "Will fix up the code and come back for second round of review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:59:58.177",
"Id": "81225",
"Score": "0",
"body": "[here is my updated program](http://codereview.stackexchange.com/questions/46503/rock-paper-scissors-in-python-updated)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:05:47.297",
"Id": "81226",
"Score": "1",
"body": "@TjF As far as I can see, you only improved variable names. That is good, but I mentioned many more issues like indentation and helper functions. Any review on your updated code will mention those as well, which is unnecessary. Consider doing more substantial improvements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:06:25.693",
"Id": "81227",
"Score": "0",
"body": "I was sort of confused by this. Wondering if you could help me a little further on that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:11:35.937",
"Id": "81228",
"Score": "1",
"body": "@TjF your code has two concerns: deciding who won, and printing out the result. Combining these two is inelegant, it is better to put each concern into a seperate function. So my above answer suggested one function to find out which move one (and will return a verb describing how the move won), plus one function to format the message. The main input loop doesn't have to do anything besides printing out the actual result. This will make it easier to extend your program later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:27:11.977",
"Id": "81230",
"Score": "0",
"body": "I pulled the update and will add this. Thank you for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T01:26:31.680",
"Id": "81245",
"Score": "0",
"body": "Should I use my own program with modifications, or is Rusian Osipov's edit better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T06:44:35.390",
"Id": "81270",
"Score": "0",
"body": "@msh210 It's more concise and just as readable, if not more readable."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:57:29.820",
"Id": "46498",
"ParentId": "46492",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "46498",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:16:59.177",
"Id": "46492",
"Score": "5",
"Tags": [
"python",
"beginner",
"game",
"rock-paper-scissors"
],
"Title": "Rock, Paper, Scissors in Python"
} | 46492 |
<p>I'm learning Haskell and thought it would be fun to write an AI for the game <a href="http://gabrielecirulli.github.io/2048/" rel="nofollow noreferrer">2048</a> in Haskell.</p>
<p>In my implementation I got rid of the randomized aspects of the game.</p>
<p>This makes the program deterministic (or pure). However, I don't think it performs very well. It uses a very simple algorithm:</p>
<p>Recurse into all possible moves with depth <code>x</code> and return the number of empty tiles of the result. The move that results in the highest number of empty tiles is seen as the best move.</p>
<p>I use a 16-length List to represent the board. I am afraid that the many list operations make my program very slow, and wonder if there are better ways to solve this.</p>
<p>The code:</p>
<pre><code>{--
Plays and solves the game 2048
--}
import Data.Time
import Control.Monad
emptyGrid :: [Int]
emptyGrid = [ 0 | _ <- [0..15] ]
-- Display the 16-length list as the 4 by 4 grid it represents
gridToString :: [Int] -> String
gridToString [] = ""
gridToString xs = show (take 4 xs) ++ "\n" ++ gridToString (drop 4 xs)
printGrid :: [Int] -> IO()
printGrid xs = putStrLn $ gridToString xs
-- Skip n empty tiles before inserting
addTile :: Int -> [Int] -> [Int]
addTile 0 (0:grid) = 2 : grid
addTile n [] = []
addTile n (0:grid) = (0 : addTile (n-1) grid)
addTile n (cell:grid) = cell : addTile n grid
-- Insert multiple tiles at once
addTiles :: [Int] -> [Int] -> [Int]
addTiles [] grid = grid
addTiles (n:ns) grid = addTiles ns (addTile n grid)
-- For one row of the grid, push the non-empty tiles together
-- e.g. [0,2,0,2] becomes [2,2,0,0]
moveRow :: [Int] -> [Int]
moveRow [] = []
moveRow (0:xs) = moveRow xs ++ [0]
moveRow (x:xs) = x : moveRow xs
-- For one row of the grid, do the merge (cells of same value merge)
-- e.g. [2,2,4,4] becomes [4,8,0,0]
-- [2,4,2,2] becomes [2,4,4,0]
mergeRow :: [Int] -> [Int]
mergeRow [] = []
mergeRow (a:[]) = [a]
mergeRow (a:b:xs)
| a == b = (a + b) : (mergeRow xs) ++ [0]
| otherwise = a : mergeRow (b:xs)
-- Rotate the grid to be able to do vertical moving/merging
-- e.g. [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
-- becomes [0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15]
rotate :: [Int] -> [Int]
rotate grid = [ grid !! (a + 4 * b) | a <- [0..3], b <- [0..3] ]
-- Use the definitions above to do the moves
move :: Int -> [Int] -> [Int]
move _ [] = []
-- 0=Left, 1=Right, 2=Up, 3=Down
move 0 grid = mergeRow (moveRow (take 4 grid)) ++ move 0 (drop 4 grid)
move 1 grid = reverse (move 0 (reverse grid))
move 3 grid = rotate (move 0 (rotate grid))
move 2 grid = reverse (move 3 (reverse grid))
-- Mapping of move-codes to text
moveToString :: Int -> String
moveToString n = ["Left", "Right", "Up", "Down"] !! n
-- Take a turn, i.e. make a move and add a tile
takeTurn :: Int -> [Int] -> [Int]
takeTurn n grid
| n == -1 = []
| newGrid /= grid = newGrid
| otherwise = []
where newGrid = addTile 0 (move n grid)
maxInList :: Ord a => [a] -> a
maxInList (x:xs) = maxInList_ x xs
maxInList_ :: Ord a => a -> [a] -> a
maxInList_ m [] = m
maxInList_ m (x:xs) = maxInList_ (max m x) xs
-- Find highest tuple in list of pairs.
-- On equality, the first wins
maxTuple :: [(Int,Int)] -> Int
maxTuple [] = -1
maxTuple (x:xs) = secondFromTuple $ maxTuple_ x xs
secondFromTuple :: (a,a) -> a
secondFromTuple (x,y) = y
maxTuple_ :: Ord a => (a,a) -> [(a,a)] -> (a,a)
maxTuple_ x [] = x
maxTuple_ (a,b) ((y,z):xs)
| a >= y = maxTuple_ (a,b) xs
| otherwise = maxTuple_ (y,z) xs
-- Return the best possible move
-- TODO: can the seemingly redundancy be eliminated?
bestMove :: Int -> [Int] -> Int
bestMove depth grid = maxTuple [ (gridValue depth (takeTurn x grid), x) | x <- [0..2], takeTurn x grid /= [] ]
gridValue :: Int -> [Int] -> Int
gridValue _ [] = -1
gridValue 0 grid = length $ filter (==0) grid
gridValue depth grid = maxInList [ gridValue (depth-1) (takeTurn x grid) | x <- [0..2] ]
-- Take turns and prints the result of each move to the console until no more moves are possible
-- n counts the moves
-- Should normally be called with n=0
takeTurns :: Int -> Int -> [Int] -> IO()
takeTurns depth n grid = do
let newGrid = takeTurn (bestMove depth grid) grid
if newGrid /= []
then do
when (n `rem` 100 == 0) $ putStrLn $ "Move " ++ (show n)
-- putStrLn $ "Move " ++ (show n)
-- putStrLn $ gridToString newGrid
takeTurns depth (n+1) newGrid
else do
putStrLn $ gridToString grid
putStrLn $ "Game Over: " ++ (show n) ++ " Turns"
solve :: Int -> IO()
solve depth = takeTurns depth 0 emptyGrid
solveTenTimes :: Int -> IO()
solveTenTimes 10 = putStrLn "Done"
solveTenTimes n = do
start <- getCurrentTime
solve n
stop <- getCurrentTime
putStrLn $ (show n) ++ ": " ++ (show $ diffUTCTime stop start)
solveTenTimes (n+1)
main = do
solveTenTimes 0
</code></pre>
<p><strong>Edit</strong></p>
<p>I posted a revised version here: <a href="https://codereview.stackexchange.com/questions/46760/revised-ai-for-2048-in-haskell">Revised: AI for 2048 in Haskell</a></p>
| [] | [
{
"body": "<p>First of all - way to go! Type signatures, pattern matching, monads - you're clearly on the right track.</p>\n\n<p>Some general tips:</p>\n\n<ol>\n<li><p>Don't reinvent the wheel!</p>\n\n<p>When you encounter a function that looks like this:</p>\n\n<pre><code>secondFromTuple :: (a,a) -> a\nsecondFromTuple (x,y) = y\n</code></pre>\n\n<p>your first thought should be: \"wait, that's a really simple and usefuly function. I wonder if it's already in the standard library?\". Well, let's search <a href=\"http://www.haskell.org/hoogle/\">Hoogle</a> for the type signature <code>(a,a)->a</code>: <a href=\"http://www.haskell.org/hoogle/?hoogle=%28a%2Ca%29-%3Ea\">http://www.haskell.org/hoogle/?hoogle=%28a%2Ca%29-%3Ea</a></p>\n\n<p>The first result is: <code>snd :: (a, b) -> b</code>, which is actually the right function. <code>snd</code> is even more general than <code>secondFromTuple</code> - the latter won't work on <code>(0,\"zero\")</code>, for example, because it's type is <code>(Int,String)</code> and <code>secondFromTuple</code> only work on homogenous tuples.</p>\n\n<p>Another example: <code>maximum</code> is a standard library function that behave just like <code>maxInList</code>. Notice that <code>maxInList []</code> will result in a pattern match failure while <code>maximum []</code> will result in an <code>empty list</code> exception.</p>\n\n<p>Now let's take a look at <code>maxTuple</code>. It takes a list of tuples and return the second item of the tuple with the highest first item. Can we replace it with a standard library function?</p>\n\n<p>Well, the <code>Data.List</code> module contains <code>maximumBy :: (a -> a -> Ordering) -> [a] -> a</code>. The <code>By</code> family of functions - <code>sortBy</code>,<code>nubBy</code> - are variation of standard function like <code>maximum</code>,<code>sort</code> and <code>nub</code>, which compares items using an external comparison function. Usually, and easy way to create one is with the <code>comparing</code> function from <code>Data.Ord</code>. For example, <code>comparing fst</code> is a function that gets 2 tuples and compares them by the first element. So <code>maximumBy (comparing fst)</code> will return the tuple with the highest first item, and <code>snd</code> will return its second item.</p>\n\n<p>So we can rewrite <code>maxTuple</code> as <code>maxTuple xs = snd $ maximumBy (comparing fst)</code>, or in pointfree style - <code>maxTuple = snd . maximumBy (comparing fst)</code>.</p>\n\n<p>There's one small issue here: One, we don't know how <code>maximumBy</code> resolves ties - if it's an issue, you can modify the solution a little, maybe use <code>sortBy</code> or write a different comparison function.</p></li>\n<li><p>If you need to fail - fail</p>\n\n<p><code>maxTuple []</code> returns <code>-1</code>, and that's not a good idea. <code>maxTuple [(0,-1)]</code> returns <code>-1</code> as well - how can you tell if it's a valid result?</p>\n\n<p>If a function encounters an invalid state - you need to report an error. There are several ways to do it - I'll mention two:</p>\n\n<ul>\n<li><p>Throw an error: <code>maxTuple [] = error \"maxTuple: empty list\"</code>. It's the simplest way to do it, and in a small-scale project it's probably the best. The downside is that error-handling is an <code>IO</code> operation, so this error can't be handled in pure code.</p></li>\n<li><p>The <code>Maybe</code> monad:</p>\n\n<pre><code>maxTuple :: [(Int,Int)] -> Maybe Int\nmaxTuple [] = Nothing\nmaxTuple xs = Just $ snd $ maximumBy (comparing fst)\n</code></pre>\n\n<p>This is the safer way to do it. A failure results in <code>Nothing</code>. The caller can then deal with this <code>Nothing</code> instead of simply crashing the program. The downside is that now you need to examine the value of <code>maxTuple</code> before using it, which complicates the code. <code>Data.Maybe</code> and <code>Control.Monad</code> can help with this task.</p></li>\n</ul>\n\n<p>You can read more about proper Haskell error handling in <a href=\"http://www.randomhacks.net/articles/2007/03/10/haskell-8-ways-to-report-errors\">this great article</a>.</p></li>\n<li><p>Use <code>data</code> instead of hardcoded values</p>\n\n<p>Instead of representing directions with 0-3, you can use <code>data</code>:</p>\n\n<pre><code>data Direction = Left | Right | Up | Down\n deriving (Show)\n</code></pre>\n\n<p>Now <code>move</code> is more readable:</p>\n\n<pre><code>move :: Direction -> [Int] -> [Int]\n...\nmove Left grid = ...\nmove Right grid = ...\nmove Down grid = ...\nmove Up grid = ...\n</code></pre>\n\n<p>Also, since there's no 5th direction, <code>move 4</code> results in a pattern match failure. In the new version, there is no such danger.</p>\n\n<p>Plus, <code>deriving (Show)</code> means we can use <code>show</code> on <code>Direction</code> value - so we get <code>moveToString</code> for free: <code>show Left</code> returns \"Left\", <code>show Down</code> returns \"Down\" and so on.</p></li>\n</ol>\n\n<p>That's it for now. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T23:02:10.210",
"Id": "81424",
"Score": "0",
"body": "Thanks for your feedback! I'll definately be upgrading my code with your advice. You're right about using library functions... I don't really know my way in the Haskell libraries yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:59:19.543",
"Id": "81828",
"Score": "0",
"body": "I implemented your feedback and posted a revised version of my code here: http://codereview.stackexchange.com/questions/46760/revised-ai-for-2048-in-haskell It would be great if you could take a look at it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:35:29.397",
"Id": "81889",
"Score": "0",
"body": "Well done! As for the performance issue - have you tried profiling it? GHC has some profiling tools (which I've never used myself)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-03T14:39:37.310",
"Id": "125479",
"Score": "0",
"body": "You have a point!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:28:44.047",
"Id": "46592",
"ParentId": "46493",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46592",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:24:47.097",
"Id": "46493",
"Score": "6",
"Tags": [
"game",
"haskell",
"ai"
],
"Title": "Poor AI for 2048 written in Haskell"
} | 46493 |
<p>To create a Logging system for a larger application, I came up with the following draft. The log sinks aren't detailed yet, but the factory method for logger creation and a rough draft of the logger itself are. Is this a good start and worth continuing? Or are there pitfalls you can see?</p>
<pre><code>class LoggingSink; // abstract base class
class ConsoleSink : public LoggingSink; // some concrete logging sink
class LogfileSink : public LoggingSink; // ... too
/***********************************************/
class Logger {
public:
void log(const std::string& msg) {
for (LoggingSink ls : Sinks)
ls.log(msg);
}
private:
std::list<std::reference_wrapper<LoggingSink>> Sinks;
friend class LoggerFactory;
};
/***********************************************/
class LoggerFactory {
public:
std::unique_ptr<Logger> create() {
std::unique_ptr<Logger> result = std::make_unique<Logger>();
result->Sinks.assign(StandardAssignedSinks.begin(), StandardAssignedSinks.end());
return result;
}
void addStandardSink(LoggingSink& ls) {
Sinks.push_back(std::reference_wrapper<LoggingSink>(ls));
}
private:
std::list<std::reference_wrapper<LoggingSink>> StandardAssignedSinks;
};
/***********************************************/
int main() {
ConsoleSink cs;
LogfileSink lfs("mylogfile.txt");
LoggerFactory lf;
lf.addStandardSink(cs); // adding as reference for polymorphism
lf.addStandardSink(lfs); // perhaps the addition of some standard sinks should be done in the constructor of LoggerFactory???
std::unique_ptr<Logger> myLogger = lf.create();
myLogger->log("Hello Log, I'm going to be injected soon!");
MyClass myClassInstance(myLogger); // constructor dependency injection
MyClass myOtherInstance(lf.create()); // direct DI
}
</code></pre>
<p>I'm also unsure about the friend class. This is something I never really liked with factories. Any ideas how to improve here?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:33:28.857",
"Id": "81220",
"Score": "0",
"body": "Have you looked at [Boost.log](http://boost-log.sourceforge.net/libs/log/doc/html/index.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:38:57.943",
"Id": "81222",
"Score": "0",
"body": "Yes, I looked at it. Seems rational to me. The main reason for this draft is to try out something new and try to get a better understanding for factories, the std::reference_wrapper, dependency injection, ... But thank you for the comment!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:34:16.467",
"Id": "81234",
"Score": "2",
"body": "Two points: 1) In this case I think it is preferable for the factory to retain ownership of a log (thus it would return a reference to `Logger`. 2) I would prefer to be able to use them like a stream rather than calling `log(std::string const&)`. Expected usage: `LoggerFactory::get().log(Logger::Critical) << \"Having fun: FileDS \" << fileDescriptor << \" has generated the error( \" << strerror(errno) << \")\";`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T08:30:08.603",
"Id": "81280",
"Score": "0",
"body": "Correct me if I'm wrong, but `std::make_unique` makes this code C++14, not C++11."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:21:12.897",
"Id": "81285",
"Score": "0",
"body": "@LokiAstari 1) You mean something like a static reference? I'd like to have multiple Loggers, each one with a name. Then I would be able to differentiate between Loggers for subsystems. 2) Yeah, an interface like std::ostream would be nice, that's right!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:23:12.760",
"Id": "81287",
"Score": "0",
"body": "@Morwenn Yes, you are right, that would make it C++14. But as the missing std::make_unique is a mere oversight in C++11, I still like to call it C++11 here ;) See also: http://herbsutter.com/gotw/_102/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T13:03:47.777",
"Id": "81312",
"Score": "0",
"body": "@Martin Since C++14 is but a slight update of C++11 (it mainly fixes stuff, all the big parts have been moved to TS), C++14 really feels like C++11 anyway :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:31:01.923",
"Id": "81347",
"Score": "0",
"body": "@Martin: No you can still name them and create them dynamically. All I am saying is that the factory should **retain ownership**. Because the factory is the owner you return a reference to the object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:33:58.503",
"Id": "81350",
"Score": "0",
"body": "@Martin: Friend info http://programmers.stackexchange.com/a/99595/12917"
}
] | [
{
"body": "<p>As noted in the comments:</p>\n\n<p>I would make the factory retain ownership:</p>\n\n<pre><code>class LoggerFactory {\n\ntypedef std::map<std::string, std::unique_ptr<Logger>> Container;\ntypedef Container::iterator iterator;\ntypedef Container::const_iterator const_iterator;\ntypedef Container::value_type value_type;\n\ntypedef std::list<std::reference_wrapper<LoggingSink>> SinkHolder;\n\npublic:\n Logger& get(std::string const& loggerName = \"default\")\n {\n iterator find = cont.find(loggerName);\n if (find == cont.end())\n {\n\n std::unique_ptr<Logger> result = std::make_unique<Logger>();\n\n // Personally I would not do this.\n // I would pass the iterators to the constructor\n // of the Logger object.\n result->Sinks.assign(std::begin(standardAssignedSinks),\n std::end(standardAssignedSinks));\n\n auto insertR = cont.insert(value_type(loggerName, result));\n if (!insertR.second)\n { throw std::runtime_error(\"Insertion Failed\");\n }\n find = insertR.first; \n }\n return *(find->second);\n }\n\n void addStandardSink(LoggingSink& ls) {\n standardAssignedSinks.empace_back(ls);\n }\n\nprivate:\n SinkHolder standardAssignedSinks;\n Container cont;\n};\n</code></pre>\n\n<p>Now you can have multiple loggers. But you can re-use loggers (as each logger has its own name. Most of the time people should be using the default logger.</p>\n\n<p>Building a streamming logger is not that difficult it just requires an intermediate buffer object to accumulate the message. When it is destroyed it sends the message to the logger.</p>\n\n<pre><code>class Logger {\n public:\n template<typename T>\n LogStreamBuffer operator<<(T const& data) // Member so left hand side implied as Logger\n {\n // This is not perfect\n // This may cause a copy (and thus a destruction)\n // If there is a copy/destruction cycle an extra message will be\n // sent. You can code around this problem.\n // This is just to get you started.\n\n return LogStreamBuffer(*this) << data;\n }\n // OTHER STUFF\n};\nclass LogStreamBuffer\n{\n Logger& parent;\n std::stringstream buffer;\n\n public:\n LogStreamBuffer(Logger& parent)\n : parent()\n {}\n ~LogStreamBuffer()\n {\n // When the object is destroyed.\n // Log the accumulated message with the parent.\n parent.log(buffer.str());\n }\n template<typename T>\n LogStreamBuffer& operator<<(T const& data)\n {\n // Anything you log is just appended to the message.\n buffer << data;\n return *this; // return a reference to yourself.\n // So you can chain messages.\n }\n};\n\n// Usage:\nint main()\n{\n LoggerFactory factory;\n Logger logger = factory.get(\"MyLogger\");\n\n\n logger << \"This is a test: \" << 1 << \" Got it\";\n // ^^^\n // Creates a LogStreamBuffer\n // As an invisable temporary object.\n // The subsequent `operator<<` will accumulate\n // data in the buffer. When the statement is\n // finished (at the ;) all temporaies will be\n // destroyed. This calls the LogStreamBuffer\n // destructor and logs your data to the Logger\n // object. \n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:01:50.910",
"Id": "46567",
"ParentId": "46499",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T21:00:25.533",
"Id": "46499",
"Score": "7",
"Tags": [
"c++",
"c++11",
"logging",
"factory-method"
],
"Title": "C++11 Logging Architecture"
} | 46499 |
<h1>Background</h1>
<p>When a user leaves a page, if they haven't submitted form data, a button is animated to draw the user's attention. (This is a poor UX choice--all the form data should be submitted--but it is what I have to work with at the moment).</p>
<p>Only the text, which is centered on the button, must wiggle: the button itself must not shake.</p>
<h1>Problem</h1>
<p>The solution entails adding a button, a div, and a span. Without these elements, the shaking does not seem to work as desired.</p>
<h1>Code</h1>
<p>Button code:</p>
<pre><code><button type="submit" id="accept-list" style="width:100%"><div style="display:inline-block;width:0 auto;margin:0;padding:0"><span>&#x2714;</span></div></button>
</code></pre>
<p>jQuery code:</p>
<pre><code>$("#accept-list > div > span").effect( "shake", { distance: 5 } );
</code></pre>
<p><a href="http://jsfiddle.net/2Skx2/" rel="nofollow">Fiddle</a></p>
<h1>Question</h1>
<p>What is a simpler way (i.e., that does not require the inner <code>div</code> and <code>span</code> elements) to shake button text, which works cross-browser?</p>
| [] | [
{
"body": "<p>I honestly don't know if this will work properly in all browsers (read: I doubt it), but you could conceivably animate the <code>text-indent</code> property to oscillate between +n and -n.</p>\n\n<p><a href=\"http://jsfiddle.net/96Tdn/\" rel=\"nofollow\">Here's a quick, <em>quick</em> hack</a> based loosely on jQuery UI's own <code>shake</code> effect.</p>\n\n<p>Again, though, I have no idea if this will work any better. It seems pretty neat, but I have a suspicion it won't be as robust as using a <code><button></code> with nested elements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T01:15:46.717",
"Id": "46518",
"ParentId": "46504",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46518",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:13:33.887",
"Id": "46504",
"Score": "1",
"Tags": [
"jquery",
"html",
"css",
"form",
"animation"
],
"Title": "Eliminate nested HTML elements for jQuery animation?"
} | 46504 |
<p>Following-up on <a href="https://codereview.stackexchange.com/questions/46312/creating-adodb-parameters-on-the-fly">Creating ADODB Parameters on the fly</a> and pushing the "wrapping" of ADODB a step further, I have written two more classes that allows me to expose methods that don't require a <code>Connection</code> object, without returning an <code>ADODB.Recordset</code>.</p>
<p>Taking this method as a reference:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Public Function Execute(connection As ADODB.connection, ByVal sql As String, ParamArray parametervalues()) As ADODB.Recordset
Dim Values() As Variant
Values = parametervalues
Dim cmd As ADODB.Command
Set cmd = CreateCommand(connection, adCmdText, sql, Values)
Set Execute = cmd.Execute
End Function
</code></pre>
</blockquote>
<h3>A bit of context</h3>
<p>I'm not comfortable with the idea of exposing a method that would return an <code>ADODB.Recordset</code> without taking in an <code>ADODB.Connection</code>, because this would mean opening a connection in a function that doesn't control when the connection needs to be closed.</p>
<p>To address this issue, I added two private fields to my <code>SqlCommand</code>:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Private connString As String
Private resultFactory As New SqlResult
</code></pre>
</blockquote>
<p>I'm using a pre-determined connection string in <code>Class_Initialize</code> for the <code>connString</code> value:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Private Sub Class_Initialize()
connString = Application.ConnectionString
End Sub
</code></pre>
</blockquote>
<p>I adopted the "Quick" prefix to refer to an "overload" method that owns its own connection, hence the connection-less "overload" for the <code>Execute</code> method above will be called <code>QuickExecute</code>:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Public Function QuickExecute(ByVal sql As String, ParamArray parametervalues()) As SqlResult
Dim parameters() As Variant
parameters = parametervalues
Dim connection As New ADODB.connection
connection.ConnectionString = connString
connection.Open
Dim rs As ADODB.Recordset
Set rs = Execute(connection, sql, parameters)
Set QuickExecute = resultFactory.Create(rs)
rs.Close
Set rs = Nothing
connection.Close
Set connection = Nothing
End Function
</code></pre>
</blockquote>
<p>The method consumes the recordset and returns an object that encapsulates its contents, a <code>SqlResult</code> object.</p>
<hr />
<h3>SqlResult</h3>
<p>This type encapsulates a <code>List<string></code> and a <code>List<SqlResultRow></code> (<a href="https://codereview.stackexchange.com/questions/32618/listt-implementation-for-vb6-vba">see List class here</a>), respectively holding field names and field values for each row.</p>
<p>Property <code>Item</code> has a procedure attribute that makes it the type's <em>default property</em>, and a procedure attribute of -4 on property <code>NewEnum</code> allows iterating the <code>SqlResultRow</code> items with a <code>For Each</code> loop, like this:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Dim sql As String
sql = "SELECT TOP 10 * FROM SomeTable"
Dim cmd As New SqlCommand
Dim result As SqlResult
Set result = cmd.QuickExecute(sql)
Dim row As SqlResultRow
For Each row In result
Debug.Print row("SomeFieldName"), TypeName(row("SomeFieldName"))
Next
</code></pre>
</blockquote>
<p>Here's the code:</p>
<pre class="lang-vb prettyprint-override"><code>Private Type tSqlResult
FieldNames As List
Values As List
ToStringValueSeparator As String
End Type
Private this As tSqlResult
Option Explicit
Private Sub Class_Initialize()
Set this.FieldNames = New List
Set this.Values = New List
this.ToStringValueSeparator = ","
End Sub
Public Property Get ValueSeparator() As String
ValueSeparator = this.ToStringValueSeparator
End Property
Public Property Let ValueSeparator(ByVal value As String)
this.ToStringValueSeparator = value
End Property
Public Sub AddFieldName(name As String)
this.FieldNames.Add name
End Sub
Public Function FieldNameIndex(ByVal name As String) As Long
FieldNameIndex = this.FieldNames.IndexOf(LCase$(name)) - 1
End Function
Public Sub AddValue(value As SqlResultRow)
this.Values.Add value
End Sub
Public Property Get Count() As Long
Count = this.Values.Count
End Property
Public Property Get Item(ByVal index As Long) As SqlResultRow
Set Item = this.Values(index + 1)
End Property
Public Property Get NewEnum() As IUnknown
'Gets an enumerator that iterates through the List.
Set NewEnum = this.Values.NewEnum
End Property
Public Function Create(adoRecordset As ADODB.Recordset) As SqlResult
Dim result As New SqlResult
Dim names As New List
Dim fieldValues As New List
Dim row As ADODB.fields
Dim field As ADODB.field
Dim rowFactory As New SqlResultRow
Dim grabFieldName As Boolean
grabFieldName = True
While Not adoRecordset.BOF And Not adoRecordset.EOF
For Each field In adoRecordset.fields
If grabFieldName Then result.AddFieldName LCase$(Coalesce(field.name, vbNullString))
Next
result.AddValue rowFactory.Create(result, adoRecordset.fields)
grabFieldName = False
adoRecordset.MoveNext
Wend
Set Create = result
End Function
</code></pre>
<hr />
<h3>SqlResultRow</h3>
<p>Each row encapsulates an array of <code>Variant</code> values, and has an <code>Item</code> property (which also has a procedure attribute that makes it the type's <em>default property</em>) that can take either a <code>String</code> representing a field's name, or any number representing a field's index. A <code>ToString</code> method conveniently outputs all field values separated by commas (the actual separator is configurable in the <code>SqlResult</code> class).</p>
<pre class="lang-vb prettyprint-override"><code>Private Type tRow
ParentResult As SqlResult
Values() As Variant
IsEmpty As Boolean
End Type
Private this As tRow
Option Explicit
Private Sub Class_Initialize()
ReDim this.Values(0 To 0)
this.IsEmpty = True
End Sub
Public Property Set ParentResult(value As SqlResult)
Set this.ParentResult = value
End Property
Friend Sub AddValue(ByVal value As Variant)
If Not this.IsEmpty Then ReDim Preserve this.Values(0 To UBound(this.Values) + 1)
this.Values(UBound(this.Values)) = value
this.IsEmpty = False
End Sub
Public Property Get Item(nameOrIndex As Variant) As Variant
If TypeName(nameOrIndex) = "String" Then
Item = GetFieldValueByName(nameOrIndex)
ElseIf IsNumeric(nameOrIndex) Then
Item = GetFieldValueByIndex(nameOrIndex)
Else
'return empty variant
End If
End Property
Private Function GetFieldValueByName(ByVal name As String) As Variant
If Not this.IsEmpty Then GetFieldValueByName = this.Values(this.ParentResult.FieldNameIndex(name))
End Function
Private Function GetFieldValueByIndex(ByVal index As Integer) As Variant
If Not this.IsEmpty Then GetFieldValueByIndex = this.Values(index)
End Function
Public Function Create(parent As SqlResult, fields As ADODB.fields) As SqlResultRow
Dim result As New SqlResultRow
Set result.ParentResult = parent
Dim field As ADODB.field
Dim value As Variant
For Each field In fields
If TypeName(field.value) = "String" Then
value = LTrim(RTrim(Coalesce(field.value, vbNullString)))
Else
value = Coalesce(field.value, vbEmpty)
End If
result.AddValue value
Next
Set Create = result
End Function
Public Function ToString() As String
If this.IsEmpty Then
ToString = TypeName(Me)
Exit Function
End If
Dim result As String
result = Join(this.Values, this.ParentResult.ValueSeparator)
ToString = result
End Function
</code></pre>
<p>The types are retained, so if a query returns a <code>Date</code> field, the type of that value will be <code>Date</code> in the <code>SqlResultRow</code>.</p>
<p>I use a small helper function, <code>Coalesce</code>, to deal with <code>null</code> values. For reference, here's the listing:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Public Function Coalesce(ByVal value As Variant, Optional ByVal value_when_null As Variant = 0) As Variant
Dim return_value As Variant
On Error Resume Next 'supress error handling
If IsEmpty(value) Or IsNull(value) Or (TypeName(value) = "String" And value = vbNullString) Then
return_value = value_when_null
Else
return_value = value
End If
Err.Clear 'clear any errors that might have occurred
On Error GoTo 0 'reinstate error handling
Coalesce = return_value
End Function
</code></pre>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-19T14:03:40.203",
"Id": "115778",
"Score": "1",
"body": "You should try to avoid using SELECT * as it can slow down querying for no good reason.\nSELECT x,y,z is easier to understand and is as fast/faster than SELECT *."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-04T13:17:03.257",
"Id": "331642",
"Score": "0",
"body": "Are you planning to add some filter or sort capabilities to your wrapper?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-04T15:22:12.197",
"Id": "331669",
"Score": "0",
"body": "@UnhandledException why would I want to do that? If I need filtering I can have a `WHERE` clause in the query; if I need sorted results I can have an `ORDER BY` clause... Why not let the database do the hard work for me?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-04T15:41:07.437",
"Id": "331672",
"Score": "0",
"body": "Ok, maybe my intention is too specific. I use an ADODB-Recordset in VBA, which holds many records, which I have to process in different ways. To avoid to many roundtrips to the server I once load all necessary records and then use it offline and filter and sort it locally for each different analysation. It would be nice to get rid of this ADODB.Recordset at all and use a custom, more abstract, approach. Thats why I got the idea that your classes maybe could be enhanced to fulfill that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-04T16:01:32.220",
"Id": "331678",
"Score": "0",
"body": "They could... But I'm pretty sure doing that work in code would be much less efficient than having the database server do it. DB roundtrips aren't free indeed, but to me the costly part is iterating the returned results; the more you iterate them, the less efficient your code is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-04T19:39:07.503",
"Id": "331710",
"Score": "0",
"body": "There's something true about it. After thinking on it, I think it really would be inefficient without any database engine behind."
}
] | [
{
"body": "<p>A quick code inspection with MZ-Tools reveals the following:</p>\n\n<blockquote>\n <p>Local variables <code>names</code>, <code>fieldValues</code> and <code>row</code> can be safely removed from the <code>Create</code> method.</p>\n</blockquote>\n\n<p>That's all the tool is picking up though.</p>\n\n<p>I like how it makes everything <em>automagical</em>, however if it were the only way to get the data I'd be worried about performance with some large recordsets. The <code>List</code> class makes it easier to find a value by field name, but the <em>search</em> for the field name happens every time, which means lots of time is <s>spent</s> <em>wasted</em> finding the same field index over and over again, for each record. Keeping the index for each name in a <code>Dictionary<String,int></code> would be more efficient than having to search for each column index for each row.</p>\n\n<p>That said, <code>SqlCommand</code> has methods that take a <code>ADODB.Connection</code> and output a <code>ADODB.Recordset</code>, having the possibility to use these methods for larger recordsets and let the client code deal with the connection and the recordset, somewhat makes up for the performance hit of the wrapper <code>SqlResult</code>; you get the <em>automagical</em> parameters <em>and</em> the possibility to only iterate the data once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T00:57:45.793",
"Id": "46515",
"ParentId": "46506",
"Score": "7"
}
},
{
"body": "\n\n<p>This loop (in <code>SqlResult.Create</code>):</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>For Each field In adoRecordset.fields\n If grabFieldName Then result.AddFieldName LCase$(Coalesce(field.name, vbNullString))\nNext\n</code></pre>\n</blockquote>\n\n<p>will still iterate all fields even though <code>grabFieldName</code> is <code>False</code>. And since <code>grabFieldName</code> will only be <code>True</code> for the first record, why not just do it like this - and the flag should be called <code>grabFieldNames</code>, since the code is \"grabbing\" <em>all</em> field names:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>If grabFieldNames Then\n For Each field In adoRecordset.fields\n result.AddFieldName LCase$(Coalesce(field.name, vbNullString))\n Next\nEnd If\n</code></pre>\n\n<p>Speaking of <code>AddFieldName</code>, this implementation:</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub AddFieldName(name As String)\n this.FieldNames.Add name\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>Might work for most scenarios, but then if you want to have a <code>Dictionary</code> that maps field names to an index for more efficient field name lookups, a query like <code>SELECT NULL AS Test, NULL AS Test</code> will blow it up, since dictionary keys must be unique.</p>\n\n<p>Given this field (see <a href=\"https://codereview.stackexchange.com/questions/45666/dictionarytkey-tvalue-implementation\">Dictionary implementation here</a>):</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private nameIndices As New Dictionary\n</code></pre>\n\n<p><code>AddFieldName</code> could look like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub AddFieldName(ByVal name As String)\n\n Static nameInstances As New Dictionary\n\n Dim localName As String\n localName = LCase$(name)\n\n If nameIndices.ContainsKey(localName) Then\n\n If nameInstances.ContainsKey(localName) Then\n nameInstances(localName) = nameInstances(localName) + 1\n Else\n nameInstances.Add localName, 1\n End If\n\n AddFieldName name & nameInstances(localName) 'recursive call\n\n Else\n this.FieldNames.Add localName\n nameIndices.Add localName, this.FieldNames.Count - 1\n End If\n\nEnd Sub\n</code></pre>\n\n<p>This way the first <code>Test</code> field will be called <code>Test</code>, and the 2nd one will be called <code>Test1</code>, ensuring uniqueness of the field names. This could be quite surprising to the calling code, though, but selecting identically named columns shouldn't happen very often.</p>\n\n<p>The <code>FieldNameIndex</code> function can then look like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Function FieldNameIndex(ByVal name As String) As Long\n\n Dim i As Long\n If nameIndices.TryGetValue(name, i) Then\n FieldNameIndex = i\n Else\n FieldNameIndex = -1\n End If\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-05-14T19:04:10.713",
"Id": "49757",
"ParentId": "46506",
"Score": "3"
}
},
{
"body": "\n\n<p>I want to focus on the <code>SqlResult</code>/<code>SqlResultRow</code> classes here. The way it is, it is analogous to having bought a huge expensive truck then insisting on driving the original dinky car that you wouldn't trade in and paying the payments on both the truck and the dinky car. </p>\n\n<p><strong>Why?</strong></p>\n\n<p>Because you're basically taking an <code>ADODB.Recordset</code> object, a full-featured entity that provides sorting, filtering, jumping to an arbitrary position, and few more. That's your expensive truck. You then painstakingly copy the contents of the recordset into a custom collection which has much less features... that's your dinky car. </p>\n\n<p>Now, you are doing this for encapsulation and that's <em>not a bad thing</em> at all! However, what I propose is that instead of copying the content from a recordset to a custom collection, that you use the <code>ADODB.Recordset</code> as the implementation underneath the <code>SqlResult</code> class. </p>\n\n<p>That way, it becomes very easy to wrap methods like sorting, filtering, jumping what have you. The consumers of the <code>SqlResult</code> class need not know about the recordset under the hood driving the class. </p>\n\n<p><strong>But, I don't want the connection leaking!</strong></p>\n\n<p>And that's a legit concern! However, with an <code>ADODB.Recordset</code>, it is easy to manage this. What you actually want is a disconnected recordset. That way, the contents of the recordset are all available in the user's computer's memory and there's no dangling connection. What you should do is basically something like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Function Execute(connection As ADODB.connection, ByVal sql As String, ParamArray parametervalues()) As ADODB.Recordset\n\n Dim Values() As Variant\n Values = parametervalues\n\n Dim cmd As ADODB.Command\n Set cmd = CreateCommand(connection, adCmdText, sql, Values)\n\n 'Configure the recordset to use client-side snapshot\n 'which is the only valid option for disconnected recordset\n 'It needs not be readonly but updatable disconnected recordset\n 'is needlessly complicating things anyway.\n Dim rs As ADODB.Recordset\n Set rs = New ADODB.Recordset\n With rs\n .CursorLocation = adUseClient\n .CursorType = adOpenStatic\n .LockType = adLockReadOnly\n End With\n\n 'Load the recordset with result of the command\n 'We can't assign rs directly from the Execute method of the cmd\n 'or it'll coerce it to the wrong type of the recordset\n rs.Open cmd\n\n 'Disconnect the recordset\n Set rs.ActiveConnection = Nothing \n\n Set Execute = rs\n\nEnd Function\n</code></pre>\n\n<p>Now we have a disconnected recordset that can be browsed, iterated, etc. and then provided to the <code>SqlResult</code> class. </p>\n\n<p>That way the consumers need not know about the implementation of ADO but you still get all the goodness of <code>ADODB.Recordset</code> without incurring any extra costs and you can then modify the <code>SqlResult</code> class to wrap various features on the <code>ADODB.Recordset</code> for essentially free. By the same token, <code>SqlResultRow</code> is easier, since you can leverage the <code>ADODB.Record</code> or something similar. Now you're actually driving that fancy expensive truck, something you <em>would</em> have gotten anyway even if you didn't really needed all the features it has to offer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T14:38:24.873",
"Id": "430149",
"Score": "0",
"body": "I'm struggling to put this into use... \"Cannot modify the `ActiveConnection` property of a `Recordset` object using a `Command` as a data source\" on `Set rs.ActiveConnection = Nothing`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T19:00:37.497",
"Id": "430197",
"Score": "0",
"body": "It's a client-side static recordset, right? That's the only type that can be disconnected."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-04-25T21:44:22.320",
"Id": "192953",
"ParentId": "46506",
"Score": "5"
}
},
{
"body": "<p>Is there any reason you don't use a disconnected record set and just close the connection in the function that opened it? I wouldn't keep a connection open any longer than you need.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>Untitled Document</title>\n</head>\n\n<body>\n<p>This is a way I've found useful. The general idea is never keeping the connection open any longer than you have to. </p>\n<pre>\nSub RunQuery()\n ' You can declare as many arrays as you need\n Dim RS1 As Variant\n Dim ParameterValues As String\n ParameterValues = \"You can change this as needed\"\n\n RS1 = GetDiscRecordset(ParameterValues)\n\n For c = LBound(RS1, 1) To UBound(RS1, 1)\n\n For r = LBound(RS1, 2) To UBound(RS1, 2)\n\n ' Iterate through the recordset\n Debug.Print RS1(c, r)\n\n\n Next r\n\n Next c\nEnd Sub\n</pre>\n\n<p>The <b>GetDiscRecordset</b> function is similar to your execute function but we are returning a <i>Disconnected</i> recordset.</p>\n<pre>\nFunction GetDiscRecordset(ParameterValues As String) As Variant\n Dim Qry As String\n\n Qry = \"Select * From SourceTable Where [?PlaceHolder for Parameters?]\" 'Modify as needed\n\n Qry = Replace(Qry, \"[?PlaceHolder for Parameters?]\", ParameterValues)\n\n Dim Conn As ADODB.connection\n\n Set Conn = New ADODB.connection\n\n Dim Rst As ADODB.Recordset\n\n Conn.ConnectionString = \"Connection String\" 'Modify as needed\n\n Conn.Open\n\n Set Rst = New ADODB.connection\n\n Set Rst.ActiveConnection = Conn\n\n ' Retrieve data\n Rst.CursorLocation = adUseClient\n\n Rst.LockType = adLockBatchOptimistic\n\n Rst.CursorType = adOpenStatic\n\n Rst.Open Qry, , , , adCmdText '<- we set the rst stuff above so thats cool, thats our recordset\n\n ' NOW DISCONNECT RECORDSET HERE!\n Set Rst.ActiveConnection = Nothing\n\n Rst.MoveFirst\n ' Pass the recordset back\n GetDiscRecordset = Rst.GetRows\nEnd Function\n\n</pre>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-16T20:40:42.367",
"Id": "396755",
"Score": "0",
"body": "Disconnected recordset is a very good point - if I wrote this today I'd scrap the `SqlResult` wrapper and return a disconnected recordset instead. The methods that take a connections parameter don't own it though, and thus shouldn't close it - they exist so that the code that owns the connection can initiate a transaction and run multiple commands before committing or rolling back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-16T20:41:43.537",
"Id": "396756",
"Score": "0",
"body": "That said this looks more like a comment than an answer IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-16T20:50:44.197",
"Id": "396759",
"Score": "1",
"body": "I agree with Mathieu here. As it stands this is not really an answer and more of a clarifying comment. If you could expand a bit on the point you're making and change the tone of the text to something more \"answer\"-y, that'd be appreciated. If you prefer to keep it like this, I can convert this to a comment for you. Just give me a heads up. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-16T20:38:10.663",
"Id": "205709",
"ParentId": "46506",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "192953",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-06T22:21:36.233",
"Id": "46506",
"Score": "13",
"Tags": [
"sql",
"vba",
"vb6",
"adodb"
],
"Title": "Materializing any ADODB Query"
} | 46506 |
<p>This program is for a class project and requires me to read data from a text file then display a list of totals. Here are the instructions/requirements:</p>
<blockquote>
<p>The fields in each record will be separated by a comma.</p>
<p>Format: Age, Gender, Marital Status, District#</p>
<p>For example: 18, M, S, 2</p>
<p>The city has 22 districts. The census department wants to see a
listing of how many residents are in each district, and a count of
residents in each of the following age groups (for all the districts
combined): under 18, 18 through 30, 31 through 45, 46 through 64, and
65 or older.</p>
</blockquote>
<p>The only way I can get this to work was using a bunch of <code>if</code> statements (which is bad I've been told). Is there a way for me to just read through the data and put the correct age/district number in an array, then display the totals for the each Age Group (groups 1-5) and District (1-22)?</p>
<p>So say each time the program reads age 18 and district 2 for example, it will add 1 to Age Group 1 and 1 to District 2 that element and so on? Then at the end just display the results? I just barely learned about array and I don't know how I can do this.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Project2
{
class Program
{
static void Main(string[] args)
{
int[] ageData = new int[900];
int[] districtDataA = new int[900];
int[] ageGroup = new int[5];
int[] districtCount = new int[22];
int i = 0;
foreach (string line in File.ReadAllLines("test.txt"))
{
string[] fields = line.Split(',');
ageData[i] = int.Parse(fields[0]);
districtDataA[i] = int.Parse(fields[3]);
if (ageData[i] > 0 && ageData[i] <= 18)
{
ageGroup[0] = ageGroup[0] + 1;
}
if (ageData[i] > 18 && ageData[i] <= 30)
{
ageGroup[1] = ageGroup[1] + 1;
}
if (ageData[i] > 30 && ageData[i] <= 45)
{
ageGroup[2] = ageGroup[2] + 1;
}
if (ageData[i] > 45 && ageData[i] <= 64)
{
ageGroup[3] = ageGroup[3] + 1;
}
if (ageData[i] >= 65)
{
ageGroup[4] = ageGroup[4] + 1;
}
//District Count info
if (districtDataA[i] == 1)
{
districtCount[0] = districtCount[0] + 1;
}
if (districtDataA[i] == 2)
{
districtCount[1] = districtCount[1] + 1;
}
if (districtDataA[i] == 3)
{
districtCount[2] = districtCount[2] + 1;
}
if (districtDataA[i] == 4)
{
districtCount[3] = districtCount[3] + 1;
}
if (districtDataA[i] == 5)
{
districtCount[4] = districtCount[4] + 1;
}
if (districtDataA[i] == 6)
{
districtCount[5] = districtCount[5] + 1;
}
if (districtDataA[i] == 7)
{
districtCount[6] = districtCount[6] + 1;
}
if (districtDataA[i] == 8)
{
districtCount[7] = districtCount[7] + 1;
}
if (districtDataA[i] == 9)
{
districtCount[8] = districtCount[8] + 1;
}
if (districtDataA[i] == 10)
{
districtCount[9] = districtCount[9] + 1;
}
if (districtDataA[i] == 11)
{
districtCount[10] = districtCount[10] + 1;
}
if (districtDataA[i] == 12)
{
districtCount[11] = districtCount[11] + 1;
}
if (districtDataA[i] == 13)
{
districtCount[12] = districtCount[12] + 1;
}
if (districtDataA[i] == 14)
{
districtCount[13] = districtCount[13] + 1;
}
if (districtDataA[i] == 15)
{
districtCount[14] = districtCount[14] + 1;
}
if (districtDataA[i] == 16)
{
districtCount[15] = districtCount[15] + 1;
}
if (districtDataA[i] == 17)
{
districtCount[16] = districtCount[16] + 1;
}
if (districtDataA[i] == 18)
{
districtCount[17] = districtCount[17] + 1;
}
if (districtDataA[i] == 19)
{
districtCount[18] = districtCount[18] + 1;
}
if (districtDataA[i] == 20)
{
districtCount[19] = districtCount[19] + 1;
}
if (districtDataA[i] == 21)
{
districtCount[20] = districtCount[20] + 1;
}
if (districtDataA[i] == 22)
{
districtCount[21] = districtCount[21] + 1;
}
i++;
}//End For
Console.WriteLine("This program provides a list of residents in 5 age groups,");
Console.WriteLine("And a list of residents in each district 1-22");
Console.WriteLine("(1.)----------------AGE-GROUP-Count----------------");
Console.WriteLine("Age Group 18 & under = {0}", ageGroup[0]);
Console.WriteLine("Age Group 18-30 = {0}", ageGroup[1]);
Console.WriteLine("Age Group 31-45 = {0}", ageGroup[2]);
Console.WriteLine("Age Group 46-64 = {0}", ageGroup[3]);
Console.WriteLine("Age Group 65 & over = {0}", ageGroup[4]);
Console.WriteLine("(2.)--------------COUNT-PER-DISRTRICT--------------");
Console.WriteLine("District 1 = {0}", districtCount[0]);
Console.WriteLine("District 2 = {0}", districtCount[1]);
Console.WriteLine("District 3 = {0}", districtCount[2]);
Console.WriteLine("District 4 = {0}", districtCount[3]);
Console.WriteLine("District 5 = {0}", districtCount[4]);
Console.WriteLine("District 6 = {0}", districtCount[5]);
Console.WriteLine("District 7 = {0}", districtCount[6]);
Console.WriteLine("District 8 = {0}", districtCount[7]);
Console.WriteLine("District 9 = {0}", districtCount[8]);
Console.WriteLine("District 10 = {0}", districtCount[9]);
Console.WriteLine("District 11 = {0}", districtCount[10]);
Console.WriteLine("District 12 = {0}", districtCount[11]);
Console.WriteLine("District 13 = {0}", districtCount[12]);
Console.WriteLine("District 14 = {0}", districtCount[13]);
Console.WriteLine("District 15 = {0}", districtCount[14]);
Console.WriteLine("District 16 = {0}", districtCount[15]);
Console.WriteLine("District 17 = {0}", districtCount[16]);
Console.WriteLine("District 18 = {0}", districtCount[17]);
Console.WriteLine("District 19 = {0}", districtCount[18]);
Console.WriteLine("District 20 = {0}", districtCount[19]);
Console.WriteLine("District 21 = {0}", districtCount[20]);
Console.WriteLine("District 22 = {0}", districtCount[21]);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T23:03:17.117",
"Id": "81235",
"Score": "3",
"body": "Please use spaces instead of tabs here. Tabs mess up the markdown."
}
] | [
{
"body": "<p>Try to visualize how your items are related. Think how your code runs, step by step, like in slow-mo. You will realize you can sum up long and tedious code into simplest, more abstract, styles.</p>\n<p>Let me start from the last portion of your code:</p>\n<pre><code> Console.WriteLine("District 1 = {0}", districtCount[0]);\n Console.WriteLine("District 2 = {0}", districtCount[1]);\n Console.WriteLine("District 3 = {0}", districtCount[2]);\n //etc etc\n</code></pre>\n<p>If you find yourself writing repetitive lines as you have here, there is almost always a better way to code that. Here, a simple loop makes sense:</p>\n<pre><code>for (int i = 1; i <= 22; i++)\n {\n Console.WriteLine("District {0} = {1}", i, districtCount[i-1]);\n }\n</code></pre>\n<p>That makes it short and readable, less convoluted. We merely extracted the 1,2,3... and the 0,1,2... into <code>i</code> and <code>i-1</code> respectively.</p>\n<p>Now using the same "trick" you can replace all your ifs (which should have been if else's in the first place) with <strong>just a single line</strong>:</p>\n<pre><code>districtCount[districtDataA[i] - 1]++;\n</code></pre>\n<p><strong>BONUS</strong>: When you want to type <code>variable = variable + 1</code> it's shorter and more readable if you type <code>variable++</code> instead. Same with <code>variable--</code>. For different amounts, you can do <code>variable += amount</code> (also <code>-=</code>, <code>*=</code>, <code>/=</code> and more operators depending on the language)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-07T00:54:16.847",
"Id": "46514",
"ParentId": "46507",
"Score": "6"
}
},
{
"body": "<p>Your <code>if</code> blocks that are detirmining theage bracket can be shortened:</p>\n\n<pre><code>if (ageData[i] > 0 && ageData[i] <= 18)\n{\n ageGroup[0] = ageGroup[0] + 1;\n}\nif (ageData[i] > 18 && ageData[i] <= 30)\n{\n ageGroup[1] = ageGroup[1] + 1;\n}\nif (ageData[i] > 30 && ageData[i] <= 45)\n{\n ageGroup[2] = ageGroup[2] + 1;\n}\nif (ageData[i] > 45 && ageData[i] <= 64)\n{\n ageGroup[3] = ageGroup[3] + 1;\n}\nif (ageData[i] >= 65)\n{\n ageGroup[4] = ageGroup[4] + 1;\n}\n</code></pre>\n\n<p>can become and iterative approach by putting the ranges in a data sctructure. Keeping with your style using arrays.</p>\n\n<p>First you declare:</p>\n\n<pre><code> int[] ageGroup = new int[5];\n int[] ageGroupLimit = new int[] {17, 30, 45, 64, int.MaxValue};\n</code></pre>\n\n<p>then you loop through the data:</p>\n\n<pre><code>for(int groupID=0; groupID < ageGroupLimit.Length; groupID++)\n{\n if(ageData[i] <= ageGroupLimit[groupID])\n {\n ageGroup[groupID]++;\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T04:57:22.657",
"Id": "81264",
"Score": "0",
"body": "Thank you, I am getting an error for the `ageGroupLimit.length;` saying \"'System.Array' does not contain a definition for 'length'...\" I'm not sure what the error means."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T04:59:53.630",
"Id": "81265",
"Score": "0",
"body": "@proppaganda it should be `.Length` If you use an IDE with auto completion/intellisense you should be able to find these things yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T05:17:00.203",
"Id": "81266",
"Score": "0",
"body": "Ah I see, thank you. I did not realize it needed to be capitalized."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:08:07.530",
"Id": "46521",
"ParentId": "46507",
"Score": "1"
}
},
{
"body": "<p>One way to shorten the code determining the age group is to use a Dictionary. the key is the age the value is the agegroup index. One relatively simple way to fill the dictionary is with LINQ:</p>\n\n<pre><code>AgeGroups = (from i in Enumerable.Range(0, 19)\n select new\n {\n key = i,\n value = 0\n }).ToDictionary(x => x.key, x => x.value);\nAgeGroups = AgeGroups.Concat((from i in Enumerable.Range(19, 12)\n select new\n {\n Key = i,\n Value = 1\n }).ToDictionary(x => x.Key, x => x.Value)).ToDictionary(x => x.Key, x => x.Value);\nAgeGroups = AgeGroups.Concat((from i in Enumerable.Range(31, 15)\n select new\n {\n Key = i,\n Value = 2\n }).ToDictionary(x => x.Key, x => x.Value)).ToDictionary(x => x.Key, x => x.Value);\nAgeGroups = AgeGroups.Concat((from i in Enumerable.Range(46, 19)\n select new\n {\n Key = i,\n Value = 3\n }).ToDictionary(x => x.Key, x => x.Value)).ToDictionary(x => x.Key, x => x.Value);\n</code></pre>\n\n<p>This creates a dictionary with 65 elements with the value of each element the appropriate agegroup index.</p>\n\n<p>You build this once.</p>\n\n<p>Shortening the district code is simply matter of subtracting 1 from the district number to get the appropriate index.</p>\n\n<p>If there's a chance the size of the data wil be large, you should consider reading each line separately rather than all of them together.</p>\n\n<p>With all this in mind the code to fill your arrays looks like this:</p>\n\n<pre><code>using(StreamReader lines = new StreamReader(\"test.txt\"))\n{\n int i = 0;\n while(!lines.EndOfStream)\n {\n string[] fields = lines.ReadLine().Split(',');\n\n ageData[i] = int.Parse(fields[0]); \n districtDataA[i] = int.Parse(fields[3]);\n\n if(AgeGroups.ContainsKey(ageData[i]))\n ageGroup[AgeGroups[ageData[i]]]++;\n else\n ageGroup[4]++;\n districtCount[districtDataA[i++] - 1]++;\n }\n}\n</code></pre>\n\n<p>Notice how you still need one loop but you're not storing the whole file in memory. Also, the only if statement is to check for the top age group.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:57:42.170",
"Id": "46525",
"ParentId": "46507",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "46514",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T22:50:55.140",
"Id": "46507",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Census Data Display from Text File"
} | 46507 |
<p>This is something I wrote as a reply to a deleted "Rock/paper/scissors [updated]" question. Since I can't post it as an answer (and the line-by-line analysis is gone as well), it might be nice to get a code review.</p>
<pre><code>"""A game of rock/paper/scissors."""
import random
SIGNS = ("rock", "paper", "scissors")
VERBS = ("crushes", "covers", "cut")
YES = ("yes", "y")
class Counter(object):
"""Keep track of game session scores."""
def __init__(self):
self.rounds = 0
self.losses = 0
self.wins = 0
self.draws = 0
self.rounds_total = 0
self.losses_total = 0
self.wins_total = 0
self.draws_total = 0
def increment(self, state):
"""Increment losses, wins, draws.
Args:
state: "losses", "wins", or "draws".
Raises:
ValueError: If input is invalid.
"""
if state not in ["losses", "wins", "draws"]:
raise ValueError("Acceptable input: losses, wins, or draws.")
for attr in (state, "%s_total" % state, "rounds", "rounds_total"):
setattr(self, attr, getattr(self, attr) + 1)
def flush(self):
"""Restart the current game counters, keep the total counters."""
self.rounds = 0
self.losses = 0
self.wins = 0
self.draws = 0
def print_results(self):
print "Games played: ", self.rounds
print "Games won: ", self.wins
print "Games lost: ", self.losses
print "Games drawn: ", self.draws
print "Total played: ", self.rounds_total
print "Total won: ", self.wins_total
print "Total lost: ", self.losses_total
print "Total drawn: ", self.draws_total
class Sign(object):
"""A rock/paper/scissors sign."""
def __init__(self, sign):
global SIGNS
if sign not in SIGNS:
raise ValueError("Allowed signs are: %s." % SIGNS.join(", "))
self.sign = sign
def __eq__(self, other):
try:
if self.sign == other.sign:
return True
except AttributeError:
pass
return False
def __gt__(self, other):
if (self.sign == "rock" and other.sign == "scissors" or
self.sign == "scissors" and other.sign == "paper" or
self.sign == "paper" and other.sign == "rock"):
return True
return False
def __lt__(self, other):
return not self.__gt__(other)
def main(max_rounds=5):
global SIGNS
global VERBS
global YES
counter = Counter()
while True:
if counter.rounds == max_rounds:
counter.print_results()
again = raw_input("Play/again? (Y/n) ").lower()
if again in YES:
counter.flush()
else:
print "Bye!"
break
while True:
player_sign = raw_input("Rock/paper/scissors? ").lower()
if player_sign not in SIGNS:
print "Only following words are valid: %s." % SIGNS.join(" ,")
continue
break
player = Sign(player_sign)
computer = Sign(random.choice(SIGNS))
if player > computer:
counter.increment("wins")
verb = VERBS[SIGNS.index(player.sign)]
print "Player wins: %s %s %s." % (player.sign, verb, computer.sign)
elif player == computer:
counter.increment("draws")
print "It's a draw! Both played %s." % player.sign
else:
counter.increment("losses")
verb = VERBS[SIGNS.index(computer.sign)]
print "Player lost: %s %s %s." % (computer.sign, verb, player.sign)
if __name__ == "__main__":
main(max_rounds=5)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T07:22:57.313",
"Id": "81275",
"Score": "4",
"body": "Consider using `__str__` for `print_results` and returning a string. Then you can use the built in `print` with a counter."
}
] | [
{
"body": "<p>So this all looks pretty good, with not much to review. I didn't see the previous question, so I will throw my two cents in here.</p>\n\n<p>You define the following at the top of your file:</p>\n\n<pre><code>SIGNS = (\"rock\", \"paper\", \"scissors\")\nVERBS = (\"crushes\", \"covers\", \"cut\")\nYES = (\"yes\", \"y\")\n</code></pre>\n\n<p>which is fine. However in all the classes where you use these variable you denote them with the <code>global</code> keyword. This isn't code breaking, but it is unnecessary. The <code>global</code> key word is used for global variables. What you are using is global constants that are defined at module scope, so you can get rid of those redundant lines.</p>\n\n<p>It was suggested in the comments that you replace the <code>print_results</code> function by <code>__str__</code>, but I would actually suggest replacing it by <code>__repr__</code>. In cases where <code>__str__</code> is not defined <code>__repr__==__str__</code> anyways. So:</p>\n\n<pre><code>def __repr__(self):\n return \"\\n\".join(\n [\"Games played: %d\"%self.rounds,\n \"Games won: %d\"%self.wins,\n \"Games lost: %d\"%self.losses,\n \"Games drawn: %d\"%self.draws,\n \"Total played: %d\"%self.rounds_total,\n \"Total won: %d\"%self.wins_total,\n \"Total lost: %d\"%self.losses_total,\n \"Total drawn: %d\"%self.draws_total])\n</code></pre>\n\n<p>This will allow you to print the object nicely with <code>print counter</code>.</p>\n\n<p>These are all ultra minor things now:</p>\n\n<p>The block</p>\n\n<pre><code>def __eq__(self, other):\n try:\n if self.sign == other.sign:\n return True\n except AttributeError:\n pass\n return False\n</code></pre>\n\n<p>has a redundant <code>pass</code> and redundant branch. This could be condensed to:</p>\n\n<pre><code>def __eq__(self, other):\n try:\n return (self.sign == other.sign)\n except AttributeError:\n return False\n</code></pre>\n\n<p>In a similar vain, there is no need to branch in <code>__gt__</code> method:</p>\n\n<pre><code>def __gt__(self, other):\n return (self.sign == \"rock\" and other.sign == \"scissors\" or\n self.sign == \"scissors\" and other.sign == \"paper\" or\n self.sign == \"paper\" and other.sign == \"rock\")\n</code></pre>\n\n<p>and the <code>__lt__</code> method:</p>\n\n<pre><code>def __lt__(self, other):\n return not self.__gt__(other)\n</code></pre>\n\n<p>is both redundant and incorrect (as pointed out in the comments, this is actually a less than or equal to that is written here, as any value that is not greater than will return true) and can be removed (the default version calls <code>__gt__</code> and should handle your problem fine).</p>\n\n<p>Finally for clarity I would define <code>VERBS</code> as a dictionary. It is more code, but it is also more readable:</p>\n\n<pre><code>VERBS = {\"rock\":\"crushes\", \"paper\":\"covers\", \"scissors\":\"cut\"}\n</code></pre>\n\n<p>this allows you to do the following in the main function:</p>\n\n<pre><code>verb = VERBS[player.sign]\n</code></pre>\n\n<p>and</p>\n\n<pre><code>verb = VERBS[computer.sign]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:27:55.887",
"Id": "81344",
"Score": "0",
"body": "Agreed with all. Regarding `global` definitions - I added those to be explicit (for the reader) that the constants come from the outer scope and whoever's reading my code shouldn't look for them in a method name. It does make the meaning ambiguous though - since `global` is used to change global variables (reader might think I am trying to change the constants)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:03:53.617",
"Id": "81420",
"Score": "1",
"body": "@RuslanOsipov agreed. The first thing I did when I saw the code was to look for where those variables were being changed. The `global` keyword is frowned upon in most python code (although it has its uses) and should be avoided unless you really need it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:01:18.990",
"Id": "46565",
"ParentId": "46508",
"Score": "6"
}
},
{
"body": "<ul>\n<li>Since we apparently speak the same language, I understand why you picked <code>sign</code>, but for most of the audience <code>symbol</code> would me more meaningful.</li>\n</ul>\n\n<p>Consider the following a design (rather than code) review.</p>\n\n<ul>\n<li><p>The game has a nice mathematical property which begs to be exploited. Notice that if we assign numerical values to the objects, namely <code>Rock = 0, Paper = 1, Scissors = 2</code>, then</p>\n\n<pre><code>(val1 - val2) % 3\n</code></pre></li>\n</ul>\n\n<p>defines the outcome of the round (0 is draw, 1 means first player wins, and 2 means second player wins). This totally eliminates a need for a Sign class.</p>\n\n<ul>\n<li>It would be nice to separate a generic game playing functionality from the specifics of the particular game. It would also be nice to abstract players (at least to test separate strategies).</li>\n</ul>\n\n<p>That said, here is the core of the game (sorry, no play again feature):</p>\n\n<pre><code># Game specific code\nimport random\n\nvalue = { 'r': 0, 'p': 1, 's': 2 }\ntext = [ 'R', 'P', 'S' ]\n\ndef human_play():\n while True:\n move = raw_input('R/P/S?').lower()\n try:\n return value[move]\n except KeyError:\n print 'invalud input'\n\ndef comp_play():\n return random.randrange(0, 3)\n\ndef round(p1, p2):\n v1 = p1()\n v2 = p2()\n return v1, v2, (v1 - v2) % 3\n\n# Generic code\noutcome = [ 'drawn', 'won', 'lost' ]\n\nclass Counter:\n def __init__(self):\n self.played = 0\n self.results = [0] * 3\n def add(self, result):\n self.played += 1\n self.results[result] += 1\n def show(self):\n print 'played: %d' % self.played\n print '; '.join(['%s: %d' % (o, r) for (o, r) in zip(outcome, self.results)])\n\ndef game(p1, p2, max_rounds = 5):\n counter = Counter()\n for _ in range(max_rounds):\n v1, v2, result = round(p1, p2)\n print '%s .. %s: %s' % (text[v1], text[v2], outcome[result])\n counter.add(result)\n return counter\n\ndef main():\n results = game(human_play, comp_play)\n results.show()\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T00:15:37.580",
"Id": "46979",
"ParentId": "46508",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46565",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T23:11:52.147",
"Id": "46508",
"Score": "11",
"Tags": [
"python",
"game",
"rock-paper-scissors"
],
"Title": "Rock, paper, scissors"
} | 46508 |
<p>Perform a graph clone. Verifying complexity to be O(E). Looking for code review, optimizations and best practices. </p>
<pre><code>class NodeOfGraph<T> {
private final T item;
NodeOfGraph(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
public class GraphWithCloneFunctionality<T> implements Iterable<NodeOfGraph<T>> {
/*
* A map from nodes in the graph to list of outgoing edges.
*/
private final Map<NodeOfGraph<T>, Map<NodeOfGraph<T>, Double>> graph;
public GraphWithCloneFunctionality() {
graph = new HashMap<NodeOfGraph<T>, Map<NodeOfGraph<T>, Double>>();
}
public GraphWithCloneFunctionality(Map<NodeOfGraph<T>, Map<NodeOfGraph<T>, Double>> graph) {
if (graph == null) {
throw new NullPointerException("The graph should not be null");
}
this.graph = graph;
}
/**
* Adds a new node to the graph. If the node already exists then its a
* no-op.
*
* @param node Adds to a graph. If node is null then this is a no-op.
* @return true if node is added, false otherwise.
*/
public boolean addNode(NodeOfGraph<T> node) {
if (node == null) {
throw new NullPointerException("The input node cannot be null.");
}
graph.put(node, new HashMap<NodeOfGraph<T>, Double>());
return true;
}
/**
* Given the two nodes it would add an arc from source
* to destination node.
*
* @param node1 the node1 node.
* @param node2 the node2 node.
* @param length if length if string
* @throws NullPointerException if node1 or nod2 is null.
* @throws NoSuchElementException if either node1 or node2 does not exists.
*/
public void addEdge (NodeOfGraph<T> node1, NodeOfGraph<T> node2, double length) {
if (node1 == null || node2 == null) {
throw new NullPointerException("node1 and node2, both should be non-null.");
}
if (!graph.containsKey(node1) || !graph.containsKey(node2)) {
throw new NoSuchElementException("node1 and node2, both should be part of graph");
}
graph.get(node1).put(node2, length);
graph.get(node2).put(node1, length);
}
@Override
public Iterator<NodeOfGraph<T>> iterator() {
return graph.keySet().iterator();
}
/**
* Given a node, returns the edges going outward that node,
* as an immutable map.
*
* @param node The node whose edges should be queried.
* @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null.
* @throws NoSuchElementException If node is not in graph.
*/
public Map<NodeOfGraph<T>, Double> edgesFrom(NodeOfGraph<T> node) {
if (node == null) {
throw new NullPointerException("The node should not be null.");
}
final Map<NodeOfGraph<T>, Double> edges = graph.get(node);
if (edges == null) {
throw new NoSuchElementException("Source node does not exist.");
}
return Collections.unmodifiableMap(edges);
}
/**
* Clones the graph. Performs deep copy.
*/
public GraphWithCloneFunctionality<T> clone() {
final Map<NodeOfGraph<T>, Map<NodeOfGraph<T>, Double>> clonedGraph = new HashMap<NodeOfGraph<T>, Map<NodeOfGraph<T>, Double>>();
final Map<NodeOfGraph<T>, NodeOfGraph<T>> cloneMap = new HashMap<NodeOfGraph<T>, NodeOfGraph<T>>();
for (NodeOfGraph<T> node : graph.keySet()) {
NodeOfGraph<T> clonedNode = new NodeOfGraph<T>(node.getItem());
clonedGraph.put(clonedNode, new HashMap<NodeOfGraph<T>, Double>());
cloneMap.put(node, clonedNode);
}
for (Entry<NodeOfGraph<T>, Map<NodeOfGraph<T>, Double>> entry : graph.entrySet()) {
NodeOfGraph<T> source = entry.getKey();
NodeOfGraph<T> sourceClone = cloneMap.get(source);
Map<NodeOfGraph<T>, Double> edges = entry.getValue();
for (Entry<NodeOfGraph<T>, Double> edge : edges.entrySet()) {
NodeOfGraph<T> destination = edge.getKey();
NodeOfGraph<T> destinationClone = cloneMap.get(destination);
clonedGraph.get(sourceClone).put(destinationClone, edge.getValue());
}
}
return new GraphWithCloneFunctionality<T>(clonedGraph);
}
public static void main(String[] args) {
GraphWithCloneFunctionality<Integer> graph = new GraphWithCloneFunctionality<Integer>();
NodeOfGraph<Integer> nodeA = new NodeOfGraph<Integer>(1);
NodeOfGraph<Integer> nodeB = new NodeOfGraph<Integer>(2);
NodeOfGraph<Integer> nodeC = new NodeOfGraph<Integer>(3);
graph.addNode(nodeA);
graph.addNode(nodeB);
graph.addNode(nodeC);
graph.addEdge(nodeA, nodeB, 10);
graph.addEdge(nodeB, nodeC, 20);
GraphWithCloneFunctionality<Integer> graphClone = graph.clone();
for (NodeOfGraph<Integer> node : graphClone) {
System.out.print("Node-> " + node.getItem() + " Edges-> ");
for (Entry<NodeOfGraph<Integer>, Double> node1 : graphClone.edgesFrom(node).entrySet()) {
System.out.print(" Node : " + node1.getKey().getItem() + " value : " + node1.getValue() + " , ");
}
System.out.println();
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Clone is an ugly API. <a href=\"http://www.artima.com/intv/bloch13.html\" rel=\"noreferrer\">Josh Bloch has a lot to say about it.</a></p>\n<p>My opinion on it, is that you should use it as a last resort, and, when you do use it, it should be a short-cut to a public copy-constructor.</p>\n<p>In other words, your clone method should look like:</p>\n<pre><code>public GraphWithCloneFunctionality<T> clone() {\n return new GraphWithCloneFunctionality<T>(this);\n}\n</code></pre>\n<p>This way, you have the benefit of the Copy-Constructor, and the functionality of the clone as well, if needed.</p>\n<p>After having said all that, I can't see any other significant issues in your code's functionality. It looks about right, and nice and clean.</p>\n<p>If you create a copy-constructor, it would look something like:</p>\n<pre><code>public GraphWithCloneFunctionality(GraphWithCloneFunctionality<T> tocopy) {\n this(copyGraph(tocopy.graph));\n}\n</code></pre>\n<p>The copyGraph function would copy the graph, believe it or not.</p>\n<p>Talking about graph-copying, this constructor should take a defensive copy of the <code>graph</code> as well. You don't want to have leaks of graph functionality to outside your class...</p>\n<blockquote>\n<pre><code>public GraphWithCloneFunctionality(Map<NodeOfGraph<T>, Map<NodeOfGraph<T>, Double>> graph) {\n if (graph == null) {\n throw new NullPointerException("The graph should not be null");\n }\n this.graph = graph;\n}\n</code></pre>\n</blockquote>\n<p>The above <code>this.graph = graph</code> is not safe. Use <code>this.graph = copyGraph(graph);</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T00:45:38.857",
"Id": "81240",
"Score": "0",
"body": "But I wanted deep-copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T00:48:02.430",
"Id": "81241",
"Score": "0",
"body": "@JavaDeveloper You can do a deep-copy in the constructor just as easily as you do it in the clone.... also, added more detail to answer (submitted early by mistake)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T00:38:15.967",
"Id": "46511",
"ParentId": "46510",
"Score": "6"
}
},
{
"body": "<p>Your <code>clone()</code> method looks very nice, and I don't have much to say about it except Good Work.</p>\n\n<p>I've read the code a few times, and even then I almost missed this:</p>\n\n<pre><code>/**\n * Adds a new node to the graph. If the node already exists then its a\n * no-op.\n * \n * @param node Adds to a graph. If node is null then this is a no-op.\n * @return true if node is added, false otherwise.\n */\npublic boolean addNode(NodeOfGraph<T> node) {\n if (node == null) {\n throw new NullPointerException(\"The input node cannot be null.\");\n }\n graph.put(node, new HashMap<NodeOfGraph<T>, Double>());\n return true;\n}\n</code></pre>\n\n<p>The comment assures the caller that trying to add a node which already exists will be no-op and return false.<br>\nIn actuality - it will override the existing node, deleting all out-going edges, and return true...</p>\n\n<p>This is another example of how a good unit-test suite is a better documentation than comments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:57:25.783",
"Id": "46549",
"ParentId": "46510",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T23:41:51.740",
"Id": "46510",
"Score": "6",
"Tags": [
"java",
"algorithm",
"graph",
"reinventing-the-wheel"
],
"Title": "Clone of an undirected graph"
} | 46510 |
<p>I have been reading about SQL injection and I want to secure my code.</p>
<p>I am not asking anyone to write me a code, but I just want to learn it in simple terms. The best way for me to learn is to edit my code so I can compare them.</p>
<pre><code><?php
if (isset ($_POST['email'])) {
//Connect to the database through our include
include_once "config/connect.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysqli_real_escape_string($db_conx, $email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = "SELECT * FROM members WHERE email='$email' AND password='$password'";
$query = mysqli_query($db_conx, $sql);
$login_check = mysqli_num_rows($query);
if($login_check > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
// Get member ID into a session variable
$id = $row["id"];
session_register('id');
$_SESSION['id'] = $id;
// Get member username into a session variable
$username = $row["username"];
$email = $row["email"];
$password = $row["password"];
$firstname = $row["firstname"];
$lastname = $row["lastname"];
session_register('username');
session_register('firstname');
session_register('lastname');
// Update last_log_date field for this member now
$sql = "UPDATE members SET lastlogin=now() WHERE id='$id'";
$query = mysqli_query($db_conx, $sql);
// Print success message here if all went well then exit the script
header("location: members/index.php?id=$id");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
header("location: login.php");
exit();
}
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T00:53:57.503",
"Id": "81242",
"Score": "1",
"body": "*The best way for me to learn is to edit my code so I can compare them.* I'm not so sure about that. We *review* code here, so no one will just be editing your code to make it better. Any answers you receive will offer *suggestions* based on your provided code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T08:10:30.483",
"Id": "81278",
"Score": "0",
"body": "@Jamal, and I am not asking anyone to edit my code for me. I need suggestions and I will do the editing myself! We review code here, so no one will just be editing your code to make it better. who is \"we\" by the way? so far not a single suggestion apart from your unhelpful comment!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T08:19:49.313",
"Id": "81279",
"Score": "0",
"body": "I apologize for misunderstanding you, then. And by \"we,\" I mean reviewers on this site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:48:44.773",
"Id": "81292",
"Score": "0",
"body": "funny, 22 people viewed this and not a single person contributed!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T11:34:16.807",
"Id": "81294",
"Score": "0",
"body": "@roozfar: I'm hesitant to review your code, because any review I post, will be dated after you apply my critiques to your code. The code you've posted should not be edited, so future visitors can _see_ what the reviewer(s) are talking about (ie: the original code)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:36:10.813",
"Id": "81305",
"Score": "1",
"body": "@roozfar: Right, I've gone ahead and posted some critiques. If you perceive them as harsh, blunt or find some of it offensive, I understand. But know that I'm only trying to help. In order to do so, [as I've explained here in great detail](http://meta.codereview.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag), I must be severe :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T13:59:50.090",
"Id": "81319",
"Score": "0",
"body": "@EliasVanOotegem I believe terrible code for beginners is the fault of google for infesting non PDO practice - but then again if you learn from the terrible code its not as bad as putting it in production."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-06T09:04:57.187",
"Id": "336301",
"Score": "0",
"body": "view this link http://allinonescript.com/questions/60174/how-can-i-prevent-sql-injection-in-php/"
}
] | [
{
"body": "<p>So, you want to defend against possible injection attacks. That's great. But I struggle to understand why you're bothering to escape all parameters in various ways, but then let the whole thing down by not using the easiest, fastest and rather safe tool you have: <strong><em>prepared statements</em></strong>.</p>\n\n<p>First off, are prepared statements 100% safe, all of the time? No, I'm not going to postulate that. Simply because I don't have a solid basis (as in proof) that it is.<Br>\nHave I seen injection attacks of the first order that managed to circumvent the security gotten from prepared statements? Nope. Never. So, as long as you're not using <code>mysqli_multi_query</code>, don't use user-data in tandem with data gotten from another query and you don't allow yourself to get bogged down in endless sub-queries or JOIN queries without aliases, you should be pretty safe.</p>\n\n<p>So, first step in defending against inject: use prepared statements.</p>\n\n<p>Now, look at what you're doing with your data:</p>\n\n<pre><code>$email = stripslashes($_POST['email']);\n$email = strip_tags($email);\n$email = mysqli_real_escape_string($db_conx, $email);\n$password = preg_replace(\"[^A-Za-z0-9]\", \"\", $_POST['password']);\n$password = md5($password);\n</code></pre>\n\n<p>Email:<br>\nWhat's wrong with how you process the email? A couple of things.</p>\n\n<ul>\n<li><code>stripslashes</code>: can potentially change email addresses that are <em>perfectly valid</em>! However unusual an email address is, you have the responsibility to write code that can handle <em>valid</em> input.<br>\nThis is a valid email address: <code>\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com</code>, believe it or not. <code>stripslashes</code>, then, is NOT an option. <a href=\"http://en.wikipedia.org/wiki/Email_address\" rel=\"nofollow\">See other wacky email addresses here</a>.</li>\n<li><code>striptags</code>: I take it that, from the example here, and on the wiki I linked to, it's self-evident that this function call is right out, for the same reasons.</li>\n</ul>\n\n<p>What to do, then? Simple. PHP comes with an email validator function out of the box, simply use that:</p>\n\n<pre><code>if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))\n $email = $_POST['email'];\nelse\n //error.\n</code></pre>\n\n<p>If you want to be lenient towards your users, which I'd encourage, you can add a sanitation call to this code. If the email address posted contains invalid chars, then notify the user and ask him/her if he meant to write a valid version of the address:</p>\n\n<pre><code>if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))\n{//not the !<-- not valid\n echo $_POST['email'], ' is not a valid email address. Did you mean: ',\n filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);//<-- sanitize\n}\n</code></pre>\n\n<p>Password:<br>\nWhat's wrong with the password? A few things.</p>\n\n<ul>\n<li><p>first off: you're going to hash the password. An md5 hash is guaranteed to contain <em>only</em> hex chars (0-9a-f). These chars pose no risk at all in terms of injection.<br>\nIf you want to inform the user about him/her using an <em>\"invalid\"</em> password, however, a regex can come in handy. However, the one you're using now is not going to work!</p></li>\n<li><p><code>preg_replace</code>: You are <em>not</em> replacing what you thing you are. In PHP, a regex has to be delimited by special chars (for example: <code>/a/</code> matches <code>a</code>). Of course, delimiters like <code>[</code> and <code>]</code> are allowed, too. That means that PHP doesn't interpret your pattern as a character class, but rather.</p></li>\n</ul>\n\n<p>It is translated to this:</p>\n\n<pre><code>preg_replace('/^A-Za-z0-9/', '', $string);\n</code></pre>\n\n<p>You're matching the beginning of the string, followed by the <strong><em>literal</em></strong> string: <code>A-Za-z0-9</code>. This will be replaced, the rest is left as is.<br>\nJust test:</p>\n\n<pre><code>echo preg_replace(\"[^A-Za-z0-9]\", '', 'Hello World!');\n</code></pre>\n\n<p>Which <em>should</em> replace the space and exclamation mark. The actual output, however, is: <code>Hello World!</code>.<br>\nI take it you were actually going for something along the lines of:</p>\n\n<pre><code>echo preg_replace('/[^A-Za-Z0-9]/', '', 'Hello World!');\n</code></pre>\n\n<p>Which echoes <code>HelloWorld</code>. But actually, it's a good thing this code doesn't work. You're actually prohibiting users from entering a safer password. Which pass, according to you (and according to common sense) would be most likely to be cracked using a simple dictionary attack:</p>\n\n<pre><code>mySimplePass\n//or\n|\\/|y=5!mpL3_P@55\n</code></pre>\n\n<p>Allow complex passes, you have no reason not to.</p>\n\n<ul>\n<li><code>md5</code>: Ok, it's good to see you're hashing passwords. It really is. But <code>md5</code> is deemed unsafe. <a href=\"http://www.mscs.dal.ca/~selinger/md5collision/\" rel=\"nofollow\">Collisions have been spotted in the wild</a>, and thus it's likely that there are several passwords that will be accepted as valid for a single hash.<Br>\n<code>sha1</code> is a safer option, but best switch to <code>blowfish</code>.</li>\n</ul>\n\n<p>Another niggle when using hash functions is: never simply hash the pass. use <em>salt</em>. If I were to create a dummy account, and at some point saw the hash you were using, I could figure out what type of hashing algorithm you are using, and I would <em>know</em> you're not using salt.<br>\nIn that case, all I need is to see someone elses salt and set my machine to work, generating random strings and computing the hash. For every match I find, I have access to another users' account on your site.</p>\n\n<p>Couple this to your policy of forcing people to use weak passes and you must admit, you have a huge security problem on your hands.<br>\nIn case you don't know what I mean by salt: </p>\n\n<pre><code>$hash = sha1($pass, 'S0me->53cr3t<>5tr!~');\n</code></pre>\n\n<p>That way, I'd first have to generate random strings, in the off chance I find the salt, which is of unknown length, can contain any char, and even when I get a matching hash (in case of md5 especially), I could be dealing with a false positive (collision...).</p>\n\n<p>Moving on: Like I said: use prepared statements, instead of just stringing arguments into a query string, for starters. Then, do away with the <code>mysqli_num_rows</code> call. All your code is contained within a <code>while</code> loop. If there are no results to be found, the loop body won't be executed. Instead, I'd simply write a single query: </p>\n\n<pre><code>$stmt = mysqli_prepare(\n $db_conx,\n 'UPDATE members\n SET lastlogin=NOW()\n WHERE email = ?\n AND password = ?'\n);\n//after validation, of course\nmysqli_stmt_bind_param($stmt, 'ss', $email, $pass);\nmysqli_stmt_execute($stmt);\nif (mysqli_affected_rows($db_conx))\n{\n mysqli_stmt_close($stmt);//<-- CLEAN UP AFTER YOURSELF!\n //update was successful\n}\n</code></pre>\n\n<p>Of course, this code doesn't select username, first and last name from the table. If you want to do so, then you'll have to keep the second query, still. </p>\n\n<p>There, too, your code can be improved on. <code>SELECT *</code> is something that can, and should be avoided as much as possible: <em>only <code>SELECT</code> what you need</em>!<br>\nIf the supplied email and pass are valid, you already have that data, so there's no reason to query for it again. You only need 4 fields: the id, user-, first- and last name.<br>\nNot only is selecting what you need easier on your server, it makes life of the people who end up maintaining your code (and that includes you, yourself) a lot easier if ever something needs to be changed/added a couple of weeks from now:</p>\n\n<pre><code>$stmt = mysqli_prepare(\n $db_conx,\n 'SELECT id, username, firstname, lastname\n FROM members\n WHERE email = ?\n AND password = ?'\n);\nmysqli_bind_param($stmt, 'ss', $email, $pass);\nif (!mysqli_stmt_execute($stmt))//returns false on success\n throw new RuntimeException('Failed to execute statement');\n//get the result first\n$result = mysqli_stmt_get_result($stmt);\n//or $row = mysqli_fetch_assoc($result)\nif ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))\n{\n $_SESSION['id'] = $row['id'];//and so on\n //AND CLEAN UP!!\n mysqli_free_result($result);\n mysqli_stmt_close($stmt);\n}\n</code></pre>\n\n<p>As you can see, the <code>mysqli_*</code> extension offers a lot of powerful features, and tools. In return, it does require you to take care of a couple of things: freeing the results, closing the statements when you're done playing with them etc...<br>\nIt takes some getting used to at first, but it's not that hard, really.</p>\n\n<p>If you find this a bit too wearisome (can't blame you if you do), then take a look at <a href=\"http://www.php.net/PDO\" rel=\"nofollow\">the alternative extension <code>PDO</code></a>.<br>\nIt offers a cleaner, less verbose API. The trade-off: it's OO-only (IMO, a good thing), slightly less powerful and marginally slower, but not as if you'd notice. Other things are far more likely to be the bottleneck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:05:07.223",
"Id": "81321",
"Score": "1",
"body": "Question for you - do you think it was necessary to preg_match the password if you are going to hash it? Unless you are specifically telling the user for particular sequence required (ie ur password must contain 1 cap, 1 special char...etc), why not just use the hash algorithm straight"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:14:09.787",
"Id": "81326",
"Score": "0",
"body": "@azngunit81: `preg_match` as a validation tool in this case is, indeed, completely pointless and silly. A hash like md5 is guaranteed to yield a string of `0-91-f` chars only. I thought about adding that, but I got carried away with explaining why the regex the OP used was wrong, and he'd probably never know about it. will edit, though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:20:49.737",
"Id": "81360",
"Score": "0",
"body": "@EliasVanOotegem, Thanks for the explanation. I just wish you did explain it the other way round (easier way \"PDO\" first and a link to learn the hard way) lol... non the less, appreciate it mate...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:46:22.847",
"Id": "81382",
"Score": "0",
"body": "@roozfar: Well, this is code-review after all... I have to start from what you give me: your code. Anyway, glad I could help. Just a side-note: On stack-exchange sites, the help section asks _not_ to post thank you comments, but to mark an answer as accepted (by clicking the big check-mark next to the answer in question), and/or upvoting the answer. If you accept an answer, you get an extra +2 rep reward to encourage accepting answers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:57:57.523",
"Id": "81385",
"Score": "0",
"body": "@EliasVanOotegem, i am still trying to learn what you said in your answer so just to be honest to myself, I won't mark this as the answer as it really doesn't makes sense to me as of yet! however, +1 for your explanation and effort to write that up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T07:14:13.203",
"Id": "81452",
"Score": "0",
"body": "@roozfar: If there's anything in particular you're having trouble understanding, let me know. I can add links, more details and references to my answer if it helps. Of course, for me to do so, I need to know which part of my answer needs clarifying"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:46:26.620",
"Id": "81704",
"Score": "0",
"body": "@EliasVanOotegem, have you tried your own suggestions mate? there seem to be something wrong as I'm keep getting a page full of errors running your little code! also, i think you meant `mysqli_stmt_close($stmt);` i think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:29:18.120",
"Id": "81712",
"Score": "0",
"body": "@roozfar: Yes, you're absolutely right, I did mean `mysqli_stmt_close` not `mysql_close_stmt`, edited that. No I did not run this code, it's all written off the top of my head, so it could very well contain bugs. I'm just offering advice, not ready-made code, after all. Hope things are beginning to make sense to you... if not, let me know what needs clarification"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T14:57:48.760",
"Id": "81747",
"Score": "0",
"body": "@EliasVanOotegem, would be good if you could answer this question so I won't get confused please: http://codereview.stackexchange.com/questions/46730/warning-mysqli-fetch-array-expects-parameter-1-to-be-mysqli-result-boolean-g"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:02:26.297",
"Id": "81749",
"Score": "0",
"body": "@roozfar: My mistake, I haven't used the `mysqli_*` extension in quite some time. To get the result set of a statement, you have to use `mysqli_stmt_fetch`, as [the docs clearly state](http://www.php.net/manual/en/mysqli-stmt.fetch.php)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:07:37.550",
"Id": "81753",
"Score": "0",
"body": "@roozfar: Just spent some time browsing through the documentation. `mysqli_*` is \"blessed\" with a tricky, and at times down right messy API, so oddities like this won't be uncommon. However, I've edited my last snippet of code: calling `mysqli_stmt_get_result($stmt);` returns the `mysqli_result` resource/object, which you can then use in the loop to call `mysqli_fetch_assoc` on"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:23:58.403",
"Id": "81758",
"Score": "0",
"body": "I did try your edited code and now i get `Fatal error: Call to undefined function mysqli_stmt_get_result() in`. I have no idea what I'm doing even though spent days reading and reading."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T06:52:58.577",
"Id": "81882",
"Score": "0",
"body": "@roozfar: Odd, because [the function is documented](http://www.php.net/mysqli-stmt.get-result). However, it wasn't added till PHP5.3. What version are you running, if it's 5.2 you really ought to update, as 5.2 is no longer supported"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:54:36.247",
"Id": "81898",
"Score": "0",
"body": "@EliasVanOotegem, I am using php version 5.3.28."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:19:26.970",
"Id": "81909",
"Score": "0",
"body": "@roozfar: The first comment on the doc page explains the problem: You need the mysql native driver (mysqlnd) for this function to work. [You can get it here](https://dev.mysql.com/downloads/connector/php-mysqlnd/)"
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:34:22.347",
"Id": "46546",
"ParentId": "46512",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T00:46:16.107",
"Id": "46512",
"Score": "2",
"Tags": [
"php",
"mysql",
"security"
],
"Title": "How to prevent SQL injection PHP and MySQL?"
} | 46512 |
<p>I have next/previous buttons on my site and all they do is slide sections of the site from left to right and vice versa, it is smooth and looks good on a desktop but on mobile devices it is a bit slow and jumpy. </p>
<pre><code>if (type == "prev") {
$(this).hide('drop', { direction: 'right' }, 600, function () { $('#dv' + page).show('drop', { direction: 'left' }, 600), $("input:text:visible:not([readonly]):first").focus(); });
} else {
$(this).hide('drop', { direction: 'left' }, 600, function () { $('#dv' + page).show('drop', { direction: 'right' }, 600), $("input:text:visible:not([readonly]):first").focus(); });
}
</code></pre>
<p>Uses the built in jQuery functions to slide the current page out and the next/previous page in based on the current page number, then sets the focus on the first input box.</p>
<p>This was as simple as I could think to do it but maybe there is a better smoother way to do left/right transitions?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T13:40:13.580",
"Id": "81316",
"Score": "0",
"body": "There is not much to code review really. You will have more luck on Stackoverflow."
}
] | [
{
"body": "<p>It sounds like the issue isn't really the code, just the performance of the hardware: A mobile device just can't redraw everything as fast as a desktop browser. Writing stuff in single lines does not increase performance!</p>\n\n<p>However, you could try the hardware acceleration \"hack\" <a href=\"https://stackoverflow.com/q/10814178/167996\">shown and explained here</a>. </p>\n\n<p>You should also consider using CSS transforms to do the actual animation, rather than jQuery's <code>position: absolute</code> trickery. <a href=\"http://caniuse.com/#feat=transforms2d\" rel=\"nofollow noreferrer\">All modern browsers (with the exception of Opera Mobile) support it</a>, and such transforms are always hardware accelerated.</p>\n\n<p>Lastly, since this is Code Review, I'd advice you to get rid of the repetition in your code:</p>\n\n<pre><code>var PAGE_SWAP_DURATION = 600; // define this once\n\nfunction swapPage(outgoingPage, incomingPage, type) {\n var outDirection = type === \"prev\" ? \"right\" : \"left\",\n inDirection = type === \"prev\" ? \"left\" : \"right\";\n\n outgoingPage.hide('drop', { direction: outDirection }, PAGE_SWAP_DURATION, function () {\n incomingPage.show('drop', { direction: inDirection }, PAGE_SWAP_DURATION, function () {\n // wait for the animation to finish; this is a complex selector\n // so it may cause the browser to stutter\n incomingPage.find(\"input:text:visible:not([readonly]):first\").focus();\n });\n });\n}\n</code></pre>\n\n<p>Apropos that selector: If possible, it would be better to find the correct input ahead of time, rather than run and re-run such a complex query on each page swap.</p>\n\n<p>For instance, you could map out what inputs belong to what pages when the site first loads, and link them to their respective pages with <code>.data()</code>. Or you could give the inputs IDs or class names, which will make the selector much simpler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T22:18:47.460",
"Id": "81627",
"Score": "0",
"body": "Thanks for the optimization tip. I did `.find` to make it more dynamic so we would not have to modify the JS should extra fields be added in the future. But I will look at binding the inputs as suggested and see if that helps with the speed of it all. \nSo css transitions are faster/smoother on mobile devices? I will also look at those for the transition effect and post back the results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T22:45:29.547",
"Id": "81633",
"Score": "0",
"body": "@Jake Yes, CSS transforms are generally smoother because they use the GPU. How much smoother depends on the browser, the hardware, and of course content being transformed. So YMMV, but it should help. As for the selector, I think you'll see the most improvement by simply running it after the animation is done (as in the code above). But if you can simplify it, or run it ahead of time, all the better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T23:01:33.220",
"Id": "81636",
"Score": "0",
"body": "I am using ASP.NET MVC for the site, so all fields are given an ID automatically based on their model name so can't really use the id as a dynamic selector. I do plan on changing it to a class selector though and just add the page number as a class to the first input for each page. should see roughly a [80% performance improvement](http://jsperf.com/complex-vs-direct-input-selectors)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T23:58:40.417",
"Id": "81640",
"Score": "0",
"body": "@Jake Nice - I suspected it'd be a significant boost, but that's impressive. But note that it'll only impact the animation if it's being run at the same time - which you should still avoid. But a nice improvement in its own right, though, so definitely go for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:54:22.767",
"Id": "81825",
"Score": "0",
"body": "Just on quick question regarding the use of CSS instead. How do I trigger the CSS animations to begin on the click event of a link/button? I have the classes set up, do I just add the transition class using JS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:36:23.277",
"Id": "81890",
"Score": "0",
"body": "@Jake Yup, that's the usual way of doing it. You can also skip the CSS animations and simply use JS to directly change the `transform:` property the same way that jQuery UI's effects usually change `left:` or `top:` to move things around. But CSS keyframes should be even better - just make sure it's the `transform` property you're using to do it, since that's what makes the hardware acceleration kick in"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T00:42:43.250",
"Id": "82022",
"Score": "0",
"body": "Thanks for all the help @Flambino. I did end up using `@keyframes` and the `transform: translateZ(0)` attribute as it seemed to do the smoothest animation. It is still a little jumpy, but smoother than it was using jQuery."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T13:41:01.060",
"Id": "46550",
"ParentId": "46517",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46550",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T01:09:04.077",
"Id": "46517",
"Score": "4",
"Tags": [
"javascript",
"optimization",
"jquery",
"mobile"
],
"Title": "Smoothen page transition for mobile devices"
} | 46517 |
<p>I'm designing a small account/password manager using C# and SQL Server CE. LINQ to SQL is my ORM of choice.</p>
<p>Here's the data model representing how the SQL Server CE database is set up:</p>
<p><img src="https://i.stack.imgur.com/uAcvZ.png" alt="Data Model"></p>
<p>And here's my GUI with a cheesy color-coding system to show how the data is mapped to the GUI:</p>
<p><img src="https://i.stack.imgur.com/Aoptk.png" alt="enter image description here"></p>
<p>Since the user is able to dynamically add whatever fields and columns they want, I can't simply bind the DataGridView to a table or collection. Instead, the DataGridView's columns, rows, and cells each have to be populated separately and manually.</p>
<p>Below is my implementation. It gets the job done, but it's TERRIBLY SLOW! We're talking 5-6 seconds to populate the DataGridView with only 10 accounts and 10 fields. The implementation just feels clunky. I've considered creating a DataTable and binding that to the DataGridView, but I would still have to manually populate the columns and rows, and it would be harder without the Tag property to identify columns, rows, and cells. Any suggestions to improve anything ranging from my database design to my GUI are welcome!</p>
<p><strong>Business Logic Methods</strong> </p>
<pre><code> public static List<Account> GetAccountsByCategory(int categoryID)
{
using (PassShedEntities context = new PassShedEntities())
{
return context.Account.Where(a => a.Category_id == categoryID).OrderBy(a => a.Id).ToList();
}
}
public static Credential GetCredential(int accountID, int fieldID)
{
using (PassShedEntities context = new PassShedEntities())
{
return (from c in context.Credential
join f in context.Field on c.Field_id equals f.Id
join a in context.Account on c.Account_id equals a.Id
where c.Account_id == accountID
where f.Id == fieldID
select c).SingleOrDefault();
}
}
public static List<Field> GetFieldsByCategoryID(int categoryID)
{
using (PassShedEntities context = new PassShedEntities())
{
return context.Field.Where(f => f.Category_id == categoryID).OrderBy(f => f.Display_index).ToList();
}
}
</code></pre>
<p><strong>Populate Fields (DataGridView Columns)</strong></p>
<pre><code> private void PopulateFields(int categoryID)
{
dgvShed.Columns.Clear();
foreach (Field field in FieldLogic.GetFieldsByCategoryID(categoryID))
{
DataGridViewColumn fieldColumn = new DataGridViewTextBoxColumn();
fieldColumn.Name = field.Label;
fieldColumn.HeaderText = field.Label;
fieldColumn.Tag = field.Id;
if (field.Display_index != null)
{
fieldColumn.DisplayIndex = (int)field.Display_index;
}
dgvShed.Columns.Add(fieldColumn);
}
}
</code></pre>
<p><strong>Populate Accounts (DataGridView Rows)</strong> </p>
<pre><code> private void PopulateAccounts(int categoryID)
{
dgvShed.Rows.Clear();
foreach (Account account in AccountLogic.GetAccountsByCategory(categoryID))
{
DataGridViewRow accountRow = new DataGridViewRow();
accountRow.Tag = account.Id;
foreach (DataGridViewColumn column in dgvShed.Columns)
{
Credential credential = CredentialLogic.GetCredential(account.Id, (int)column.Tag);
DataGridViewTextBoxCell credCell = new DataGridViewTextBoxCell();
credCell.Tag = credential.Id;
credCell.Value = credential.Value;
accountRow.Cells.Add(credCell);
}
dgvShed.Rows.Add(accountRow);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T17:33:39.317",
"Id": "84354",
"Score": "5",
"body": "I'd question the design of the thing, a password manager should treat passwords as first-class citizens - if it's just another text *field*, you have a potential security issue."
}
] | [
{
"body": "<p>What you call <em>business logic methods</em> is actually your <em>data access logic</em>. And you've put that in a bunch of <code>static</code> methods on what I'm assuming is a <code>static</code> class, which means the GUI code / \"populate fields/accounts\" is <em>tightly coupled</em> with that specific data access logic implementation (<code>AccountLogic</code>); I'd make them instance methods and <em>inject</em> an instance of <code>AccountLogic</code> and <code>CredentialLogic</code> as a dependency, into the constructor of whoever needs it.</p>\n\n<hr>\n\n<p>Your data model <em>seems</em> to have <em>navigation properties</em>. Your code isn't using them:</p>\n\n<pre><code> return (from c in context.Credential\n join f in context.Field on c.Field_id equals f.Id\n join a in context.Account on c.Account_id equals a.Id\n where c.Account_id == accountID\n where f.Id == fieldID\n select c).SingleOrDefault();\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>return context.Credential\n .Where(c => c.Account_id == accountID && c.Field.ID == fieldID)\n .SingleOrDefault();\n</code></pre>\n\n<p>Not sure whether/how it would affect performance though, but definitely clearer.</p>\n\n<hr>\n\n<pre><code>foreach (Account account in AccountLogic.GetAccountsByCategory(categoryID))\n{\n ...\n}\n</code></pre>\n\n<p>Might have zero performance impact, but I find this cleaner:</p>\n\n<pre><code>var accounts = AccountLogic.GetAccountsByCategory(categoryID)\nforeach (var account in accounts)\n{\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>As for performance, I'd be tempted to blame WinForms and constant redrawing taking place - try to disable the refreshing of the DGV's as you're manipulating them; I'm pretty sure WinForms is redrawing the grid every time a column is added, and that requires quite a lot of computing that's not needed until you're done adding all the columns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T16:34:51.443",
"Id": "84526",
"Score": "1",
"body": "I've updated the design here quite tremendously since this was posted, but your suggestions were still helpful. My updates actually include some of your suggestions.\n\nMy biggest performance problem (a \"duh\" moment) was that the GetCredential() method - which joins 3 tables - was nested within two foreach loops. I restructured that by retrieving the credentials beforehand and iterating through a list of them instead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T18:06:24.647",
"Id": "48076",
"ParentId": "46519",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48076",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T02:02:01.950",
"Id": "46519",
"Score": "12",
"Tags": [
"c#",
"performance",
"sql-server",
"winforms",
"linq-to-sql"
],
"Title": "Password Manager UI: Populating DataGridView is Painfully Slow"
} | 46519 |
<p>I'm writing away for this website, and I've come into a problem. I need to display only one <code>td</code> based on the corresponding radio button pressed. However, there are two 'master' radio buttons that dictate how many radio buttons are shown, and after that, which are selected. - if that makes any sense!</p>
<p>Now, I am only showing a very small snippet of what I actually have at the moment - this nested if statement goes on 5 more times. So, as you can probably imagine, it looks horrendous. And I'm not sure if there is a better way, maybe there is a way to create functions that can be called? What do you all think?</p>
<pre><code>$('input:radio').change(function () {
if (this.id == prodMoveRadio) {
if ($("#ExtIdTd").is(":visible") === true) {
$("#ExtIdTd").css({ visibility: "hidden" });
$("#LocIdTd").css({ visibility: "visible" });
$("#" + locIdRadio).prop("checked", true);
$("#ExtIdTr").css({ visibility: "hidden" });
}
else {
$("#MainContent_DetailsPanel").css({ visibility: "hidden" });
$("#ExtIdTr").css({ visibility: "hidden" });
$("#LocIdTd").css({ visibility: "visible" });
$("#" + locIdRadio).prop("checked", true);
}
}
else if (this.id == opMoveRadio) {
if ($("#ExtIdTd").is(":visible") === false) {
$("#ExtIdTr").css({ visibility: "visible" });
$("#ExtIdTd").css({ visibility: "visible" });
}
else {
$("#MainContent_DetailsPanel").css({ visibility: "visible" });
$("#" + extIdRadio).prop("checked", true);
$("#ExtIdTr").css({ visibility: "visible" });
$("#ExtIdTd").css({ visibility: "visible" });
$("#LocIdTd").css({ visibility: "hidden" });
}
}
</code></pre>
<p><strong>Edit</strong></p>
<p>Would it be 'clean' to put a class onto the <code>td</code>'s I need to hide, and hide that whole class then set only the visibility to <code>visible</code> on the <code>td</code> I require? Thoughts?</p>
| [] | [
{
"body": "<p>You could use polymorphism to represent the states, and to apply the needed formatting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:36:23.227",
"Id": "81260",
"Score": "0",
"body": "Reading up on them now, and they seem to be exactly what I'm after. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:34:55.323",
"Id": "46523",
"ParentId": "46522",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46523",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:16:05.560",
"Id": "46522",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"asp.net",
"css"
],
"Title": "Horrible nested if statement for changing CSS based on RadioButton selection"
} | 46522 |
<p>The code I want to refactor look as following:</p>
<pre><code>public bool CheckPay(Int64 orderID)
{
vpc_OrderInfo = orderID;
RequestParams =
string.Format(
"vpc_Version={0}&vpc_Command={1}&vpc_AccessCode={2}&vpc_MerchTxnRef={3}&vpc_Merchant={4}&vpc_User={5}&vpc_Password={6}",
vpc_Version, vpc_Command, vpc_AccessCode, vpc_MerchTxnRef, vpc_Merchant, vpc_User, vpc_Password);
string[] response = SendRequest(vpc_VirtualPaymentClientURL, RequestParams).Split('&');
bool ResponseCode = false;
bool exist = false;
Total = 0;
TransactionDate = DateTime.Now;
TransactionId = CardNo = vpc_Message = string.Empty;
var query = new StringBuilder();
try
{
foreach (string s in response)
{
if (string.IsNullOrWhiteSpace(s))
throw new Exception(string.Format("Message='{0}' ", s));
if (s.IndexOf("vpc_SecureHash") == -1)
{
string vpcMessage = s.Split('=')[1];
query.AppendFormat("{0}-{1}|", s.Split('=')[0], vpcMessage);
if (s.IndexOf("vpc_DRExists") > -1)
{
exist = vpcMessage == "Y";
}
if (s.IndexOf("vpc_TxnResponseCode") > -1)
{
ResponseCode = vpcMessage == "0";
}
if (s.IndexOf("vpc_Amount") > -1)
{
Total =
double.Parse(vpcMessage.Length > 2
? vpcMessage.Insert(vpcMessage.Length - 2, ",")
: "0," + vpcMessage);
}
if (s.IndexOf("vpc_BatchNo") > -1)
{
TransactionDate = DateTime.Parse(vpcMessage.Insert(6, "-").Insert(4, "-"));
}
if (s.IndexOf("vpc_TransactionNo") > -1)
{
TransactionId = vpcMessage;
}
if (s.IndexOf("vpc_CardNum") > -1)
{
CardNo = vpcMessage;
}
if (s.IndexOf("vpc_Message") > -1)
{
vpc_Message = vpcMessage;
}
}
serviceLog.InfoFormat("Message: " + s);
}
}
catch (Exception ex)
{
serviceLog.Error("fatal error", ex);
}
return exist && ResponseCode;
}
</code></pre>
<p>I'm not sure if I can get rid of these multiple if statements.</p>
<p>The "exist" and "ResponseCode" are boolean values and I need them to return bool type from method. Other values are class properties.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:19:20.987",
"Id": "81284",
"Score": "0",
"body": "Why not convert to a switch statement? The data appears to be a single key-value pair."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:22:31.613",
"Id": "81286",
"Score": "1",
"body": "Why are you using `IndexOf()`? Shouldn't you just check `s.Split('=')[0]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:23:33.257",
"Id": "81288",
"Score": "0",
"body": "Also, how much more is left in the whole function... can you post the whole method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:28:34.057",
"Id": "81289",
"Score": "0",
"body": "I've edited the original code and whole method is available now."
}
] | [
{
"body": "<p>You could convert the if statements to a switch. The value being checked is the same in each if and would only be true in one instance. This should make the code easier to read.</p>\n\n<p>Also, the query variable is being assigned, but not being used anywhere in the function so this can be removed.</p>\n\n<pre><code>foreach (string s in response)\n{\n if (string.IsNullOrWhiteSpace(s))\n throw new Exception(string.Format(\"Message='{0}' \", s));\n\n if (s.IndexOf(\"vpc_SecureHash\") == -1)\n {\n string vpcMessage = s.Split('=')[1];\n\n switch (s.Split('=')[0])\n {\n case \"vpc_DRExists\":\n exist = vpcMessage == \"Y\";\n break;\n\n case \"vpc_TxnResponseCode\":\n ResponseCode = vpcMessage == \"0\";\n break;\n\n case \"vpc_Amount\":\n Total = double.Parse(vpcMessage.Length > 2\n ? vpcMessage.Insert(vpcMessage.Length - 2, \",\")\n : \"0,\" + vpcMessage);\n break;\n\n case \"vpc_BatchNo\":\n TransactionDate = DateTime.Parse(vpcMessage.Insert(6, \"-\").Insert(4, \"-\"));\n break;\n\n case \"vpc_TransactionNo\":\n TransactionId = vpcMessage;\n break;\n\n case \"vpc_CardNum\":\n CardNo = vpcMessage;\n break;\n\n case \"vpc_Message\":\n vpc_Message = vpcMessage;\n break;\n }\n }\n\n serviceLog.InfoFormat(\"Message: \" + s);\n}\n</code></pre>\n\n<p>As a further consideration the various cases can be converted to <code>const</code> values.</p>\n\n<p>// Update</p>\n\n<p>outside the function - in class level</p>\n\n<pre><code>private const string RESPONSE_SECURE_HASH = \"vpc_SecureHash\"; // Name should be descriptive\nprivate const string RESPONSE_DRExists = \"vpc_DRExists\";\n</code></pre>\n\n<p>and so on...</p>\n\n<p>Then update the switch statement to be </p>\n\n<pre><code>case RESPONSE_DRExists :\n</code></pre>\n\n<p>see:\n<a href=\"https://stackoverflow.com/questions/9501893/using-a-lot-of-hardcoded-strings-in-code\">https://stackoverflow.com/questions/9501893/using-a-lot-of-hardcoded-strings-in-code</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T11:42:50.047",
"Id": "81295",
"Score": "0",
"body": "Why should various cases be converted to const values?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:24:53.803",
"Id": "81302",
"Score": "2",
"body": "@tesicg It is a point for consideration, as the name of the constant is more descriptive then the string values. If this value is to be used at multiple locations, then it is easier to refractor the code at a later point. I have updated the answer to include a sample."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:54:31.673",
"Id": "46536",
"ParentId": "46530",
"Score": "5"
}
},
{
"body": "<p>This isn't related to your question, but you are not using exceptions properly.</p>\n\n<pre><code>try\n{\n foreach (string s in response)\n {\n if (string.IsNullOrWhiteSpace(s))\n throw new Exception(string.Format(\"Message='{0}' \", s));\n\n //...\n }\n}\ncatch (Exception ex)\n{\n serviceLog.Error(\"fatal error\", ex);\n}\n</code></pre>\n\n<p>You are using the exception as a way to break out of the for loop. This is exactly what the <code>break</code> statement is for. Instead, you create a new <code>Exception</code>, which must populate the stack trace, and then the code starts to unwind the stack looking for the closest matching <code>catch</code>. This is an expensive process for something that is very basic. This could be replaced with:</p>\n\n<pre><code>foreach (string s in response)\n{\n if (string.IsNullOrWhiteSpace(s))\n {\n serviceLog.Error(\"fatal error\", string.Format(\"Message='{0}' \", s));\n break;\n }\n\n //...\n}\n</code></pre>\n\n<p>In addition, you are throwing the base class <code>Exception</code>. This means that the most specific <code>catch</code> you can write is for the base class. This will catch all exceptions, including things like <code>StackOverflowException</code> and <code>OutOfMemoryException</code>. Your code will then try to continue on with no knowledge that these much more serious exceptions were swallowed up into a log message.</p>\n\n<p>When you throw an exception in your code, it should be a sub-class of <code>Exception</code> that is as specific as you can be. This may be a predefined exception of an exception class you explicitly declare. By doing this, you can use the type system to handle different types of exceptions differently and not catch the exceptions you don't mean to handle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:08:22.857",
"Id": "81387",
"Score": "2",
"body": "also, he is misusing the phrase \"fatal error\". A fatal error occurs when the entire program fails, but his catch block exists only in the `CheckPay()` function. It would be more accurate to print something along the lines of \"`error in CheckPay()\"`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:04:02.190",
"Id": "46553",
"ParentId": "46530",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>Instead of using <code>IndexOf</code> and comparing the returned value to something, simply use the <code>Contains</code> method on string objects. </p>\n\n<pre><code>if (!s.Contains(\"vpc_SecureHash\")) { }\n\nif (s.Contains(\"vpc_DRExists\")) { }\n</code></pre></li>\n<li><p>Your If-chain should be an if-else chain, because if one of those is true, then there is no reason to check the next condition. This behavior is easily emulated also in a switch statement</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:57:40.750",
"Id": "46561",
"ParentId": "46530",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46536",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T08:00:17.317",
"Id": "46530",
"Score": "7",
"Tags": [
"c#"
],
"Title": "How to refactor multiple if statements?"
} | 46530 |
<p>Given a large bounding rectangle ("envelope"), a list of points, and a maximal aspect ratio, the goal is to find a rectangle within the envelope, whose aspect ratio is bounded within the given aspect ratio, that contains a largest number of points from the list.</p>
<p>For example: if the envelope is the rectangle with corners (0,0) and (80,200), and the points are {(0,0),(0,60),(0,100),(0,140),(0,200)}, and the maximum aspect ratio is 1, then a possible solution is the square: with corners (0,60) and (80,140), that contains 3 of the points in the list.</p>
<p>My algorithm is relies on the following observation: suppose the envelope is taller than it is long (i.e. its y span is larger than its x span, as in the example). Then an optimal square can always contain the entire x span; the only thing to determine is the optimal y span. So, I just loop over all unique y values of the points, and look for the minimal y value that gives a square with the largest number of points.</p>
<p>If the envelope is longer than it is tall (i.e. its y span is larger than its x span, as in the example), then the exact same algorithm should work, only this time we should loop over the y values.</p>
<p>And here is my problem: the implementation (shown below) contains two exact duplicates of the same algorirthm, with the only difference being that x in one version becomes y in the other version and vice versa.</p>
<p>My question is: is there a way to prevent this duplication?</p>
<pre><code>var _ = require("underscore");
/**
* @param points array of points, e.g. [{x:0,y:0}, {x:100,y:100}, etc.]
* @param envelope defines the bounding rectangle, e.g. {minx: 0, maxx: 100, miny: 0, maxy: 200}
* @param maxAspectRatio number>=1: the maximum width/height ratio of the returned rectangle.
* @return a rectangle contained within the envelope, with aspect ratio at most maxAspectRatio, that contains a largest number of points.
*/
var squareWithMaxNumOfPoints = function(points, envelope, maxAspectRatio) {
if (!maxAspectRatio) maxAspectRatio=1;
var width = envelope.maxx-envelope.minx;
var height = envelope.maxy-envelope.miny;
var largestWidthPerHeight = maxAspectRatio*height;
var largestHeightPerWidth = maxAspectRatio*width;
var result = {};
if (width<=largestWidthPerHeight && height<=largestHeightPerWidth) {
// the envelope has aspect ratio at most maxAspectRatio, so just return it entirely:
result = envelope;
} else if (width>largestWidthPerHeight) {
var miny = result.miny = envelope.miny;
var maxy = result.maxy = envelope.maxy;
var xValues = _.chain(points)
.pluck("x") // get the x values
.sort(function(a,b) { return a-b; }) // sort them in increasing order
.uniq(/*sorted=*/true) // keep each value only once
.filter(function(x) { return envelope.minx<=x && x<=envelope.maxx}) // keep only values in the envelope
.value();
if (xValues.length==0) { // no x values in the envelope - just return any rectangle within the envelope
result.minx = envelope.minx;
result.maxx = result.minx+largestWidthPerHeight;
} else {
var maxNum = 0;
for (var i=0; i<xValues.length; ++i) {
var minx = xValues[i];
var maxx = Math.min(minx+largestWidthPerHeight, envelope.maxx);
var curNum = numPointsWithinXY(points, minx,miny,maxx,maxy);
if (curNum>maxNum) {
maxNum = curNum;
result.minx = minx;
result.maxx = maxx;
}
}
}
} else { // height>largestHeightPerWidth
var minx = result.minx = envelope.minx;
var maxx = result.maxx = envelope.maxx;
var yValues = _.chain(points)
.pluck("y") // get the x values
.sort(function(a,b) { return a-b; }) // sort them in increasing order
.uniq(/*sorted=*/true) // keep each value only once
.filter(function(y) { return envelope.miny<=y && y<=envelope.maxy}) // keep only values in the envelope
.value();
if (yValues.length==0) { // no y values in the envelope - just return any rectangle within the envelope
result.miny = envelope.miny;
result.maxy = result.miny+largestHeightPerWidth;
} else {
var maxNum = 0;
for (var i=0; i<yValues.length; ++i) {
var miny = yValues[i];
var maxy = Math.min(miny+largestHeightPerWidth, envelope.maxy);
var curNum = numPointsWithinXY(points, minx,miny,maxx,maxy);
if (curNum>maxNum) {
maxNum = curNum;
result.miny = miny;
result.maxy = maxy;
}
}
}
}
return result;
}
var numPointsWithinXY = function(points, minx,miny,maxx,maxy) {
return points.reduce(function(prev,cur) {
return prev + (minx<=cur.x && cur.x<=maxx && miny<=cur.y && cur.y<=maxy);
}, 0);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:39:17.573",
"Id": "81291",
"Score": "1",
"body": "Given envelope `(0,0) (80,200)` aspect ratio 1:1 points `(1,200) (2, 200) (3, 200) (4, 200)` this algorithm would find `result.miny = 200` and `result.maxy = 200 + 80 = 280` which is outside the envelope. You have a `var maxy = Math.min(miny+largestHeightPerWidth, envelope.maxy);` but you ignore it when returning the `result`. You should have `result.maxy = maxy;` below `result.miny = miny;`, no? (vice versa for symmetric case, of course)"
}
] | [
{
"body": "<p>The obvious solution is move the max-point-coverage logic into a function, and then call it with an array of just the x or y values, the min/max boundaries, and the \"span\" (i.e. largest width/height allowed).</p>\n\n<p>In other words, start by checking if the square can perfectly cover the envelope, like you do now, and if it can, you're done. If not, start by filtering the points to remove those that fall outside the envelope in either dimension before proceeding. Right now, you're only discarding point based on <em>either</em> its x or y coordinate, which means you might end up finding points you shouldn't.</p>\n\n<p>For instance, if the envelope is <code>(0, 0) (200, 100)</code>, and there's a single point <code>(100, 300)</code>, you'd find it because it's x coordinate is well within 0-200, and that's the only thing you filter. But its y coordinate is way off.</p>\n\n<p>So, given a list of points contained in the envelope, you can focus on either x or y coordinates, as needed. That means starting by plucking the x or y properties from the (already filtered) points array, and passing it on to the aforementioned function.</p>\n\n<p><em>Update 1:</em> You can't use <code>uniq</code> on the 1D values, as it'll make points that lie on the same line count as just 1 point. Hence, you're not guaranteed to actually find the square containing the most points, since it'd favor 5 scattered points over 10 points that lie in a line.<br>\nAlso, added <a href=\"http://jsfiddle.net/9eyvX/1/\" rel=\"nofollow\">a quick demo</a>.</p>\n\n<p><em>Update 2:</em> Fixed a bug in my code that would cause the <code>while</code> loop to \"give up\" immediately in some situations. I've update the code, and the demo link above</p>\n\n<p>I'd suggest something like this:</p>\n\n<pre><code>function findBounds(values, minValue, maxValue, span) {\n var offset = minValue,\n maxCount = 0,\n lowerBoundary,\n upperBoundary,\n prevValue,\n i, l;\n\n values = values.slice(0).sort(function (a, b) { return a -b; });\n\n // optimization: If there aren't enough points left to\n // beat the maxCount we don't have to bother looking.\n while(values.length > maxCount) {\n lowerBoundary = values.shift();\n\n if(lowerBoundary === prevValue) {\n continue; // skip if value is the same as the previous one\n }\n prevValue = lowerBoundary;\n\n upperBoundary = Math.min(lowerBoundary + span, maxValue);\n\n // similar optimization; stop once we exceed\n // the upperBoundary value, and see how far we got\n for( i = 0, l = values.length ; i < l ; i++ ) {\n if( values[i] > upperBoundary ) {\n break;\n }\n }\n\n if( 1 + i > maxCount ) { // add 1 because we shifted the array\n offset = Math.min(lowerBoundary, maxValue - span);\n maxCount = 1 + i;\n }\n\n if(lowerBoundary + span > maxValue) {\n break; // no need to keep looking if we'd exceed the bounding box\n }\n }\n\n return {\n min: offset,\n max: offset + span,\n count: maxCount\n };\n}\n</code></pre>\n\n<p>Which can use like so (for x, as an example):</p>\n\n<pre><code>var values = points.pluck(\"x\");\n bounds = findBounds(values, envelope.minx, envelope.maxx, largestWidthPerHeight),\n result = {\n minx: bounds.min,\n maxx: bounds.max,\n miny: envelope.miny,\n maxy: envelope.maxy\n };\n</code></pre>\n\n<p>And \"vice-versa\" for y.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:00:01.793",
"Id": "46543",
"ParentId": "46531",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46543",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T08:27:56.563",
"Id": "46531",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"node.js"
],
"Title": "Reducing code duplication in a geometric function"
} | 46531 |
<p>I am getting <code>List ids</code> and by using those <code>ids</code> I am creating a <code>Map</code> by fetching related data of id from database, here I am checking <code>prevId</code> with <code>currId</code> if these are not equal then I am putting them into <code>oCMap</code>.</p>
<p>Can this code be optimized? Or are there any improvements (like is there any better algorithm)? Please offer suggestions.</p>
<pre><code> public void populateMap(List<Number> ids)
{
Object oName, cName, startDate, endDate;
String header = "<html><table>";
String footer = "</table></html>";
String rowStart = "<tr>";
String rowEnd = "</tr>";
String columnStart = "<td>&nbsp;";
String columnEnd = "</td>";
SimpleDateFormat displayDateFormat = new SimpleDateFormat ("dd/MM/yyyy");
String convertedDateString;
Number prevId = null;
Number currId = null;
StringBuilder sBuild = new StringBuilder();
StringBuilder sbLoop = new StringBuilder();
for(int j = 0; j < ids.length; j++)
{
Row row = getRow(ids[j]);
currId = (Number)row.getAttribute("OwnerId");
oName = row.getAttribute("oName");
cName = row.getAttribute("ContracttypeName");
startDate = row.getAttribute("StartDate");
endDate = row.getAttribute("EndDate");
if(prevId != null && !currId.equals(prevId))
{
if(sbLoop.length() > 0)
{
sBuild.append(header);
sBuild.append(sbLoop);
sBuild.append(footer);
}
_oCMap.put(prevId, sBuild); //HashMap declared at class level
sBuild = new StringBuilder();
sbLoop = new StringBuilder();
}
sbLoop.append(rowStart);
if(oName != null)
{
sbLoop.append(columnStart + oName + columnEnd);
}
else
{
sbLoop.append(columnStart + columnEnd);
}
sbLoop.append(columnStart + cName + columnEnd);
if(startDate != null)
{
convertedDateString = displayDateFormat.format(((Date)startDate).dateValue());
sbLoop.append(columnStart + convertedDateString + columnEnd);
}
else
{
sbLoop.append(columnStart + columnEnd);
}
if(startDate != null && endDate != null)
{
sbLoop.append(columnStart + " t/m" + columnEnd);
}
else
{
sbLoop.append(columnStart + columnEnd);
}
if(endDate != null)
{
convertedDateString = displayDateFormat.format(((Date)endDate).dateValue());
sbLoop.append(columnStart + convertedDateString + columnEnd);
}
else
{
sbLoop.append(columnStart + columnEnd);
}
sbLoop.append(rowEnd);
prevId = currId;
if(j == ownerContract.length - 1) //code for putting into map for last id.
{
if(sbLoop.length() > 0)
{
sBuild.append(header);
sBuild.append(sbLoop);
sBuild.append(footer);
}
_oCMap.put(prevId, sBuild); //HashMap declared at class level
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:10:04.293",
"Id": "81664",
"Score": "0",
"body": "shall I move all the constant local variable to class level and declare them as static or its ok if I keep it there only... which one is the better way?"
}
] | [
{
"body": "<p><strong>Indentation</strong><br>\nJava's indentation convention is 4 spaces, and not 2 as in your code. You may choose the align <code>=</code> signs between grouped lines, but if you do - be consistent - in your assignment block there are 3 different indentations...</p>\n\n<p><strong>Variables, constants and literals</strong><br>\nVariables, which are dynamic and may change as the method progresses, should be named in camelCase, and should be declared as close to their use as possible (no need to declare them at the beginning of the method).<br>\nConstants, which do not change when the code is run, should be declared as constants <em>outside</em> the method, and be named in ALL_CAPS.<br>\nPersonally I think that you should consider dropping the constants altogether, and use <em>literals</em>, since they are less ambiguous then using constants in this case:</p>\n\n<pre><code>sBuild.append(\"<html><table>\");\nsBuild.append(sbLoop);\nsBuild.append(\"</table></html>\");\n</code></pre>\n\n<p>reads better than:</p>\n\n<pre><code>sBuild.append(HEADER);\nsBuild.append(sbLoop);\nsBuild.append(FOOTER);\n</code></pre>\n\n<p>which reads better than:</p>\n\n<pre><code>sBuild.append(header);\nsBuild.append(sbLoop);\nsBuild.append(footer);\n</code></pre>\n\n<p><strong>Make operations close to where they are used</strong><br>\nSame as variable declaration, it is better to calculate a variable value close to where it is used:</p>\n\n<pre><code>Object oName = row.getAttribute(\"oName\");\nif(oName != null)\n{\n sbLoop.append(columnStart + oName + columnEnd);\n}\nelse\n{\n sbLoop.append(columnStart + columnEnd);\n}\n</code></pre>\n\n<p><strong>Naming</strong><br>\nYou should give variable names which convey information about their purpose and usage. <code>oName</code> and <code>cName</code> are borderline, if they are part of the domain's nomenclature, but <code>sBuild</code> and <code>sbLoop</code> can definitely be improved.</p>\n\n<p><strong>Proper usage of <code>StringBuilder</code></strong><br>\nSo, you've decided to use <code>StringBuilder</code> to optimize string concatenations. That's good, but then you use <code>+</code> to concatenate strings <em>before</em> you append them to your <code>StringBuilder</code>! <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#append%28java.lang.String%29\"><code>#append</code></a> method returns <code>this</code> exactly so you can avoid this:</p>\n\n<pre><code>sbLoop.append(columnStart).append(oName).append(columnEnd);\n</code></pre>\n\n<p>You use <code>sBuild</code> only to wrap your <code>sbLoop</code> with a <code>header</code> and a <code>footer</code>, I suggest you consider simply prepend <code>sbLoop</code> with the prefix, and append it the suffix without using a temp object:</p>\n\n<pre><code>if(prevId != null && !currId.equals(prevId))\n{\n if(sbLoop.length() > 0)\n {\n sbLoop.insert(0, header);\n sbLoop.append(footer);\n } \n _oCMap.put(prevId, sbLoop); //HashMap declared at class level\n\n sbLoop = new StringBuilder();\n}\n</code></pre>\n\n<p>I also think that you should consider <em>not</em> save the <code>StringBuilder</code> in your map, but rather a <code>toString()</code> of it.</p>\n\n<p><strong>Less boilerplate</strong><br>\nYour code has a repeating pattern which is something like this:</p>\n\n<pre><code>if(something != null)\n{\n sbLoop.append(columnStart + something + columnEnd);\n}\nelse\n{\n sbLoop.append(columnStart + columnEnd);\n}\n</code></pre>\n\n<p>I think a better pattern might be:</p>\n\n<pre><code>sbLoop.append(columnStart);\nif(something != null)\n{\n sbLoop.append(something);\n}\nsbLoop.append(columnEnd);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:09:41.560",
"Id": "81663",
"Score": "0",
"body": "shall I move all the constant local variable to class level and declare them as static or its ok if I keep it there only... which one is the better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T06:24:00.020",
"Id": "81671",
"Score": "0",
"body": "I believe you should inline most of them (simply use literals). Although it is less ubiquitous, you may use local constants intead of class constants, as long as you name them appropriately"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T11:49:08.337",
"Id": "46540",
"ParentId": "46533",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46540",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T09:34:45.720",
"Id": "46533",
"Score": "7",
"Tags": [
"java",
"optimization"
],
"Title": "Creating map from ids"
} | 46533 |
<p>For a school project I have been asked to create a login system for a website. The language I have to use is PHP with no database as of yet (for a later assignment). I'm just wondering if this code has any security flaws.</p>
<p>Here is my current code:</p>
<p><strong>Navigation.php</strong> note that this is to be included in another html document. </p>
<pre><code><link type="text/css" rel="stylesheet" href="style_nav.css">
<ul>
<li><a href="index.php">Index</a></li>
<li><a href="test.php">Test</a></li>
<li><a href="#">not-in-use</a></li>
</ul>
<div class="login" >
<?php
session_start();
$_SESSION['last_phage'] = $_SERVER['PHP_SELF'];
if (empty($_SESSION['user'])) {
echo '
<form action="login.php" method="POST">
Username: <input type="text" name="username">
Password: <input type="password" name="password">&nbsp;&nbsp;
<input type="submit" value="Login">
</form>';
} else {
echo 'Welcome! ' . $_SESSION['user'] . '<form action="login.php" method="POST"><input type="submit" value="logout" name="logout"></form>';
}
?>
</div>
<br />
<br />
<hr />
</code></pre>
<p><strong>Login.php</strong> </p>
<pre><code><?php
session_start();
if (isset($_POST['logout'])) {
session_destroy();
header("Location: index.php");
}
if (isset($_POST['username']) && isset($_POST['password'])) {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == 'kad' && $password == 'lol') { //this is just temporary without a database
$_SESSION['user'] = $username;
header("Location:" . $_SESSION['last_phage']);
}
header("Location: " . $_SESSION['last_phage']);
}
}
?>
</code></pre>
| [] | [
{
"body": "<p>Here's my 2 cents as Java \"developer\" with a little experience in c# and vba.</p>\n\n<p>Your security here largely depends on whether you send the password and username in clear text or encrypted. You should force HTTPS protocol for access to the page. </p>\n\n<p>You might also want to show errors if the login is invalid:</p>\n\n<pre><code>$valid = true;\nif(!isset($_POST['username']) || empty($_POST['username'])){\n $errors .= \"Please enter a username.<br>\"\n $valid = false;\n}\nif(!isset($_POST['password']) || empty($_POST['password'])){\n $errors .= \"Please enter a pasword.<br>\"\n $valid = false;\n}\nif($valid){\n //check for username and password compliance\n}\n</code></pre>\n\n<p>Also it would definitely be better to have the logout be handled in a different file than the login</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:12:44.047",
"Id": "81297",
"Score": "0",
"body": "Https sounds like a great idea, thanks for the help! Also i've thought about the showing of error messages, but ill do that for a later assignment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T11:42:56.187",
"Id": "46539",
"ParentId": "46537",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T11:25:50.677",
"Id": "46537",
"Score": "4",
"Tags": [
"php",
"html",
"security",
"form",
"session"
],
"Title": "Security - Login system"
} | 46537 |
<p>I am looking for a review on the following code which is for <a href="http://www.codechef.com/APRIL14/problems/ADIGIT">this question</a>. I am looking for a general review of the code. I am specifically also looking for advice on how to make this code run more efficiently.</p>
<pre><code>#include<iostream>
#include<stdlib.h>
using namespace std;
long int b[100001]={0},x,n,m,i;
char num[100001];
int main()
{
cin>>n>>m;
for(i=1;i<=n;i++)
cin>>num[i];
while(m--)
{
b[100001]={0};
cin>>x;
for(i=1;i<x;i++)
{
b[i]=b[i-1]+abs(num[x]-num[i]);
}
cout<<b[x-1]<<"\n";
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:48:04.983",
"Id": "81308",
"Score": "0",
"body": "Getting something to run in under a second could just be you getting a better computer. It would be better instead to ask for a review, as that is what this site is for, and perhaps you will also get some efficiency tips."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:51:42.483",
"Id": "81309",
"Score": "0",
"body": "i'm quite new to this forum.\nany kind of help would be appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:53:19.570",
"Id": "81310",
"Score": "0",
"body": "Edited. Also I would recommend you fix the spacing and tabbing in your code. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T13:09:19.200",
"Id": "81314",
"Score": "1",
"body": "Start by making the code actually correct. I'm not sure what you think `b[100001]={0};` does, but what it actually does is cause undefined behavior (it's writing past the end of `b`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:01:40.023",
"Id": "81320",
"Score": "3",
"body": "it assigns the value '0' to each cell in the array b[].\nfor example in this code \nhttp://ideone.com/VHoTg1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:05:38.063",
"Id": "81322",
"Score": "0",
"body": "nevermind i did the question myself :|"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:17:56.153",
"Id": "81358",
"Score": "2",
"body": "NO: `long int b[100001]={0};` sets all members to zero. But `b[100001]={0};` access one past the end of the array pretends it a long a sets this single value to zero. So whatever was one past the end of your array is now corrupt. Also its undefined behavior this means your program is broken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:48:26.850",
"Id": "81368",
"Score": "0",
"body": "@LokiAstari: The difference here being that all members are set to zero only on initialization, right? I think I also recall that `long int b[100001] = {};` does the same as well."
}
] | [
{
"body": "<ul>\n<li><p>Try not to get into the habit of using <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a>. It may be okay for small programs, but it can cause problems for larder ones.</p></li>\n<li><p>Use <code><cstdlib></code> instead of <code><stdlib.h></code>; the latter is a C library.</p>\n\n<p>Moreover, you don't need this library at all; <code><cmath></code> is where <code>std::abs()</code> is defined.</p></li>\n<li><p>Even in a small program, do not use global variables:</p>\n\n<pre><code>long int b[100001]={0},x,n,m,i;\nchar num[100001];\n</code></pre>\n\n<p>The problem with this is that these variables can be changed anywhere in the program. If you have a large program, this will be even worse as it won't be easy to determine where a certain variable is being modified. I'd strongly recommend that you don't let this become a habit.</p>\n\n<p>If you're going to keep everything in <code>main()</code> (could be permissible for this small program), then move those variables into the function. If you were to expand this to multiple functions, then pass those variables to the functions from <code>main()</code>.</p></li>\n<li><p>Avoid single-character variable names unless they're simple loop counters. This makes it harder for others to understand your code. It will also make maintenance a lot harder, especially if you decide to grow this program. Use more distinctive names that will also not require comments. </p></li>\n<li><p>Use whitespace between operators for readability. There's no need to cram characters together if you're trying to have shorter lines. Just find ways to use less code on each line.</p>\n\n<p>This, for instance:</p>\n\n<pre><code>b[i]=b[i-1]+abs(num[x]-num[i]);\n</code></pre>\n\n<p>will become</p>\n\n<pre><code>b[i] = b[i-1] + abs(num[x] - num[i]);\n</code></pre></li>\n<li><p>Declaring the loop counter outside the loop statement is from C, not C++. Declare it inside.</p>\n\n<pre><code>for (int i = 0; i < n; i++)\n</code></pre></li>\n<li><p>You don't need the explicit <code>return 0</code> at the end of <code>main()</code>. Reaching this point already implies successful termination, so the compiler will insert it for you.</p></li>\n<li><p>Although it may not make a great difference here, I'd recommend considering <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a> over C-style arrays in general. This is a common C++ storage container and is more usable than static arrays as it's a dynamic container.</p>\n\n<p>Your C-style arrays:</p>\n\n<pre><code>long int b[100001]={0};\n</code></pre>\n\n<p></p>\n\n<pre><code>char num[100001];\n</code></pre>\n\n<p>would look like these respectively:</p>\n\n<pre><code>std::vector<long int> b(100001, 0);\n</code></pre>\n\n<p></p>\n\n<pre><code>std::vector<char> num(100001);\n</code></pre>\n\n<p>This container overloads <code>operator[]</code>, so the syntax for accessing C-style array elements is the same. But you also get iterators, which directly point to the elements and will help prevent accessing the container out of bounds.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:45:36.557",
"Id": "81573",
"Score": "0",
"body": "I am really surprised that you didn't recommend using C++ vectors rather than Arrays in C-style.\nGood answer, well organised!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:37:00.233",
"Id": "81585",
"Score": "0",
"body": "@SAFAD: Very true. :-) I tend to still miss some obvious things. I may add this later. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:34:43.643",
"Id": "46556",
"ParentId": "46547",
"Score": "12"
}
},
{
"body": "<p>The advice from @Jamal's answer is sound regarding general programming issues. This is a supplemental answer specifically addressing performance and design issues. </p>\n\n<h2><code>b</code> doesn't need to be an array</h2>\n\n<p>'b' in your code need only be a single <code>long int</code> rather than an array. Your inner loop then becomes</p>\n\n<pre><code>b += abs(num[x] - num[i]);\n</code></pre>\n\n<h2>make only one loop through <code>num[]</code></h2>\n\n<p>You need only iterate through <code>num[]</code> at most one time. Instead of reading in each <code>x</code> and calculating each in a loop, you could instead read all <code>x</code> values into an array and then calculate all answers in parallel. </p>\n\n<p>It may seem contradictory, but then that means you could make <code>b[]</code> back into an array, but one which need only hold <code>m</code> answers rather than having the dimension <code>n</code>.</p>\n\n<h2>pull loop invariants out of the loop</h2>\n\n<p>The chances are good that your compiler will do this for you, but instead of this:</p>\n\n<pre><code>for(i=1; i<x; i++)\n{\n b[i]=b[i-1]+abs(num[x]-num[i]);\n}\n</code></pre>\n\n<p>You could instead write this:</p>\n\n<pre><code>for(long int i=1, lim=num[x]; i<x; i++)\n{\n b+=abs(lim-num[i]);\n}\n</code></pre>\n\n<p>This assumes that you've also made the change that <code>b</code> is now a single answers.</p>\n\n<h1>generate all answers and then print them</h1>\n\n<p>Instead of emitting each answer within your loop, create them all in an array and then emit them all at once at the end of the program. This makes little difference with small amounts of data, but as your data grows larger, this allows more of the relevant pieces to stay in the cache during calculation. </p>\n\n<p>You might even consider creating the output string in memory and then send it to <code>std::cout</code>, but this only saves very little until the output strings get very large.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:02:18.213",
"Id": "46589",
"ParentId": "46547",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:36:05.830",
"Id": "46547",
"Score": "7",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "Chef and Digits"
} | 46547 |
<p>Is this the best way to do this sort?</p>
<pre><code>assets.OrderBy(a =>
a.GalleryItems != null &&
a.GalleryItems.FirstOrDefault() != null
? a.GalleryItems.OrderBy(gi => gi.SortOrder).First().SortOrder
: 1000)
</code></pre>
<p>Basically I have a group of assets, which contain a group of gallery items with a sort order. I need to get the lowest sort order from this group and sort the assets by that. Gallery items can be null (it is coming through a service so I am unable to change this).</p>
| [] | [
{
"body": "<p>What about something like this:</p>\n\n<pre><code>assets.OrderBy(a => a.GalleryItems != null && \n a.GalleryItems.Any()\n ? a.GalleryItems.Min(gi => gi.SortOrder) \n : 1000)\n</code></pre>\n\n<p>It's actually a bit faster, since sorting the inner list takes longer than just getting the minimum value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:32:24.600",
"Id": "81327",
"Score": "0",
"body": "I like the use of min, think that's what I was after. Looks a lot neater"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:30:25.217",
"Id": "46555",
"ParentId": "46552",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46555",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-07T13:50:47.700",
"Id": "46552",
"Score": "5",
"Tags": [
"c#",
"linq"
],
"Title": "Linq sorting on sort order of inner group"
} | 46552 |
<p>I just began learning programming and I'm learning Objective-C. I'm taking an online course and in that course we were doing a magic crystal ball app. Then I decided to use what I learned and make my own app.</p>
<p><code>Viewcontroller .h</code></p>
<pre><code>#import <UIKit/UIKit.h>
@class MBFQuotes;
@interface MBFViewController : UIViewController
@property (strong, nonatomic) MBFQuotes *quotes;
@property (strong, nonatomic) IBOutlet UILabel *quoteLabel;
@property (strong, nonatomic) IBOutlet UIButton *generalButton;
@property (strong, nonatomic) IBOutlet UIButton *lifeButton;
@property (strong, nonatomic) IBOutlet UIButton *politicsButton;
@property (strong, nonatomic) IBOutlet UIButton *smartButton;
//Action
- (IBAction)generalButton:(id)sender;
- (IBAction)lifeButton:(id)sender;
- (IBAction)politicsButton:(id)sender;
- (IBAction)smartButton:(id)sender;
@end
</code></pre>
<p><code>Viewcontroller .m</code></p>
<pre><code>#import "MBFViewController.h"
#import "MBFQuotes.h"
@interface MBFViewController ()
@end
@implementation MBFViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.quotes = [[MBFQuotes alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)generalButton:(id)sender {
self.quoteLabel.text = [_quotes randomGeneral];
self.quoteLabel.backgroundColor = [UIColor redColor];
}
- (IBAction)lifeButton:(id)sender {
self.quoteLabel.text = [_quotes randomLife];
self.quoteLabel.backgroundColor = [UIColor blueColor];
}
- (IBAction)politicsButton:(id)sender {
self.quoteLabel.text = [_quotes randomPolitics];
self.quoteLabel.backgroundColor = [UIColor blackColor];
}
- (IBAction)smartButton:(id)sender {
self.quoteLabel.text = [_quotes randomSmart];
self.quoteLabel.backgroundColor = [UIColor orangeColor];
}
@end
</code></pre>
<p><code>Class Quotes .h</code></p>
<pre><code>#import <Foundation/Foundation.h>
@interface MBFQuotes : NSObject
-(NSString *)randomGeneral;
-(NSString *) randomLife;
-(NSString *) randomPolitics;
-(NSString *) randomSmart;
@end
</code></pre>
<p><code>Class Quotes.m</code></p>
<pre><code>#import "MBFQuotes.h"
@implementation MBFQuotes
-(NSString *) randomGeneral {
NSArray *generalQuotes = @[@"g1", @"g2", @"g3", @"g4"];
int randomGeneral = arc4random_uniform([generalQuotes count]);
return [generalQuotes objectAtIndex:randomGeneral];
}
-(NSString *) randomLife {
NSArray *lifeQuotes = @[@"l1", @"l2"];
int randomLife = arc4random_uniform([lifeQuotes count]);
return [lifeQuotes objectAtIndex:randomLife];
}
-(NSString *) randomPolitics {
NSArray *politicsQuotes = @[@"p1", @"p2"];
int randomPolitics = arc4random_uniform([politicsQuotes count]);
return [politicsQuotes objectAtIndex:randomPolitics];
}
-(NSString *) randomSmart {
NSArray *smartQuotes = @[@"s1", @"s2"];
int randomSmart = arc4random_uniform([smartQuotes count]);
return [smartQuotes objectAtIndex:randomSmart];
}
@end
</code></pre>
<p>The app works perfectly, but I just want to see if there is better or easier way to do it, or is there there a better design.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:12:10.670",
"Id": "81324",
"Score": "0",
"body": "Regarding your P.S. statement I removed, select all of the code and press CTRL-K."
}
] | [
{
"body": "<h1>ViewController.h</h1>\n<p>First, this name isn't really descriptive at all, is it? We need to know more about this view controller. In fact, standard naming convention is to suffix all view controller subclasses with <code>ViewController</code> anyway, so this is basically an unnamed view controller.</p>\n<p>Now, basically everything declared in your <code>.h</code> should be in the <code>.m</code> file. Of the 6 property declarations, 5 of them are <code>IBOutlet</code> properties, and there's never really an excuse for a view controller to expose its subviews publicly. A view controller should be in complete controller of its view. If an outside class needs to do something that would effect one of these views, create a public method, and let that method internally handle the effects on those views.</p>\n<p>As for the 4 <code>IBAction</code> method declarations, you don't even need to declare these. The only reason to put a method in an <code>@interface</code> section is to expose it to another class. And <code>IBAction</code> methods should never be exposed to another class for the same point as exposing <code>IBOutlets</code> to outside classes. If you need to, create a public method and have that method call the <code>IBAction</code> method internally.</p>\n<p>Finally, the <code>MBFQuotes</code> object. Does this need public visibility? Are you modifying it from outside classes? Looks like probably not, and as such, we can get rid of the class declaration (<code>@class MBFQuotes</code>) and move the <code>@property</code> declaration in the the <code>@interface</code> section of the <code>.m</code>, which comes after the <code>#import</code> of that classes file, and eliminates the need for declaring the class.</p>\n<hr />\n<h1>ViewController.m</h1>\n<p>Seeing as we're not actually doing anything in <code>didReceiveMemoryWarning</code>, we can simply eliminate that entire method from this file. All we're doing is calling the <code>super</code> method, and simply leaving the entire method out handles that. I understand that <code>didReceiveMemoryWarning</code>'s stub is generated automatically by Xcode when you create a new <code>UIViewController</code> subclass, but you should still take it out unless you intend to do something with it (and in most cases, you won't need this method).</p>\n<p>Our four <code>IBAction</code> methods look quite similar, don't they? Why don't we <a href=\"https://codereview.stackexchange.com/a/41762/36366\">combine them into one method</a>.</p>\n<p>First, we need an <code>enum</code> for some readability, so at the top of this file, right after the <code>#import</code> statements, you'll want this code:</p>\n<pre><code>typedef NS_ENUM(NSInteger, QuoteTypes) {\n GeneralQuotes = 100,\n LifeQuotes = 101,\n PoliticalQuotes = 102,\n SmartQuotes = 103\n};\n</code></pre>\n<p>Now, let's use the <code>.tag</code> property of <code>UIButton</code>. You can set this on the storyboard or programmatically. If you set it on the storyboard, set the tag for each button to match the appropriate number in the <code>enum</code> we just created. Programmatically, you can set them as such:</p>\n<pre><code>self.generalButton.tag = GeneralQuotes;\nself.lifeButton.tag = LifeQuotes;\nself.politicalButton.tag = PoliticalQuotes;\nself.smartButton.tag = SmartQuotes;\n</code></pre>\n<p>Now then, get rid of the 4 <code>IBAction</code> methods (be sure to unlink the buttons in storyboard), and create on method to handle all 4 buttons, link all of the buttons to that method. The method should look something like this:</p>\n<pre><code>- (IBAction)quoteButtonPushed:(id)sender {\n switch(sender.tag) {\n case GeneralQuotes:\n self.quoteLabel.text = [self.quotes randomGeneral];\n self.quoteLabel.backgroundColor = [UIColor redColor];\n break;\n case LifeQuotes:\n self.quoteLabel.text = [self.quotes randomLife];\n self.quoteLabel.backgroundColor = [UIColor blueColor];\n break; \n case PoliticalQuotes:\n self.quoteLabel.text = [self.quotes randomPolitical];\n self.quoteLabel.backgroundColor = [UIColor blackColor];\n break;\n case SmartQuotes:\n self.quoteLabel.text = [self.quotes randomSmart];\n self.quoteLabel.backgroundColor = [UIColor orangeColor];\n break;\n default: break;\n }\n}\n</code></pre>\n<p>And please notice that I've used <code>self.quotes</code> here rather than <code>_quotes</code> as you used. If you're declaring a <code>@property</code>, you should be accessing that property through the accessor except in <code>init</code>, <code>dealloc</code>, and the accessor methods, should you choose to write custom accessor methods. If you don't want to access the property through the accessors, then maybe you don't need a property and instead just need a regular instance variable.</p>\n<hr />\n<h1>MBFQuotes.h / MBFQuotes.m</h1>\n<p>As it stands, this is really incomplete as a class, and doesn't really justify being a class at all. It could easily be simply a set of C-style functions. Which way do you want to go? Right now, you're in between.</p>\n<p>If we're happy with the methods as they are and don't want to add anything, then let's change this to some C-style functions:</p>\n<pre><code>// MBFQuotes.h\n\n#import <Foundation/Foundation.h>\n\nNSString * randomGeneral();\nNSString * randomLife();\nNSString * randomPolitical();\nNSString * randomSmart();\n</code></pre>\n<p>Notice the slightly different style and the elimination of <code>@interface</code> and <code>@end</code>. This is no longer a class, but instead a header file with some C-style function declarations.</p>\n<p>EDIT: All right, so you can't actually have <code>const</code> NSArray objects as far as I can tell. The answer has been edited to the next best solution:</p>\n<pre><code>// MBFQuotes.m\n\n#import "MBFQuotes.h"\n\nNSString * randomGeneral() {\n static NSArray *generalQuotes = @[@"g1", @"g2", @"g3", @"g4"];\n int randomGeneral = arc4random_uniform([generalQuotes count]);\n return [generalQuotes objectAtIndex:randomGeneral];\n}\n\nNSString * randomLife() {\n static NSArray *lifeQuotes = @[@"l1", @"l2"];\n int randomLife = arc4random_uniform([lifeQuotes count]);\n return [lifeQuotes objectAtIndex:randomLife];\n}\n\nNSString * randomPolitical() {\n static NSArray *politicsQuotes = @[@"p1", @"p2"];\n int randomPolitical = arc4random_uniform([politicsQuotes count]);\n return [politicsQuotes objectAtIndex:randomPolitical];\n}\n\nNSString * randomSmart() {\n static NSArray *smartQuotes = @[@"s1", @"s2"];\n int randomSmart = arc4random_uniform([smartQuotes count]);\n return [smartQuotes objectAtIndex:randomSmart];\n}\n</code></pre>\n<p>Notice moving the array declaration out of the functions/methods and declaring them as constants. This makes the program a lot more efficient.</p>\n<p>Anyway, if you don't want to go this route, there is certainly room to turn this into a class. For starters, you'd still want to move the arrays out of the methods, but now you'll want them as private properties. For this to be truly classworthy though, you'd want to include methods to be able to add and remove quotes, perhaps give the class a file-path and parse quotes out of a text file.</p>\n<p>Realistically, since this is a class and we're instantiating it, we shouldn't have different categories of quotes. Realistically, we should instantiate a different object of this class for each quote category.</p>\n<p>UNLESS... we were to add a method to pick a random quote from ALL categories (single method, random category, random quote).</p>\n<hr />\n<p>Finally, I think for the project to be really complete, instead of the <code>MBHQuotes</code> class simply holding an array of strings, completeness would say there should be a Quote class, which consists of a few properties. The main property is the quote itself. The other properties give some information about the quote, such as the author, the date of the quote's origin, the category of quote it fits into, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:23:08.043",
"Id": "46598",
"ParentId": "46554",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:06:57.943",
"Id": "46554",
"Score": "4",
"Tags": [
"beginner",
"objective-c",
"ios",
"random"
],
"Title": "Random quote generator"
} | 46554 |
<p>I am trying to remove file extension of a file with many dots in it:</p>
<pre><code>string a = "asdasdasd.asdas.adas.asdasdasdasd.edasdasd";
string b = a.Substring(a.LastIndexOf('.'), a.Length - a.LastIndexOf('.'));
string c = a.Replace(b, "");
Console.WriteLine(c);
</code></pre>
<p>Is there any better way of doing this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:32:42.377",
"Id": "81348",
"Score": "13",
"body": "Googling this exact question title yields [this Stack Overflow answer](http://stackoverflow.com/a/7356223/1188513) as the first search result..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:37:17.607",
"Id": "81352",
"Score": "0",
"body": "are you doing this for practice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:47:51.797",
"Id": "81383",
"Score": "4",
"body": "Please people, for the next time don't answer this question, close it for migratation. This site is codereview, not stackoverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:36:26.677",
"Id": "81399",
"Score": "0",
"body": "Can `a` contain a path?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:36:43.667",
"Id": "81400",
"Score": "0",
"body": "@Manu343726 I don't really like this question, but it does not need to be migrate IMO. We should migrate good question, not borderline question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:38:33.800",
"Id": "81402",
"Score": "0",
"body": "Your code is incorrect. Consider `a = \"a.a.a\"` which should output `\"a.a\"` but actually returns `a`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T05:08:06.923",
"Id": "82392",
"Score": "0",
"body": "In my opinion, this is a poor question for Code Review. However, it's technically on-topic according to our rules. It should stay open, but feel free to upvote/downvote according to your opinion."
}
] | [
{
"body": "<p>If you can, just use <a href=\"http://msdn.microsoft.com/library/system.io.path.getfilenamewithoutextension%28v=vs.110%29.aspx\"><code>Path.GetFileNameWithoutExtension</code></a></p>\n\n<blockquote>\n <p>Returns the file name of the specified path string without the extension.</p>\n</blockquote>\n\n<pre><code>Path.GetFileNameWithoutExtension(\"asdasdasd.asdas.adas.asdasdasdasd.edasdasd\");\n</code></pre>\n\n<p>With one line of code you can get the same result.</p>\n\n<p>If you want to create one by yourself, why not just use this?</p>\n\n<pre><code>int index = a.LastIndexOf('.');\nb = index == -1 ? a : a.Substring(0, index);\n</code></pre>\n\n<p>P.S Special thanks to @Anthony and @CompuChip to point me out some mistake i done, bad day maybe.</p>\n\n<p>You take everything which comes from 0 (the start) to the last dot which means the start of the extension</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:00:25.813",
"Id": "81354",
"Score": "1",
"body": "Just note that `b = a.Substring(0, a.LastIndexOf('.'));` will break on files without an extension because it will end up calling `a.Substring(0, -1)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:01:36.593",
"Id": "81355",
"Score": "0",
"body": "@Anthony Fixed :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:22:53.687",
"Id": "81362",
"Score": "1",
"body": "And saving a call to `Substring` when it is unnecessary:\n\n`b = index == -1 ? a : a.Substring(0, index);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:32:49.340",
"Id": "81364",
"Score": "0",
"body": "Thanks to you too @CompuChip, would be great to give to you an upvote but... :|"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:06:11.977",
"Id": "81386",
"Score": "0",
"body": "No problem, I'm just happy to help. I wouldn't call it a mistake either - your original code did the job as well and to be honest I don't think the difference would be noticeable in practice. Just think this is a bit more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:40:39.407",
"Id": "81403",
"Score": "2",
"body": "It's important to note that `Path.Path.GetFileNameWithoutExtension` removes the path portion of the input. e.g. `Path.Path.GetFileNameWithoutExtension(\"a\\b.c\")` returns `\"b\"` not `\"a\\b\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T04:34:13.247",
"Id": "428485",
"Score": "0",
"body": "Also note that the `Path.GetFileNameWithoutExtension` is slower as it checks for invalid path chars and try to extract the `DirectorySeparatorChar`, `AltDirectorySeparatorChar` or `VolumeSeparatorChar` in a **loop** which seems not necessary for file names (not full path's)!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T07:31:41.287",
"Id": "485558",
"Score": "0",
"body": "I just found an issue where Path.GetFileNameWithoutExtension doesn't work on file names containing the colon (:) character. This character is not permitted in Windows file names, but we've got some integration code using FTP servers that have file names with colons in them. \n\"abc:def.exe\" returns \"def\", instead of \"abc:def\""
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:58:02.073",
"Id": "46562",
"ParentId": "46559",
"Score": "22"
}
},
{
"body": "<p>In your code, you are getting the subsection of the extension, then removing it from the original. Instead you should simply just get the subsection of the string without the extension. </p>\n\n<pre><code>string c = a.Substring(0, a.LastIndexOf('.'));\n</code></pre>\n\n<p><strong>Edit</strong>: Just as stated before me by Marco :D</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:06:20.527",
"Id": "81373",
"Score": "0",
"body": "Downvoted, why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:51:52.993",
"Id": "81474",
"Score": "1",
"body": "What happens if the filename doesn't have any `.extension`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:06:09.033",
"Id": "81491",
"Score": "0",
"body": "@200_success It borks, however the parameter of this question is that this path has multiple dots in it. I simply took shortcuts to improve the posted code. I did not go into depth about error checking."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:00:02.100",
"Id": "46563",
"ParentId": "46559",
"Score": "4"
}
},
{
"body": "<p>Use the Path class within the namespace <code>System.IO</code>.</p>\n\n<pre><code>Path.GetFileNameWithoutExtension(a);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:00:48.853",
"Id": "46564",
"ParentId": "46559",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "46562",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:46:09.427",
"Id": "46559",
"Score": "2",
"Tags": [
"c#"
],
"Title": "How to remove file extension using C#?"
} | 46559 |
<p>I'm planning to make a small game for learning purposes. So far, I've got the hang of the canvas element and using the context to draw things on it, as well as object notation and classes in JavaScript. </p>
<p>But before moving on to making the rest of the game, I'd like you to please take a look at my code and see if there's something I should have done differently. Anything, such as that shouldn't be called or anything as simple as that. Any tips and suggestions are happily accepted!</p>
<p>Here is a link to the jsbin: <a href="http://jsbin.com/hozazeki/1">http://jsbin.com/hozazeki/1</a></p>
<p>If that one throws an error or doesn't work, try this: <a href="http://jsbin.com/hozazeki/1/edit">http://jsbin.com/hozazeki/1/edit</a></p>
<p>P.S: I refer to the red cube as goat. Placeholder graphics, 'ya know?</p>
<pre><code>//Creating requestAnimationFrame to avoid crashing the browser
var requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| fallbackRequestAnimationFrame;
function fallbackRequestAnimationFrame(func) {
setTimeout(func, 0); // Emulate a requestAnimationFrame if none is available
}
//Game object - doesn't have to be a class
game = {
state: "stopped", //initial state of the game
W: 800, //canvas size vars
H: 600,
//Function called by the html page - initializes the game
init: function(){
//get canvas context object
var canvas = document.getElementById("canvas");
this.context = canvas.getContext("2d");
//create goat
this.goat = new Goat();
//start game
this.start(this.context);
},
//Function called to start the game - triggers the game loop
start: function(canvas){
//change the game state
this.state = "running";
//variables used for deltaTime
this.previousTime = new Date().getTime();
//trigger game loop
requestAnimationFrame(this.onFrame);
},
//The game loop basically calls this function over and over
onFrame: function(){
//game loop
if(game.state === "running"){
//calculate deltaTime
var currentTime = new Date().getTime();
var deltaTime = currentTime - game.previousTime;
game.previousTime += deltaTime;
//draw and update
game.draw(deltaTime);
game.update(deltaTime);
//continue looping
requestAnimationFrame(game.onFrame);
}
},
update: function(deltaTime){
//update the goat
this.goat.update(deltaTime);
},
draw: function(deltaTime){
this.clearCanvas(game.context);
//Draw the goat
this.context.fillStyle = "#FF0000";
this.context.fillRect(this.goat.x, this.goat.y, this.goat.w, this.goat.h);
},
clearCanvas: function(canvas){
canvas.beginPath();
canvas.rect(0,0,this.W, this.H);
canvas.fillStyle = "#CCCC99";
canvas.fill();
}
}
function Goat(){
//size
this.w = 50;
this.h = 50;
//position
this.x = 0; // (game.W + this.w) / 2;
this.y = (game.H + this.h) / 2;
//speed - pixels per second
this.vx = 200;
this.vy = 100;
this.update = function(deltaTime){
//if it hit the wall, reverse its velocity
if( this.x >= game.W - this.w || this.x <= 0 ){
this.vx *= -1;
}
if( this.y >= game.H - this.h || this.y <= 0){
this.vy *= -1;
}
this.x += this.vx * (deltaTime / 1000);
this.y += this.vy * (deltaTime / 1000);
}
}
</code></pre>
<p>And the HTML, just because:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Game!</title>
<script src="flappygoat.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600" />
<script>
window.onload = function(){
game.init();
};
</script>
</body>
</html>
</code></pre>
<p>(There is a known non-critical bug: if you hide the tab for a while and then come back, the cube disappears.)</p>
| [] | [
{
"body": "<p>Interesting,</p>\n\n<ul>\n<li><p><a href=\"http://jsperf.com/path-rect-vs-fillrect/7\" rel=\"nofollow\">http://jsperf.com/path-rect-vs-fillrect/7</a> will tell you that <code>fillRect</code> is faster than what you use in <code>clearCanvas</code>.</p></li>\n<li><p><code>window.onload</code> <- consider using addEventListener instead of assigning straight to <code>window.onload</code></p></li>\n<li><p><code>(deltaTime / 1000)</code> <- you should cache this, division is expensive </p></li>\n<li><p><code>game.previousTime += deltaTime;</code> <- Cant you just <code>game.previousTime = currentTime</code> ? An assignment is faster than addition. Also, this would show that perhaps, <code>previousTime</code> is a misnomer ;)</p></li>\n<li><p>in <code>update</code>, you really update the data(model), your function name should reflect that</p></li>\n</ul>\n\n<p>Other than that, I like your style. I would advise you to read up on IIFE's, as they can help you avoid writing <code>this.</code> all the time. Your code is fine now, but at some point <code>this.</code> might get annoying.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:45:56.907",
"Id": "81462",
"Score": "0",
"body": "Thank you very much for your input! About caching the deltaTime division, what do you mean by that, practically? What should I change the update function name to? Again, thank you very, very much!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:00:03.887",
"Id": "81467",
"Score": "0",
"body": "And how should I go about using IIFE's instead of this? I'm sorry, I understand what you mean, but I can't seem to figure out how to practically apply those things to the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:12:15.030",
"Id": "81469",
"Score": "0",
"body": "And as a last comment, I just wanted to ask, what should previousTime be renamed to? I can't seem to think of a better name for it, just something like previousFrameTime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:58:03.980",
"Id": "81476",
"Score": "0",
"body": "I take it back, `previousTime` is fine, since you use it to calculate `deltaTime`. As for IIFE's I will see if I can clone your jsbin project and use an IIFE."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T19:25:20.830",
"Id": "46582",
"ParentId": "46560",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46582",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T14:48:02.400",
"Id": "46560",
"Score": "6",
"Tags": [
"javascript",
"html5",
"canvas"
],
"Title": "Plan to make a small game - got a hang of canvas and made a cube fly around"
} | 46560 |
<p>I've had ideas for something like this in the past but I've finally implemented one and I could definitely use some code review for it. Obviously the quality of the names generated will depend on what the whole thing is seeded with, but that's a separate question. My concerns are the quality and readability of the code, following Objective-C best practices, and possibly how to better structure it to add functionality to it.</p>
<p>I'm creating an NSString, so I did briefly try to subclass NSString before I realized that it was a lot more complicated than I thought, so I'm just using a string property on the object. </p>
<p>Here is the header:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface DTNameCreator : NSObject
//eventually this would take an enum as a type
-(id) initWithType:(int)characterType;
@property NSString *createdName;
@end
</code></pre>
<p>And the implementation:</p>
<pre><code>#import "DTNameCreator.h"
@implementation DTNameCreator {
NSMutableArray *_prefixArray;
NSMutableArray *_middleString1Array;
NSMutableArray *_middleString2Array;
NSMutableArray *_middleString3Array;
NSMutableArray *_suffixStringArray;
NSString *_prefixString;
NSString *_middleString1;
NSString *_middleString2;
NSString *_middleString3;
NSString *_suffixString;
NSMutableArray *_generatorArray;
}
#pragma mark - Initialization
-(id) initWithType:(int)characterType {
self = [super init];
if (self) {
[self seedArraysForType:characterType];
[self createNameGeneratorStringsAndArray];
[self createName];
}
return self;
}
-(void) seedArraysForType:(int)characterType {
switch (characterType) {
case 0:
[self seedArraysForType0];
break;
case 1:
[self seedArraysForType1];
break;
default:
break;
}
}
-(void) seedArraysForType0 {
_prefixArray = [[NSMutableArray alloc]initWithObjects:@"Abu", @"Bra", @"Der", @"Eve", @"Far", @"Gar", @"Her", nil];
_middleString1Array = [[NSMutableArray alloc]initWithObjects:@"ne", @"we", @"re", @"ne", @"be", @"ge", @"te", nil];
_middleString2Array = _middleString1Array;
_middleString3Array = _middleString1Array;
_suffixStringArray = [[NSMutableArray alloc]initWithObjects:@"we", @"re",@"mu", @"ne", @"ge", @"or", @"ar", nil];
}
-(void) seedArraysForType1 {
_prefixArray = [[NSMutableArray alloc]initWithObjects:@"Wen", @"Pre", @"Mar", @"Nem", @"Car", @"Cat", @"Hel", nil];
_middleString1Array = [[NSMutableArray alloc]initWithObjects:@"ne", @"we", @"re", @"ne", @"be", @"ge", @"te", nil];
_middleString2Array = _middleString1Array;
_middleString3Array = _middleString1Array;
_suffixStringArray = [[NSMutableArray alloc]initWithObjects:@"pe", @"ra",@"mul", @"nem", @"ge", @"ara", @"era", nil];
}
-(void) createNameGeneratorStringsAndArray {
int randomNumber1 = arc4random() % _prefixArray.count;
int randomNumber2 = arc4random() % _middleString1Array.count;
int randomNumber3 = arc4random() % _middleString2Array.count;
int randomNumber4 = arc4random() % _middleString3Array.count;
int randomNumber5 = arc4random() % _suffixStringArray.count;
_prefixString = [[NSString alloc]initWithString:[_prefixArray objectAtIndex:randomNumber1]];
_middleString1 = [[NSString alloc]initWithString:[_middleString1Array objectAtIndex:randomNumber2]];
_middleString2 = [[NSString alloc]initWithString:[_middleString2Array objectAtIndex:randomNumber3]];
_middleString3 = [[NSString alloc]initWithString:[_middleString3Array objectAtIndex:randomNumber4]];
_suffixString = [[NSString alloc]initWithString:[_suffixStringArray objectAtIndex:randomNumber5]];
//only add the middle ones because we add the prefix and suffix manually
_generatorArray = [[NSMutableArray alloc]initWithObjects:_middleString1, _middleString2, _middleString3, nil];
}
#pragma mark - Name geneneration
-(void) createName {
NSMutableArray *localGeneratorArray = [[NSMutableArray alloc]init];
NSString *generatorString = [[NSString alloc]init];
//have to add the prefix manually first
[localGeneratorArray addObject:_prefixString];
//check if any of the middle pieces are already present in the name and add if not
BOOL isMiddlePresent = NO;
for (id obj in _generatorArray) {
for (int i = 0; i < localGeneratorArray.count; i++) {
if ([obj isEqualToString:[localGeneratorArray objectAtIndex:i]]) {
isMiddlePresent = YES;
}
}
if (!isMiddlePresent) {
[localGeneratorArray addObject:obj];
}
}
//check if the suffix is present and add it if not
BOOL isSuffixPresent = NO;
for (int i = 0; i < localGeneratorArray.count; i++) {
if ([_suffixString isEqualToString:[localGeneratorArray objectAtIndex:i]]) {
isSuffixPresent = YES;
}
}
if (!isSuffixPresent) {
[localGeneratorArray addObject:_suffixString];
}
//create the name string out of the contents of the array
for (int i = 0; i < localGeneratorArray.count; i++) {
generatorString = [generatorString stringByAppendingString:[localGeneratorArray objectAtIndex:i]];
}
self.createdName = generatorString;
}
@end
</code></pre>
<p>And a sample of the output:</p>
<pre><code>2014-04-07 10:12:33.273 DwarfTowers01[21566:60b] Eveweor
2014-04-07 10:12:33.273 DwarfTowers01[21566:60b] Abuwetegere
2014-04-07 10:12:33.274 DwarfTowers01[21566:60b] Garnear
2014-04-07 10:12:33.274 DwarfTowers01[21566:60b] Fargewene
2014-04-07 10:12:33.275 DwarfTowers01[21566:60b] Derneteor
2014-04-07 10:12:33.275 DwarfTowers01[21566:60b] Evenewe
2014-04-07 10:12:33.276 DwarfTowers01[21566:60b] Farnewegemu
2014-04-07 10:12:33.276 DwarfTowers01[21566:60b] Dernege
2014-04-07 10:12:33.277 DwarfTowers01[21566:60b] Gargemu
2014-04-07 10:12:33.277 DwarfTowers01[21566:60b] Farbewenere
</code></pre>
| [] | [
{
"body": "<p>So, here's a quick lesson on Objective-C <code>@properties</code>.</p>\n\n<p>When you declare a <code>@property</code>, you've created 3 things. An instance variable, a setter, and a getter.</p>\n\n<p>For example, <code>@property NSString *foo;</code> is almost the same as this:</p>\n\n<pre><code>@interface SomeClass : NSObject\n\n- (void)setFoo:(NSString*)foo;\n- (NSString *)foo;\n\n@end\n\n@implementation SomeClass {\n NSString *_foo;\n}\n\n- (void)setFoo:(NSString *)foo {\n _foo = foo;\n}\n\n- (NSString *)foo {\n return _foo;\n}\n\n@end\n</code></pre>\n\n<p>Now, that's just a default <code>@property</code>. The thing is, we can do much more with properties--such as giving them attributes.</p>\n\n<p>In this case, we'll definitely want the <code>readonly</code> attribute.</p>\n\n<pre><code>@property (readonly) NSString *createdName;\n</code></pre>\n\n<p>Now, instead of creating an instance variable and a setter and a getter, we'll only generate an instance variable and a getter.</p>\n\n<p>So, how do we set the instance variable?</p>\n\n<p>Well, we certainly don't want to allow the instance variable to be set externally. That'd be no good and wouldn't make our generated name very random, would it? So, we have two options. We can either simple access the instance variable directly, or we can redeclare the property in the <code>.m</code> as a <code>readwrite</code> property.</p>\n\n<pre><code>@property (readwrite) NSString *createdName;\n</code></pre>\n\n<p>But... you can also completely eliminate the instance variable.</p>\n\n<p>Currently, your class calls <code>createName</code> in the <code>init</code> method and it creates a name. The only publicly exposed aspects of the class are the <code>init</code> and the <code>@property</code>. Once I've grabbed the first name generated, I can't do anything else with the class. The BEST way to use this class as is would be as such:</p>\n\n<pre><code>NSString *name;\n@autoreleasepool {\n name = ([[DTNameCreator alloc] initWithType:0]).createdName;\n}\n</code></pre>\n\n<p>This assures that ARC quickly deallocs the object since it's no good to us once we've extracted the single generated name.</p>\n\n<p>But, there's a better option.</p>\n\n<p>First, let's take the call to <code>createName</code> out of <code>init</code>. We don't need to create a name before someone calls it, and this is especially true if we want generate numerous names from the same instance.</p>\n\n<p>Now, remember what I said? <strong>... you can also completely eliminate the instance variable...</strong></p>\n\n<p>Okay, so let's change our property declaration to <code>readonly</code>:</p>\n\n<pre><code>@property (readonly) createdName; // I think randomName is a little bit better name\n</code></pre>\n\n<p>Now, it's <code>readonly</code>, so we've got no setter method. But we don't need it. \"Setting\" this value is merely a matter of random generation... the work you're doing in <code>createName</code>.</p>\n\n<p>So, change the name of your <code>createName</code> method to <code>createdName</code> and change its return type from <code>void</code> to <code>NSString *</code>. And finally, change the last line of the method.</p>\n\n<p>Eliminate this line:</p>\n\n<pre><code>self.createdName = generatorString;\n</code></pre>\n\n<p>And add this line:</p>\n\n<pre><code>return generatorString;\n</code></pre>\n\n<p>So, what have we done? Because this method name has the same return type and name as one of our <code>@properties</code>, this is now the getter for that property. Because we declared the property as <code>readonly</code>, there's no setter created. And because you've eliminated both the automatically generated setter and getter and haven't used what would be the autosynthesized instance variable backing this property, the instance variable is never created.</p>\n\n<p>So now, </p>\n\n<pre><code>DTNameCreator *nameCreator = [[DTNameCreator alloc] initWithType:0];\n</code></pre>\n\n<p>The object is instantiated but no names are generated.</p>\n\n<pre><code>for(int i=0; i<100; ++i) {\n NSLog(@\"Random name: %@\",nameCreator.createdName);\n}\n</code></pre>\n\n<p>Now you'll generate 100 random names as simple as that without instantiating a new object each time.</p>\n\n<hr>\n\n<p>A couple other notes for completeness.</p>\n\n<ol>\n<li>An <code>enum</code>, as you already mentioned, defining the types of names to generate.</li>\n<li>A factory method: <code>+ (instancetype)nameCreatorWithType:(int)type;</code></li>\n<li>I can't see why your arrays other than the <code>localGeneratorArray</code> in <code>createName</code> would need to be mutable. You should change these to <code>NSArray</code>.</li>\n<li>The default <code>init</code> method.</li>\n</ol>\n\n<p>Four is a big one. It's important that your class still work properly when someone tries to initialize it with the default <code>init</code> it inherits from <code>NSObject</code>.</p>\n\n<p>In some cases, such as a delegated object that must have a delegate, you might choose to simply prevent <code>init</code> from being called:</p>\n\n<pre><code>- (id)init __attribute__((unavailable(\"Cannot instantiate without a delegate\")));\n</code></pre>\n\n<p>But in this case, I don't think that's necessary. We just need to be sure that the initializations take place, so the following should be sufficient:</p>\n\n<pre><code>- (id)init {\n return [self initWithType:0];\n}\n</code></pre>\n\n<p>You don't need to add anything in <code>.h</code>, just add these lines to the <code>.m</code> file.</p>\n\n<hr>\n\n<p><strong>Addendum:</strong> I spent a few minutes looking at <code>createName</code> in more detail and noticed a few issues.</p>\n\n<p>Your <code>forin</code> loops.</p>\n\n<pre><code>for (id obj in _generatorArray)\n//...\nif ([obj isEqualToString:[localGeneratorArray objectAtIndex:i]])\n</code></pre>\n\n<p>You're declaring <code>obj</code> as type <code>id</code> but then treating it as a <code>NSString</code> object in the body of the loop.</p>\n\n<p>Xcode may not complain, but I will. You need to make one of the following changes.</p>\n\n<p>You can change the declaration to <code>NSString *</code>:</p>\n\n<pre><code>for (NSString *obj in _generatorArray)\n</code></pre>\n\n<p>Or, you can change the comparison method:</p>\n\n<pre><code>if ([obj isEqual:blahblahblah])\n</code></pre>\n\n<p>The former is probably better because we all know there's nothing but strings in that array. But the latter is fine too. <code>isEqual:</code> is an <code>NSObject</code> method, so all Objective-C object respond to it. In the case of <code>NSString</code>, it does almost the exact same thing as <code>isEqualToString:</code>. I think internally it first does a type check (after the pointer comparison) to see if the compared objects are of the same type (because if they're not, they're definitely not equal).</p>\n\n<p>The main point here is, if we know everything in the array is a string, we should declare the iterator object as that type of object. If we don't know this, however, then we can't be calling <code>isEqualToString</code> on every object in the array, because only <code>NSString</code> and its subclasses respond to that selector.</p>\n\n<p>Finally, you can make your loops a little more efficient by adding a <code>break;</code> statement after the spots where you set the <code>BOOL</code> variables to <code>YES</code>. There's nothing in the loop that sets it back to <code>NO</code>, so why continue iterating through the loop? Once it's <code>YES</code>, we know the final outcome and can stop checking.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:05:58.797",
"Id": "81937",
"Score": "0",
"body": "This really helped clear a few things up for me. For example, I wasn't sure if it was preferable to use id obj or specify the type when using for loops. I also did not know that you should still have an explicit init when you are planning to initialize with a custom init. Thanks for writing this up."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T23:10:46.660",
"Id": "46600",
"ParentId": "46566",
"Score": "4"
}
},
{
"body": "<p>I'm no Obj-C expert, but it looks like you're working much, much too hard here.</p>\n\n<p>For one, this could easily be a straight-up function; no class needed. Or, you make it a static method. Or - likely overkill - create a singleton <code>DTNameGenerator</code> instance. But certainly less overkill than the current solution.</p>\n\n<p>My point is that there's no need to instantiate an object here. There's no internal state, no real dependencies; only fixed (hard coded) input (the name fragments), and an output.</p>\n\n<p>And I'm not sure what's going on with the underscored variable names everywhere; no need for that here either.</p>\n\n<p>Moreover, things can be improved by simple looping. Say you build your array of name fragments like this (using the <code>@[ ... ]</code> shorthand for creating arrays):</p>\n\n<pre><code>NSArray *prefix = @[@\"Abu\", @\"Bra\", @\"Der\", @\"Eve\", @\"Far\", @\"Gar\", @\"Her\"];\nNSArray *repeated = @[@\"ne\", @\"we\", @\"re\", @\"ne\", @\"be\", @\"ge\", @\"te\"];\nNSArray *suffix = @[@\"we\", @\"re\",@\"mu\", @\"ne\", @\"ge\", @\"or\", @\"ar\"];\nNSArray *fragments = @[ prefix, repeated, repeated, repeated, suffix ];\n</code></pre>\n\n<p>Then you just need to loop through the <code>fragments</code> and pick a fragment from each nested array. To figure out if a particular fragment is already in the name, you can just check whether <code>[nameArray indexOfObject:pick] == NSNotFound</code></p>\n\n<p>Finally, those \"types\" are completely opaque and meaningless - what's \"type 0\" vs. \"type 1\"? I'm guessing it's male/female since we're talking about names. In that case call a spade a spade, and typedef the values you expect, e.g.</p>\n\n<pre><code>typedef enum DTGender {\n kDTGenderFemale,\n kDTGenderMale\n} DTGender;\n</code></pre>\n\n<p>Then you can pass <code>kDTGenderFemale</code> or <code>kDTGenderMale</code> to your function or method, and it's obvious what's going on. Even if it's not specifically genders, you should still make it explicit what those \"types\" are.</p>\n\n<p>In all, I get something like this (a more experienced Obj-C coder will probably scream, but it's still an improvement over the original code):</p>\n\n<p>DTNameGenerator.h</p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\ntypedef enum DTGender {\n kDTGenderFemale,\n kDTGenderMale\n} DTGender;\n\n@interface CRNameGenerator : NSObject\n+ (NSString*)randomNameForGender:(DTGender)gender;\n@end\n</code></pre>\n\n<p>DTNameGenerator.m</p>\n\n<pre><code>#import \"CRNameGenerator.h\"\n\n@implementation CRNameGenerator\n\n+ (NSString*)randomNameForGender:(DTGender)gender {\n NSArray *prefix;\n NSArray *suffix;\n NSArray *middle = @[@\"ne\", @\"we\", @\"re\", @\"ne\", @\"be\", @\"ge\", @\"te\"];\n\n if (gender == kDTGenderMale) {\n prefix = @[@\"Abu\", @\"Bra\", @\"Der\", @\"Eve\", @\"Far\", @\"Gar\", @\"Her\"];\n suffix = @[@\"ne\", @\"re\", @\"mu\", @\"we\", @\"ge\", @\"or\", @\"ar\"];\n } else {\n prefix = @[@\"Wen\", @\"Pre\", @\"Mar\", @\"Nem\", @\"Car\", @\"Cat\", @\"Hel\"];\n suffix = @[@\"pe\", @\"ra\", @\"mul\", @\"nem\", @\"ge\", @\"ara\", @\"era\"];\n }\n\n NSArray *fragments = @[ prefix, middle, middle, middle, suffix ];\n\n NSMutableArray* name = [NSMutableArray array];\n\n for(NSArray *parts in fragments) {\n // get a random index. The docs recommend using\n // arc4random_uniform() rather than the modulo trick\n NSUInteger i = arc4random_uniform((u_int32_t) parts.count);\n NSString* part = (NSString*)[parts objectAtIndex:i];\n if( [name indexOfObject:part] == NSNotFound ) {\n [name addObject:part];\n }\n }\n\n return [name componentsJoinedByString:@\"\"];\n}\n\n@end\n</code></pre>\n\n<p>And you just have to call <code>[DTNameGenerator randomNameForGender:...]</code> to get a random name. Of course, the hard coded name fragments are still pretty iffy; would probably be better to load those from somewhere else or otherwise have a way to define them at runtime.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:28:05.387",
"Id": "81482",
"Score": "0",
"body": "Singletons really shouldn't be recommended outside of where they're legitimately needed. The underscored variable names are completely expected. These are underscored to match the autosynthesized pattern for the instance variables that back `@properties`. The point is, an underscored variable let's you know this is a private, class variable, and is common in Objective-C. It let's an experienced Objective-C coder know exactly what they are even if they missed the declaration of the variables. Anyway, given your suggested implementation, I'd probably go with a C-style function here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:11:07.317",
"Id": "81494",
"Score": "0",
"body": "@nhgrif I've only seen the underscored naming used to distinguish a private variable from the public property it backs (as you mention). In this case, though, I don't see the need - it's all private instance variables as far as I can tell. And the only property - `createdName` - seems completely autosynthed with no private `_createdName` var explicitly backing it. Hence I didn't see the need to underscore _everything_. But if it's convention, then OK"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:17:09.843",
"Id": "81941",
"Score": "0",
"body": "I am a novice so sometimes my approach is more brute force than necessary, and I'm slowly learning ways to clean it up. Your comments are very helpful though. The code that you came up with looks very clean to me so seeing it helps a lot. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T23:48:41.730",
"Id": "46601",
"ParentId": "46566",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46600",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T15:31:36.683",
"Id": "46566",
"Score": "3",
"Tags": [
"game",
"objective-c",
"random"
],
"Title": "Random Name Generator"
} | 46566 |
<p>Here is a class of one of my applications I'm trying to learn writing good code with.
<strong>Old Code:</strong></p>
<pre><code>//-----------------------------------------------------------------------
// <copyright file="Client.cs" company="-">
// Copyright (c) -. All rights reserved.
// </copyright>
// <author>-</author>
//-----------------------------------------------------------------------
namespace LightCS
{
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
/// <summary>
/// Stores information about a single client and provides functions to control the client.
/// </summary>
public partial class Client : IDisposable
{
/// <summary>
/// <c>TcpClient</c> of the connection</summary>
private TcpClient tcpClient;
/// <summary>
/// Stores the <c>streamwriter</c> of the <c>TcpClient</c></summary>
private StreamWriter writer;
/// <summary>
/// Declares if the client is alive or not.</summary>
private bool alive = true;
/// <summary>
/// Unique ID of the client</summary>
private int id;
/// <summary>
/// Initializes a new instance of the Client class. </summary>
/// <param name="tcpClient">The <c>TcpClient</c> of the client connection</param>
/// <param name="id">The unique Id of the client</param>
public Client(TcpClient tcpClient, int id)
{
this.tcpClient = tcpClient;
this.id = id;
this.writer = new StreamWriter(tcpClient.GetStream());
new Thread(() =>
{
this.Listen(new StreamReader(tcpClient.GetStream()));
}).Start();
}
/// <summary>
/// The internal OnClientMessage Handler.</summary>
/// <param name="sender">Client who fired the event</param>
/// <param name="e">InternalClientEventArgs include the received message</param>
public delegate void InternalOnClientMessageHandler(object sender, InternalClientMessageEventArgs e);
/// <summary>
/// The internal OnClientDisconnect Handler.</summary>
/// <param name="sender">Client who fired the event</param>
/// <param name="e">EventArgs of the event</param>
public delegate void InternalOnClientDisconnectHandler(object sender, EventArgs e);
/// <summary>
/// The Internal OnClientMessage Event fires when a new message is received.</summary>
public event InternalOnClientMessageHandler InternalOnClientMessage;
/// <summary>
/// The internal OnClientDisconnect Event fires when the client closes the connection.</summary>
public event InternalOnClientDisconnectHandler InternalOnClientDisconnect;
/// <summary>
/// Sends a message to the client.</summary>
/// <param name="message">Message to send</param>
public void Write(string message)
{
if (this.alive)
{
this.writer.WriteLine(message);
this.writer.Flush();
}
}
/// <summary>
/// Returns the client specific id.</summary>
/// <returns>The client specific id</returns>
public int GetID()
{
return this.id;
}
/// <summary>
/// Closes the client connection and fires Internal OnClientDisconnect event.</summary>
public void Close()
{
this.alive = false;
this.writer.Close();
this.tcpClient.GetStream().Close();
this.tcpClient.Close();
if (this.InternalOnClientDisconnect != null)
{
this.InternalOnClientDisconnect(this, new EventArgs());
}
}
/// <summary>
/// Listens for incoming messages and processes them. Also fires the Internal OnClientMessage event containing the message.</summary>
/// <param name="reader">The <c>Streamreader</c> where should be read</param>
private void Listen(StreamReader reader)
{
while (this.alive)
{
string input = reader.ReadLine();
if (input == "exit")
{
this.Close();
break;
}
if (this.InternalOnClientMessage != null)
{
this.InternalOnClientMessage(this, new InternalClientMessageEventArgs(input));
}
Thread.Sleep(150);
}
}
/// <summary>
/// <c>Dispose()</c></summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose()</summary>
/// <param name="disposing"><c>disposing</c></param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (writer != null)
{
writer.Dispose();
writer = null;
}
}
}
}
}
</code></pre>
<p>I would like to know how good this code is overall, but especially how well the <code>IDisposable</code> interface is implemented because I never did it before and I'm not sure if I understand it 100% correctly. Is there something I miss or I should add? Should I do something different?</p>
<p>I strictly followed the StyleCop rules and used the <strong>Analyse code</strong> function of Visual Studio. </p>
<p><strong>Improved Code:</strong> </p>
<pre><code> //-----------------------------------------------------------------------
// <copyright file="Client.cs" company="-">
// Copyright (c) -. All rights reserved.
// </copyright>
// <author>-</author>
//-----------------------------------------------------------------------
namespace LightCS
{
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
/// <summary>
/// Stores information about a single client and provides functions to control the client.
/// </summary>
public partial class Client : IDisposable
{
/// <summary>
/// <c>TcpClient</c> of the connection</summary>
private TcpClient tcpClient;
/// <summary>
/// Stores the <c>streamwriter</c> of the <c>TcpClient</c></summary>
private StreamWriter writer;
/// <summary>
/// Declares if the client is alive or not.</summary>
private bool alive = true;
/// <summary>
/// Unique ID of the client</summary>
private int id;
/// <summary>
/// Initializes a new instance of the Client class. </summary>
/// <param name="tcpClient">The <c>TcpClient</c> of the client connection</param>
/// <param name="id">The unique Id of the client</param>
public Client(TcpClient tcpClient, int id)
{
this.tcpClient = tcpClient;
this.id = id;
this.writer = new StreamWriter(tcpClient.GetStream());
new Thread(() =>
{
this.Listen(new StreamReader(tcpClient.GetStream()));
}).Start();
}
/// <summary>
/// Sends a message to the client.</summary>
/// <param name="message">Message to send</param>
/// <exception cref="ObjectDisposedException">Throws when object is disposed and is handled by firing the Internal OnClientException event</exception>
/// <exception cref="IOException">Throws when an I/O Error occurs and is handled by firing the Internal OnClientException event</exception>
public void Write(string message)
{
if (this.alive)
{
try
{
this.writer.WriteLine(message);
this.writer.Flush();
}
catch (Exception ex)
{
if (ex is ObjectDisposedException || ex is IOException)
{
this.InternalOnClientException(this, new InternalClientExceptionEventArgs(ex));
}
}
}
}
/// <summary>
/// Listens for incoming messages and processes them. Also fires the Internal OnClientMessage event containing the message.</summary>
/// <param name="reader">The <c>Streamreader</c> where should be read</param>
/// <exception cref="ObjectDisposedException">Throws when object is disposed and is handled by firing the Internal OnClientException event</exception>
/// <exception cref="IOException">Throws when an I/O Error occurs and is handled by firing the Internal OnClientException event</exception>
private void Listen(StreamReader reader)
{
while (this.alive)
{
try
{
string input = reader.ReadLine();
if (input == "exit")
{
this.Close();
break;
}
if (this.InternalOnClientMessage != null)
{
this.InternalOnClientMessage(this, new InternalClientMessageEventArgs(input));
}
Thread.Sleep(150);
}
catch (Exception ex)
{
if (ex is ObjectDisposedException || ex is IOException)
{
this.InternalOnClientException(this, new InternalClientExceptionEventArgs(ex));
}
}
}
}
/// <summary>
/// Returns the client specific id.</summary>
/// <returns>The client specific id</returns>
public int GetID()
{
return this.id;
}
/// <summary>
/// Closes the client connection and fires Internal OnClientDisconnect event.</summary>
public void Close()
{
this.alive = false;
this.writer.Close();
this.tcpClient.GetStream().Close();
this.tcpClient.Close();
if (this.InternalOnClientDisconnect != null)
{
this.InternalOnClientDisconnect(this, new EventArgs());
}
}
/// <summary>
/// <c>Dispose()</c></summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Calls Dispose()</summary>
/// <param name="disposing"><c>disposing</c> argument</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (this.writer != null)
{
this.writer.Dispose();
this.writer = null;
}
}
}
/// <summary>
/// The internal <c>OnClientMessage</c> Handler.</summary>
/// <param name="sender">Client who fired the event</param>
/// <param name="e"><c>InternalClientEventArgs</c> include the received message</param>
public delegate void InternalOnClientMessageHandler(object sender, InternalClientMessageEventArgs e);
/// <summary>
/// The internal <c>Onclientexception</c> Handler.</summary>
/// <param name="sender">Client who fired the event</param>
/// <param name="e">InternalClientEventArgs include the received message</param>
public delegate void InternalOnClientExceptionHandler(object sender, InternalClientExceptionEventArgs e);
/// <summary>
/// The internal <c>OnClientDisconnect</c> Handler.</summary>
/// <param name="sender">Client who fired the event</param>
/// <param name="e">EventArgs of the event</param>
public delegate void InternalOnClientDisconnectHandler(object sender, EventArgs e);
/// <summary>
/// The Internal <c>OnClientMessage</c> Event fires when a new message is received.</summary>
public event InternalOnClientMessageHandler InternalOnClientMessage;
/// <summary>
/// The internal <c>OnClientException</c> Event fires when the client runs into an exception</summary>
public event InternalOnClientExceptionHandler InternalOnClientException;
/// <summary>
/// The internal <c>OnClientDisconnect</c> Event fires when the client closes the connection.</summary>
public event InternalOnClientDisconnectHandler InternalOnClientDisconnect;
}
}
</code></pre>
<p>The rules StlyeCop finds as mistaken:<br>
<img src="https://i.stack.imgur.com/1tRPU.png" alt="rules"><br>
<em>Click <a href="http://puu.sh/7ZK2r.png" rel="nofollow noreferrer">here</a> for bigger image.</em></p>
| [] | [
{
"body": "<p>Looks like very nice code, I only have 2 remarks:</p>\n\n<ul>\n<li><p>You declare a ton of one liners between <code>public Client(TcpClient tcpClient, int id)</code> and <code>public void Write(string message)</code> which harms the reading flow if you want to follow the code. I would suggest to put the oneliners completely at the bottom.</p></li>\n<li><p>You should support the throwing of <code>IOException</code> and <code>ObjectDisposedException</code> when you read (write?) from the connection.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:49:01.063",
"Id": "81384",
"Score": "0",
"body": "Okay so I moved the one liners to the bottom. The declarations should stay on the top, right? After moving the one liners to the bottom StyleCop tells me that the methods should be placed after the delegates and events. Should I care about the \"Rules\" or about own oppinion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:17:54.450",
"Id": "81388",
"Score": "0",
"body": "Hmmm, I am really not a C# expert, so I cannot give you much guidance. I can tell you that I think the new version is more readable. Note that you should not take away the original code, you can have a second code box with the changed code. Otherwise the mods will roll back your changes to the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:21:46.850",
"Id": "81390",
"Score": "0",
"body": "Okay I think I will keep the new code and added the original code. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:20:33.580",
"Id": "46573",
"ParentId": "46572",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>Most of your comments are completely redundant. They only bloat the code without adding any information. For example for <code>bool Client.alive</code> you write:</p>\n\n<blockquote>\n <p>Declares if the client is alive or not.</p>\n</blockquote>\n\n<p>The reader learns nothing from this they can't already see from the the definition. You could instead document what being \"alive\" <em>means</em>. There are several possible definitions with subtle differences, telling the reader which you are using is helpful.</p>\n\n<p>It's the same for most of your other comments.</p></li>\n<li><p>It's confusing to have <em>public</em> members called <code>Internal*</code></p></li>\n<li><p>When you construct a <code>StreamWriter</code> or <code>StreamReader</code> with the default constructor, it owns the underlying stream and closes it when it's closed.</p>\n\n<p>So closing the stream is redundant. You also have two objects (the reader and the writer) which own the stream, which I'd avoid.</p></li>\n<li><p><code>GC.SuppressFinalize(this)</code> is useless if your class has no finalizer. This also means <code>Dispose(bool disposing)</code> doesn't get called with <code>false</code> as parameter and can be thrown out.</p>\n\n<p>In general I'd recommend against using this disposing pattern. If you own unmanaged resources directly, implement a <code>SafeHandle</code>. If you only own them indirectly, there is no need for <code>Dispose(bool)</code> and the finalizer.</p></li>\n<li><p>Don't silently swallow unexpected exceptions. They indicate a bug and should be rethrown or not be caught in the first place.</p></li>\n<li>You call <code>this.InternalOnClientException</code> without ensuring it's not <code>null</code>.</li>\n<li>Use a property for <code>public int GetID()</code> instead of a method.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:06:41.577",
"Id": "81479",
"Score": "0",
"body": "Yes I should extend the comments. I'm programming a library and I'm using the `Internal*` events to fire events that are used inside the library but the end user application. Is there a way I could use them inside the library project but hide them outside the lib? Point 4/5: Does this mean I should remove the `Dispose` part completely? Point 5: I want to handle `IOExceptions` and `ObjectDisposedExceptions` in my server class, so I used events to handle them nicely. Should I rethrow any other exceptions? Point 6/7 are right. Point 3: Should I safe the stream separately and use it instant?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:59:46.577",
"Id": "46580",
"ParentId": "46572",
"Score": "7"
}
},
{
"body": "<p>On top of other remarks, I'm surprised this even works:</p>\n\n<pre><code>namespace LightCS\n{\n using System;\n using System.IO;\n using System.Net.Sockets;\n using System.Threading;\n</code></pre>\n\n<p>Normally the <code>using</code> instructions sit at the very top of the code file, like this:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Net.Sockets;\nusing System.Threading;\n\nnamespace LightCS\n{\n</code></pre>\n\n<p>It's somewhat off-putting to see them within a <code>namespace</code> scope.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T09:56:26.827",
"Id": "81466",
"Score": "3",
"body": "I followed the Stylecop rules. Same topic [here](http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T19:40:45.563",
"Id": "46584",
"ParentId": "46572",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T17:08:31.383",
"Id": "46572",
"Score": "7",
"Tags": [
"c#"
],
"Title": "IDisposable Interface for an Server/Client connection client"
} | 46572 |
<p>I am comparing two integer values, but there is chance of <code>parseInt</code> giving NaN. I would like to know if I need to do any additional checks.</p>
<pre><code>var txtFromCustomerId = document.getElementById(FROMCUSTOMERID_FIELDNAME);
var txtToCustomerId = document.getElementById(TOCUSTOMERID_FIELDNAME);
if (txtFromCustomerId != null && txtToCustomerId != null) {
var fromCustomerId = parseInt(txtFromCustomerId.value);
var toCustomerId = parseInt(txtToCustomerId.value);
if (fromCustomerId > toCustomerId) { <---There is chance of parseInt giving Nan
//some other stuff
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:19:38.997",
"Id": "81389",
"Score": "1",
"body": "If this data comes from the user typing it in, it seems to me that you ought to check the data the user typed in before you get to this function and not even call this if the values aren't what you are expecting (inform the user that the data is not correct). So, in answer to your question, you should already know that they are valid numbers before you get here and thus shouldn't have to test for NaN here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:23:27.300",
"Id": "81391",
"Score": "0",
"body": "Actually, I am having these as independent functions that are called by ASP.NET custom validators. So, would it be nice to check for integer types in fromCustomerId and toCustomerId before comparing them."
}
] | [
{
"body": "<ul>\n<li>A blank string <strong>is not</strong> equal to <code>null</code>, therefore it can get through. </li>\n<li><code>parseInt('')</code> returns a <code>NaN</code>.</li>\n<li>Always use <code>parseInt()</code> with the radix (the second parameter). In some implementations, it doesn't default to base 10 (decimal).</li>\n<li>As much as possible, use string comparison (<code>===</code>, <code>!==</code>, etc). It's best practice.</li>\n</ul>\n\n<hr>\n\n<p>Instead, check for a blank string. Then instead of <code>parseInt</code>, you can do a <code>+</code>.</p>\n\n<pre><code>var text = *get value*\nif(text !== ''){\n var number = +text;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:23:52.907",
"Id": "46575",
"ParentId": "46574",
"Score": "2"
}
},
{
"body": "<p>An opinion question,</p>\n\n<p>ideally you should not compare with <code>NaN</code>, it always gives <code>false</code>.</p>\n\n<p>If that is okay for the code within the comparison, then go ahead, otherwise make sure you are dealing with a proper customer id.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:32:36.770",
"Id": "81393",
"Score": "0",
"body": "Yes, it is giving false for the NaN comparisions as per the expectations. But I would like to know if it is ethical to do this way, by knowing that we shouldn't compare if it is not valid values. Does it give wrong outlook overall."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:33:52.717",
"Id": "81395",
"Score": "0",
"body": "Question again is, what is inside the `if` block, does it matter ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:36:01.307",
"Id": "81397",
"Score": "0",
"body": "It returns false if the check fails. And if it is NaN, it does nothing which is fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:47:35.840",
"Id": "81405",
"Score": "0",
"body": "Then, I would not worry, and put a comment `//Dont worry about NaN`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:28:20.120",
"Id": "46577",
"ParentId": "46574",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46577",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:14:13.070",
"Id": "46574",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Is it ok to have NaN while comparing fields in JavaScript?"
} | 46574 |
<p>This is my first Laravel package. It uses hybrid Auth package to authenticate users using their social network accounts. It can retrieve information to store in a local database.</p>
<p>Its purpose is to be able to link several social networks accounts into one single user. That way, if you login with Facebook or Twitter, you will have the same account.</p>
<p><a href="https://github.com/caalaniz1/LorisLogin" rel="nofollow">Package GIT</a></p>
<p><a href="https://github.com/caalaniz1/LorisLogin/blob/master/src/controllers/LorisLoginController.php" rel="nofollow">Main Controller</a></p>
<pre><code><?php
class LorisLogin extends BaseController {
private $success_messages = array(
'newSProfile' => 'NewProfile added successfully',
);
private $error_messages = array(
'notFound' => 'Aparently the social network profile that you tried to
access with is not in our database, please login using your local
account or previosly synced social profile.',
'incorrectCred' => 'Incorrect username or password please try again',
'Found' => 'Try to click on a social network button to login or signup',
'registered' => 'This social Profile is already linked with your account',
'registeredToOther' => 'This social Profile is already associated with an other',
);
/**
* This function must be exclusively used when creating a local account
* using a social profile, it will generate and return an unused
* username for a user.
*
* @param string $username
* @return string $username
*/
private static function nameUser($username) {
$num = 00;
$dup = NULL;
//is username cannot be saved the username is taked by other user
while (!User::where('username', '=', $username)->get()->isEmpty()) {
//TRy to take the last duplicate of the number
$dup = User::where('username', 'LIKE', $username . '-sL__')
->orderBy('username', 'desc')
->first();
//if theres a hit the the number and increase it
if ($dup != NULL) {
$num = (int) substr($dup->username, -2);
$num++;
}
//try a new username
$username = $username . '-sL' . sprintf('%02d', $num);
}
return $username;
}
/**
* Tries to connect to a social network provider is success return
* the profile else trow expection
*
* @param string $network
* Network to connect to ex. 'facebook', 'twitter'
* @return HybridAuth profile object
*/
public static function loginSocial($network = NULL) {
//config file
$_config = include app_path() . '/config/hybridauth.php';
//Get current Route
$route_name = Route::currentRouteName();
$action = Input::get('action');
// check URL segment
if ($action == "auth") {
// process authentication
try {
Hybrid_Endpoint::process();
} catch (Exception $e) {
// redirect back to http://URL/social/
return Redirect::route($route_name);
}
return;
}
try {
$network = Input::get('network');
// create a HybridAuth object
$_config['base_url'] = route($route_name) . '?action=auth';
$socialAuth = new Hybrid_Auth($_config);
// authenticate with Google
$provider = $socialAuth->authenticate($network);
// fetch user profile
$userProfile = $provider->getUserProfile();
} catch (Exception $e) {
// exception codes can be found on HybBridAuth's web site
return $e->getMessage();
}
$provider->logout();
return $userProfile;
}
/**
* Try to log in using a social profile, if is not found on the DB
* It redirects to Sigup
*
* @array Mixed
*
*/
public function loginWithSocial() {
try {
$userProfile = $this->loginSocial();
$profile = SocialProfile::find($userProfile->identifier);
if ($profile != NULL) {
$user = $profile->user()->getResults();
Auth::login($user);
return Redirect::route('admin-user-landing');
} else {
echo $this->error_messages['notFound'];
return Redirect::route('signup')
->with('message', $this->error_messages['notFound']
);
}
} catch (Exception $e) {
return $e->getMessage();
}
}
/**
* Try to Authenticate a user using local credentials
*
* @return Redirect
*/
public function loginWithLocal() {
$username = Input::get('username');
$password = Input::get('password');
if (Auth::attempt(array('username' => $username, 'password' => $password))) {
return Redirect::route('admin-users-landing');
}
return Redirect::route('login')
->with('message', $this->error_messages['incorrectCred']);
}
/**
* Check if Social Profile Exists in DB if not it will create a new local
* account and a new Social Profile and Link them togueter.
*
* @return Redirect or Exeption
*/
public function signupWithSocial() {
try {
$userProfile = $this->loginSocial();
$profile = SocialProfile::find($userProfile->identifier);
echo var_dump($profile);
if ($profile == NULL) {
//Generate username and password
$username = $this->nameUser($userProfile->displayName);
$password = Str::random(8);
//Create new User
$user = new User;
$user->username = $username;
$user->password = Hash::make($password);
$user->save();
//generate new socialProfile
$sprofile = new SocialProfile;
$sprofile->identifier = $userProfile->identifier;
$sprofile->provider = Input::get('network');
$sprofile->user_id = $user->id;
$sprofile->save();
//login
Auth::login($user);
//redirect back to admin
//include message about changing password
return Redirect::action('LorisLogin@addLocalProfile', array('network' => Input::get('network')));
} else {
return Redirect::action("LorisLogin@loginWithSocial", array('network' => Input::get('network')));
}
} catch (Exception $e) {
return $e->getMessage();
}
}
/**
*
* Creates or Updates local Profile
*
* @return \Exception or Redirect
*/
public function addLocalProfile() {
try {
$user = Auth::user();
//user profile
$up = $this->loginSocial();
//try to get a local profile
$localProfile = Auth::user()->localProfile()->getResults();
//if it does not exist create a new one
if (!$localProfile) {
$localProfile = new LocalProfile;
}
//fill/update
$localProfile->first_name = $up->firstName;
$localProfile->last_name = $up->lastName;
$localProfile->description = $up->description;
$localProfile->gender = $up->gender;
$localProfile->photo_url = $up->photoURL;
$localProfile->birth_day = $up->birthDay;
$localProfile->birth_month = $up->birthMonth;
$localProfile->birth_year = $up->birthYear;
$localProfile->email = $up->email;
$localProfile->address = $up->address;
$localProfile->country = $up->country;
$localProfile->city = $up->city;
$localProfile->zip = $up->zip;
$localProfile->user_id = $user->id;
//save profile
$localProfile->save();
//link to user
$user->local_profile_id = $localProfile->id;
//save User
$user->save();
} catch (Exception $e) {
return $e;
}
return Redirect::route('admin-user-landing');
}
/**
* associates a new Social Profile to a user account
*
* @return Void
*/
public function linkSocialProfile() {
try {
//get user
$user = Auth::user();
//get social Profile
$socialProfile = $this->loginSocial();
//check if Profile is registered already
$dbsp = SocialProfile::find((int) $socialProfile->identifier);
if ($dbsp != NULL) {
if ($dbsp->user()->getResults() == $user) {
return Redirect::route('admin-user-landing')
->with('message', $this->error_messages['registered']);
} else {
return Redirect::route('admin-user-landing')
->with('message', $this->error_messages['registeredToOther']);
}
}
//Add social profile to DB
$user->socialProfiles()->create(array(
'provider' => Input::get('network'),
'identifier' => $socialProfile->identifier,
'user_id' => $user->id,
));
return Redirect::route('admin-user-landing')
->with('message', $this->success_messages['newSProfile'])
->with('sucess', true);
} catch (Exception $e) {
return $e;
}
}
public function fillLocalProfile() {
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:47:40.150",
"Id": "46578",
"Score": "2",
"Tags": [
"php",
"authentication",
"laravel"
],
"Title": "Social user login"
} | 46578 |
<p>I'm currently working on a very simple one-file project:</p>
<p>Lumix provides the possibility for the camera TZ41 (and others) to load GPS data and tourist information from a DVD to a SD-card so that you can see on the camera (which has GPS and the SD card inside) this information. Sadly, the software to copy it on the SD card (with the required folder structure) is not available for Linux. So that's what my lumix-maptool does.</p>
<p>As this should be simple to use, I wanted to create a Debian package. But this is not so simple, so I've created a Python package first and I hope a working Python package will make packaging for Debian easier. But it also is the first time I've created a Python package.</p>
<p>I want the user to be able to install the package and then enter <code>lumixmaptool</code> and get the program. This currently works. </p>
<p>Here are some relevant links:</p>
<ul>
<li><a href="https://github.com/MartinThoma/lumix_map_tool" rel="nofollow">GitHub project repository</a></li>
<li><a href="https://pypi.python.org/pypi/LumixMaptool" rel="nofollow">PyPI page</a></li>
</ul>
<p>Currently, my project structure is:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>.
├── dist <- automatically generated
│ ├── LumixMaptool-1.0.5.tar.gz
│ ├── LumixMaptool-1.0.6.tar.gz
│ ├── LumixMaptool-1.0.7.tar.gz
│ ├── LumixMaptool-1.0.8.tar.gz
│ └── LumixMaptool-1.0.9.tar.gz
├── LICENSE.txt
├── lumixmaptool
│ ├── __init__.py
│ └── lumixmaptool.py
├── lumix-maptool.desktop <- needed for Debian packaging
├── LumixMaptool.egg-info <- automatically generated
│ ├── dependency_links.txt
│ ├── entry_points.txt
│ ├── PKG-INFO
│ ├── requires.txt
│ ├── SOURCES.txt
│ └── top_level.txt
├── lumix-maptool-icon.png <- will be used for Debian packaging
├── README.md
├── setup.cfg
└── setup.py
</code></pre>
</blockquote>
<pre class="lang-python prettyprint-override"><code>3 directories, 19 files
</code></pre>
<h2>setup.py</h2>
<pre class="lang-python prettyprint-override"><code>from setuptools import setup
setup(
name='LumixMaptool',
version='1.0.9',
author='Martin Thoma',
author_email='info@martin-thoma.de',
packages=['lumixmaptool'],
scripts=['lumixmaptool/lumixmaptool.py'],
url='http://pypi.python.org/pypi/LumixMaptool/',
license='LICENSE',
description='Manage GPS information for Panasonic Lumix cameras.',
long_description="""Panasonic offers GPS metadata to add to a SD card. This metadata can contain
tourist information that might be useful for sightseeing. This maptool helps
to copy the data from Lumix DVD to the SD card that is inserted into your
computer (the camera has not to be connected).""",
install_requires=[
"argparse >= 1.2.1",
"pyparsing >= 2.0.1",
"pyparsing >= 2.0.1",
],
entry_points={
'console_scripts':
['lumixmaptool = lumixmaptool:main']
}
)
</code></pre>
<h2>lumixmaptool.py</h2>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python
"""
Author: Martin Thoma <info@martin-thoma.de>,
based on https://github.com/RolandKluge/de.rolandkluge.lumix_map_tool/
from Roland Kluge.
Manage GPS information for Panasonic Lumix cameras.
Panasonic offers GPS metadata to add to a SD card. This metadata can contain
tourist information that might be useful for sightseeing. This maptool helps
to copy the data from Lumix DVD to the SD card that is inserted into your
computer (the camera has not to be connected).
This script was tested with Lumix TZ41.
"""
import os
import re
import shutil
import logging
from argparse import ArgumentParser, RawTextHelpFormatter, Action
from pyparsing import Word, nums, OneOrMore, alphanums
logfile = os.path.join(os.path.expanduser("~"), 'maptool.log')
logging.basicConfig(filename=logfile, level=logging.INFO,
format='%(asctime)s %(message)s')
__version__ = "1.0.9"
region_mapping = {}
region_mapping[1] = 'Japan'
region_mapping[2] = 'South Asia, Southeast Asia'
region_mapping[3] = 'Oceania'
region_mapping[4] = 'North America, Central America'
region_mapping[5] = 'South America'
region_mapping[6] = 'Northern Europe'
region_mapping[7] = 'Eastern Europe'
region_mapping[8] = 'Western Europe'
region_mapping[9] = 'West Asia, Africa'
region_mapping[10] = 'Russia, North Asia'
def is_valid_mapdata(parser, path_to_mapdata):
"""Check if path_to_mapdata is a valid path."""
if os.path.isfile(path_to_mapdata):
return path_to_mapdata
else:
if path_to_mapdata == '':
parser.error("You have to specify the path to the mapdata file "
+ "(it's on a DVD).")
else:
parser.error("The file '%s' does not exist." % path_to_mapdata)
def is_valid_sdcard(parser, path_to_sdcard):
"""Check if sdcard is a valid path."""
if not os.path.exists(path_to_sdcard):
parser.error("The path '%s' does not exist." % path_to_sdcard)
if not os.access(path_to_sdcard, os.W_OK):
parser.error("The path '%s' is not writable" % path_to_sdcard)
else:
return path_to_sdcard
def parse_mapdata(path_to_mapdata):
with open(path_to_mapdata, 'r') as f:
mapdata = f.read()
mapdata_pattern = re.compile("\s*(\d{8})\s*(\d{8})\s*(.*)\s*", re.DOTALL)
num1, num2, data = mapdata_pattern.findall(mapdata)[0]
parsed_map_data = {'num1': num1, 'num2': num2, 'regions': {}}
def regionParsing(x):
parsed_map_data['regions'][int(x[0])] = x[1:]
regionnum = Word(nums, exact=2).setResultsName("region-number")
regionnum = regionnum.setName("region-number")
filename = Word(alphanums + "/.").setResultsName("filename")
filename = filename.setName("filename")
regiondata = Word("{").suppress() + OneOrMore(filename)
regiondata += Word("}").suppress()
regiondata = regiondata.setResultsName("region-data")
regiondata += regiondata.setName("region-data")
region = (regionnum + regiondata).setResultsName("region")
region = region.setName("region")
region.setParseAction(regionParsing)
map_grammar = OneOrMore(region)
data = data.strip() # a strange character at the end
map_grammar.parseString(data)
return parsed_map_data
def copy_maps(path_to_mapdata, path_to_sdcard, regions):
"""Copy map information of regions to sdcard."""
mapdata_cd_folder = '/'.join(path_to_mapdata.split("/")[:-1])
logging.info("mapdata_cd_folder: %s" % mapdata_cd_folder)
#mapdata_on_sdcard = path_to_sdcard + "/PRIVATE/MAP_DATA"
# This works with Panasonic Lumix DMC TZ-41
mapdata_on_sdcard = os.path.join(path_to_sdcard,
"PRIVATE/PANA_GRP/PAVC/LUMIX/MAP_DATA")
if not os.path.exists(mapdata_on_sdcard):
os.makedirs(mapdata_on_sdcard)
mapdata = parse_mapdata(path_to_mapdata)
# Delete previously stored cards
shutil.rmtree(mapdata_on_sdcard, ignore_errors=True)
# And create the directory again
os.makedirs(mapdata_on_sdcard)
for selected_region_id in regions:
print("Copying region '%s' ..." % selected_region_id)
for path in mapdata['regions'][selected_region_id]:
logging.info("Copy file %s" % path)
subdir, filename = path.split("/")
abspath_to_source_file = os.path.join(mapdata_cd_folder, path)
target_dir = mapdata_on_sdcard + "/" + subdir
target_file = target_dir + "/" + filename
logging.info("abspath_to_source_file: %s" % abspath_to_source_file)
logging.info("target_dir: %s" % target_dir)
logging.info("target_file: %s" % target_file)
if not os.path.exists(target_dir):
os.mkdir(target_dir)
if not os.path.exists(target_file):
shutil.copy(abspath_to_source_file, target_dir)
print("Copying region '%i' DONE" % selected_region_id)
print("All operations exited succesfully.")
class UniqueAppendAction(Action):
"""Make sure that the list of regions contains unique values."""
def __call__(self, parser, namespace, values, option_string=None):
unique_values = set(values)
setattr(namespace, self.dest, unique_values)
def autodetect_mapdata():
"""Try to find the DVD with map data."""
path = "/media"
subdir = [f for f in os.listdir(path)
if os.path.isdir(os.path.join(path, f))]
while len(subdir) == 1:
path = os.path.join(path, subdir[0])
subdir = [f for f in os.listdir(path)
if os.path.isdir(os.path.join(path, f))]
if "MAP_DATA" in subdir:
path = path = os.path.join(path, "MAP_DATA/MapList.dat")
return path
return ""
def main():
parser = ArgumentParser(description=__doc__,
formatter_class=RawTextHelpFormatter)
# Add more options if you like
parser.add_argument("-m", "--mapdata", dest="mapdata", metavar="MAPDATA",
default=autodetect_mapdata(),
help="path to MAPDATA folder on the Lumix DVD",
type=lambda x: is_valid_mapdata(parser, x))
parser.add_argument("-s", "--sdcard", dest="path_to_sdcard",
metavar="SDCARD", required=True,
help="path to SDCARD",
type=lambda x: is_valid_sdcard(parser, x))
helptext = "The space-separated indices of the regions to copy. "
helptext += "E.g. 1 6 10. At least one region needs to be given. "
helptext += "Regions are:\n"
tmp = map(lambda i: "%i -\t%s" % (i, region_mapping[i]), range(1, 11))
helptext += "\n".join(list(tmp))
parser.add_argument("-r", "--regions", dest="regions", nargs='+',
required=True, choices=list(range(1, 11)), type=int,
action=UniqueAppendAction,
help=helptext)
parser.add_argument('--version', action='version', version='%(prog)s '
+ __version__)
args = parser.parse_args()
copy_maps(args.mapdata, args.path_to_sdcard, args.regions)
if __name__ == "__main__":
main()
</code></pre>
<h2><strong>init</strong>.py</h2>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python
import lumixmaptool
if __name__ == "__main__":
lumixmaptool.main()
</code></pre>
<p><strong>Especially I would like to know if the way I currently use the <code>__init__.py</code> is correct and if my project structure makes sense.</strong> But I'm also interested in general coding advice.</p>
<p>I've used <a href="http://pep8online.com/" rel="nofollow">http://pep8online.com/</a> to check for "obvious" advice.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T20:30:06.660",
"Id": "81411",
"Score": "0",
"body": "A quick note ... for multiline strings, you can use parenthesis rather than += ... `helptext = ('abc' [newline] 'def' [newline] 'ghi')`"
}
] | [
{
"body": "<p>This is really nice code. Clean, documented, idiomatic. I couldn't have written it any better, but that doesn't mean I wouldn't find stuff to improve further ;-)</p>\n\n<h2>Regarding the Code</h2>\n\n<p>For example, this regex: <code>\\s*(\\d{8})\\s*(\\d{8})\\s*(.*)\\s*</code>. The <code>\\s*</code> at either end is completely irrelevant, because your regex isn't anchored anywhere and you do not capture their values. Note furthermore that due to the <code>DOTALL</code> option, the <code>.*</code> will consume <em>all</em> remaining characters, so not only is the trailing <code>\\s*</code> but also the <code>findall</code> unnecessary, use <code>search</code> instead:</p>\n\n<pre><code>match = re.search(\"(\\d{8})\\s*(\\d{8})\\s*(.*)\", mapdata)\nif not match:\n # handle error because of malformed data\nnum1, num2, data = match.groups()\n</code></pre>\n\n<p>Should you actually have wanted to anchor at the beginning, reintroduce the leading <code>\\s*</code> but use <code>re.match</code> instead of <code>re.search</code>.</p>\n\n<p>If you really want to precompile the regex, do so outside of your function. Likewise, the grammar could be assembled outside of <code>parse_mapdata</code>. It furthermore irks me that you are reassigning parts of the grammar<sup>[1]</sup>, and could have abstracted over the <code>foo = foo.setResultsName(\"foo\"); foo = foo.setName(\"foo\")</code> e.g. with a function like this:</p>\n\n<pre><code>def named(name, rule):\n return rule.setResultsName(name).setName(name)\n\nregionnum = named(\"region-number\", Word(nums, exact=2))\nfilename = named(\"filename\", Word(alphanums + \"/.\"))\nregiondata = named(\"region-data\",\n Word(\"{\").suppress() + OneOrMore(filename) + Word(\"}\").suppress())\nregion = named(\"region\", (regionnum + regiondata))\n</code></pre>\n\n<p>The next eyesore is probably how you initialized the <code>region_mapping</code>. A dict literal would be a bit cleaner:</p>\n\n<pre><code>region_mapping = {\n 1: 'Japan',\n 2: 'South Asia, Southeast Asia',\n ...\n</code></pre>\n\n<p>You have the habit of concatenating strings in ways that are not really appropriate, in the sense that these do not aid readability. For example, the line wrapping in</p>\n\n<pre><code>parser.add_argument('--version', action='version', version='%(prog)s '\n + __version__)\n</code></pre>\n\n<p>makes sense from a use-as-much-of-each-line-as-possible viewpoint, but it obscures what <code>__version__</code> is being concatenated with. While PEP-8 states: “<em>The preferred place to break around a binary operator is after the operator, not before it</em>”, I'd rather align the named arguments:</p>\n\n<pre><code>parser.add_argument('--version',\n action='version',\n version='%(prog)s ' + __version__)\n</code></pre>\n\n<p>New lines are cheap, so we can use lots of them :) I'd suggest the one-named-argument-per-line for the remaining argument parser setup as well, but that's a personal preference.</p>\n\n<p>Related to concatenation, is this:</p>\n\n<pre><code>helptext = \"The space-separated indices of the regions to copy. \"\nhelptext += \"E.g. 1 6 10. At least one region needs to be given. \"\nhelptext += \"Regions are:\\n\"\ntmp = map(lambda i: \"%i -\\t%s\" % (i, region_mapping[i]), range(1, 11))\nhelptext += \"\\n\".join(list(tmp))\n</code></pre>\n\n<p>It makes sense where you are breaking up the strings, but I'd rather concatenate instead of append:</p>\n\n<pre><code>helptext =\n \"The space-separated indices of the regions to copy. \" +\\\n \"E.g. 1 6 10. At least one region needs to be given. \" +\\\n \"Regions are:\\n\" +\\\n \"\\n\".join([\"%i -\\t%s\" % (i, region_mapping[i]) for i in range(1, 11)])\n</code></pre>\n\n<p>Note also the <code>for</code>-comprehension instead of <code>map</code>. I see that my suggested solution uses backslashes (which are sometimes unavoidable) and has a line length over 79 characters. As <a href=\"https://codereview.stackexchange.com/questions/46587/python-single-script-packaging#comment81411_46587\">jcfollower points out in an above comment</a>, this could be partially solved with implicit concatenation:</p>\n\n<pre><code>helptext = (\n \"The space-separated indices of the regions to copy. \"\n \"E.g. 1 6 10. At least one region needs to be given. \"\n \"Regions are:\\n\"\n (\"\\n\".join([\"%i -\\t%s\" % (i, region_mapping[i]) for i in range(1, 11)]))\n)\n</code></pre>\n\n<p>The extra parens around the <code>join</code> are mandatory in this case, because the implicit concatenation has a higher precedence than a method call (WTF, Python?).</p>\n\n<p>One issue that remains here is the magic number <code>range(1, 11)</code>, which should ideally have been taken directly from <code>region_mapping</code>.</p>\n\n<p>In <code>autodetect_mapdata</code> you've copy&pasted a small piece of code:</p>\n\n<pre><code>[f for f in os.listdir(path)\n if os.path.isdir(os.path.join(path, f))]\n</code></pre>\n\n<p>This would become much more readable with a small helper function:</p>\n\n<pre><code>def autodetect_mapdata():\n \"\"\"Try to find the DVD with map data.\"\"\"\n def subdirectories(*path_fragments):\n path = os.path.join(*path_fragments)\n subdirs = [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]\n return path, subdirs\n\n path, subdirs = subdirectories(\"/media\")\n while len(subdirs) == 1: \n path, subdirs = subdirectories(path, subdirs[0])\n\n if \"MAP_DATA\" in subdirs:\n return os.path.join(path, \"MAP_DATA\", \"MapList.dat\")\n return \"\"\n</code></pre>\n\n<p>This also happens to get rid of the entertaining</p>\n\n<pre><code>path = path = os.path.join(path, \"MAP_DATA/MapList.dat\")\nreturn path\n</code></pre>\n\n<h2>Regarding the Project Structure</h2>\n\n<p>This is done quite nicely, although <code>__init__.py</code> is not used correctly. When a user says <code>import lumixmaptool</code>, this file will be executed – that is, the sole purpose of this file is to allow a directory to be used as a package. The symbols in this file's namespace make up the public API. If I understand Python packaging correctly, users would currently have to say <code>from lumixmaptools import lumixmaptools</code> to get actual access to the functions.</p>\n\n<p>Instead, <code>lumixmaptool/__init__.py</code> should probably be:</p>\n\n<pre><code># this will import symbols from the inner, internal package\nfrom . lumixmaptools import __version__, main, copy_maps\n</code></pre>\n\n<p>It would make sense to rename the internal package to avoid confusion.</p>\n\n<p>The <code>if __name__ == \"__main__\"</code> trick does not work here, unless you invoke the package by a full path: <code>python /wherever/its/installed/lumixmaptool/__init__.py</code>. If you want to execute it as a command line tool via <code>python -m lumixmaptool</code>, we offer a <code>__main__</code> submodule (file <code>lumixmaptool/__main__.py</code>):</p>\n\n<pre><code>from . __init__ import *\n\nmain()\n</code></pre>\n\n<p>We can furthermore improve the <code>setup.py</code>.</p>\n\n<ul>\n<li><code>license</code> should rather be an actual license like <code>MIT</code>.</li>\n<li>don't list your module in <code>scripts</code>, now that we can invoke it properly</li>\n<li>you could also specify classifiers and keywords for your module.</li>\n</ul>\n\n<p>I noticed that your project doesn't have any tests. This is understandable, but unacceptable if you want to distribute this. At the very least, a check that the module compiles successfully would be a step forward. If you change <code>parse_mapdata</code> to take not the filename but the contents of the file as argument, it will be very straightforward to add a few tests for this crucial function as well.</p>\n\n<hr>\n\n<p>[1]: I am a fan of single-assignment form</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:10:39.000",
"Id": "81423",
"Score": "0",
"body": "(and by the way, greetings from Karlsruhe to Karlsruhe)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T02:27:22.597",
"Id": "81439",
"Score": "0",
"body": "You're from Karlsruhe? Do you also study computer science at KIT? Do we eventually know each other?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T02:28:08.157",
"Id": "81441",
"Score": "0",
"body": "Thanks for your advice. Could you please tell me if the way I use `__init__.py` is correct and if my project structure makes sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T09:14:20.997",
"Id": "81464",
"Score": "0",
"body": "@moose I added an update regarding the project structure, but keep in mind that I'm not terribly knowledgeable about this kind of stuff. I do study at the KIT, but CS is only my minor. I recognized you from the Facebook group, but we don't know each other IRL."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:10:08.880",
"Id": "46597",
"ParentId": "46587",
"Score": "7"
}
},
{
"body": "<p>On top of amon's comment about <code>region_mapping</code> :</p>\n\n<blockquote>\n <p>A dict literal would be a bit cleaner.</p>\n</blockquote>\n\n<p>It would indeed be better than the way you are setting the dict at the moment. However, an even simpler solution could be done : just use a list and generate the indices on demand with <code>enumerate()</code> :</p>\n\n<pre><code>region_mapping = ['Japan', 'South Asia, Southeast Asia', 'Oceania', 'North America, Central America', 'South America', 'Northern Europe', 'Eastern Europe', 'Western Europe', 'West Asia, Africa', 'Russia, North Asia']\nprint \"\\n\".join(\"%i -\\t%s\" % (i+1,r) for i,r in enumerate(region_mapping))\n</code></pre>\n\n<p>Many advantages :</p>\n\n<ul>\n<li>you don't have to care about the indices.</li>\n<li>you don't have to care about the length of the dictionnary.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:20:27.980",
"Id": "46648",
"ParentId": "46587",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T20:13:41.050",
"Id": "46587",
"Score": "5",
"Tags": [
"python",
"parsing",
"regex",
"linux",
"file-system"
],
"Title": "Packaging a single-file Python copy-tool"
} | 46587 |
<p>I am slowly learning C and C++, and decided after a few lessons to dive in myself without any help. I developed this prime number generator. It seems fast, but I'm wondering if I'm <strong>following the best practices for C++</strong>, or if I am missing anything important.</p>
<pre><code>#include "stdafx.h"
#include "stdio.h"
bool checkPrime(int Number);
int _tmain(int argc, _TCHAR* argv[])
{
int currentNum;
currentNum = 2;
do {
if (checkPrime(currentNum)) {
printf("%d ", currentNum);
}
currentNum++;
} while (1 == 1);
return 0;
}
bool checkPrime(int Number){
for (int a = 2; a < Number; a++){
if (Number % a == 0) {
return false;
}
}
return true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T03:04:38.903",
"Id": "81444",
"Score": "5",
"body": "to check for a prime, no need to loop all from 2 to n, just odd numbers from 2 to sqrt(n) is enough"
}
] | [
{
"body": "<ul>\n<li><p>In C++, you should now use <code>std::cout</code> and <code>std::cin</code> instead of <code>printf()</code> and <code>scanf()</code> respectively. These are found in <a href=\"http://en.cppreference.com/w/cpp/header/iostream\" rel=\"nofollow\"><code><iostream></code></a>, and you'll no longer need <code><stdio.h></code>.</p>\n\n<p>Example of <code>std::cout</code>:</p>\n\n<pre><code>int number = 1;\nstd::cout << \"Number: \" << number;\n</code></pre>\n\n<p>Example of <code>std::cin</code>:</p>\n\n<pre><code>int number;\nstd::cin >> number;\n</code></pre></li>\n<li><p><code>currentNum</code> just needs to be initialized, not declared and then assigned:</p>\n\n<pre><code>int currentNum = 2;\n</code></pre></li>\n<li><p>The <code>do while</code> loop condition should just be <code>1</code>, not <code>1 == 1</code>. This still equates to <code>true</code>.</p></li>\n<li><p>You can put <code>main()</code> below every function, eliminating the need for function prototypes since it will already know the existence of these functions.</p></li>\n<li><p>You don't need <code>return 0</code> at the end of <code>main()</code>. This is a special case in that the compiler will automatically insert <code>return 0</code> as reaching this point always indicates a successful termination.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T20:04:18.613",
"Id": "87372",
"Score": "0",
"body": "Beware: iostreams vs. stdio is controversial among C++ programmers. Definitely avoid scanf, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:24:13.283",
"Id": "46591",
"ParentId": "46590",
"Score": "19"
}
},
{
"body": "<p>This loop…</p>\n\n<pre><code>int currentNum;\ncurrentNum = 2;\ndo {\n if (checkPrime(currentNum)) {\n printf(\"%d \", currentNum);\n }\n currentNum++;\n} while (1 == 1);\n</code></pre>\n\n<p>… would be better written as a <code>for</code> loop:</p>\n\n<pre><code>for (int currentNum = 2; /* TODO: fix overflow */ ; currentNum++) {\n if (checkPrime(currentNum)) {\n printf(\"%d \", currentNum);\n }\n}\n</code></pre>\n\n<p>For readability, <code>checkPrime()</code> should be renamed <code>isPrime()</code>. Its parameter should be named <code>number</code> (lowercase).</p>\n\n<p>You are using a brute-force trial division algorithm. That works, but when you want a list of <em>many</em> prime numbers, the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\">Sieve of Eratosthenes</a> is a much more efficient algorithm.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:44:50.497",
"Id": "46593",
"ParentId": "46590",
"Score": "14"
}
},
{
"body": "<p>A few things in addition to what <a href=\"https://codereview.stackexchange.com/users/22222/jamal\">@Jamal</a> and <a href=\"https://codereview.stackexchange.com/users/9357/200-success\">@200_success</a> already wrote:</p>\n\n<ul>\n<li><p><code>g++</code> on Mac OS X won't compile this code, because of <code>#include \"stdafx.h\"</code> and the <code>int _tmain(int argc, _TCHAR* argv[])</code> signature. It's good to keep your code portable, unless you have a special reason not to. <code>g++</code> can compile if you drop the <code>stdafx.h</code> import and if change the <code>main</code> declaration.</p></li>\n<li><p>... and since you're not using the arguments of <code>main</code>, you could just declare without any args: <code>int main() { ... }</code>.</p></li>\n<li><p>As you already used <code>true</code> in the <code>checkPrime</code> function, why not use it in the infinite <code>while</code> loop in <code>main</code>, instead of <code>1 == 1</code>.</p></li>\n<li><p>This may be a matter of taste, but I think <code>while (true) { ... }</code> is generally more readable and intuitive than <code>do { ... } while (true)</code>.</p></li>\n<li><p>... actually, as @200_success pointed out, a <code>for (int currentNum = 2; ; currentNum++) { ... }</code> loop would be even better: this way <code>currentNum</code> is declared in the block where it is used, eliminating potential side effects, and the counter is a natural element in a <code>for</code> loop. Notice the empty terminating condition, making this an infinite loop.</p></li>\n<li><p>In <code>checkPrime</code> you named the variable <code>int Number</code>, but the common convention is to not capitalize variable names, use simply <code>int number</code> instead.</p></li>\n<li><p>As <a href=\"https://codereview.stackexchange.com/users/12987/leetnightshade\">@leetnightshade</a> pointed out, place the opening curly either always on the same line as the function name (\"Egyption brackets\"), or always on the next line.</p></li>\n</ul>\n\n<h3>Suggested implementation</h3>\n\n<pre><code>#include <iostream>\n\nbool isPrime(int number)\n{\n for (int a = 2; a < number; a++) {\n if (number % a == 0) {\n return false;\n }\n }\n return true;\n}\n\nint main()\n{\n for (int currentNum = 2; ; currentNum++) {\n if (isPrime(currentNum)) {\n std::cout << currentNum << \" \";\n }\n }\n}\n</code></pre>\n\n<p>This compiles with <code>g++</code> without warnings and runs fine in Mac OS X and GNU/Linux. I would hope it works as expected in Windows too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:08:17.440",
"Id": "81422",
"Score": "4",
"body": "To be consistent all functions should not have Egyptian brackets, or all should. Right now `main` and `isPrime` are inconsistent in that regard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T23:30:16.183",
"Id": "81430",
"Score": "0",
"body": "@leetNightshade: What are `Egyptian` brackets. Not heard that term before. Though I agree with the general comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T00:15:02.653",
"Id": "81433",
"Score": "1",
"body": "@LokiAstari Egyptian brackets are placing the opening curly on the same line as the function name eg: foo(){ as opposed to foo()\\n{ (using \\n to signify new line as I cant put one in a comment.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:01:41.033",
"Id": "81488",
"Score": "0",
"body": "@Vality hmm, weird name for standard K&R bracing. But indeed not proper for C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:10:46.397",
"Id": "81493",
"Score": "0",
"body": "@jwenting I am not sure where the term came from, I think it is the term used for that style of brackets in Java where K&R style would have no meaning. However it is easy enough to guess what is meant in C also. Personally I always prefer the next line as else my eyes have trouble matching pairs of brackets but it is a valid style in some conventions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:56:25.327",
"Id": "81510",
"Score": "0",
"body": "@LokiAstari I believe it's from [New programming jargon you coined? on SO](http://stackoverflow.com/a/2801919/445517) (deleted). [Image](http://www.muppin.com/quilts/egyptian.jpg)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:23:38.190",
"Id": "81541",
"Score": "0",
"body": "And in the `isPrime` function, you can change the check for `a < number` in the `for`-loop to `a * a < number`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T20:21:09.437",
"Id": "81608",
"Score": "0",
"body": "@jwenting I had not heard of the K&R style. Now that I know there is a proper name, I'll start using that. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T22:35:12.330",
"Id": "81631",
"Score": "0",
"body": "@jwenting Here's a visual for you, Egyptian brackets aren't the same thing as the K&R indenting, as K&R uses mixed brackets. http://pdgeeks.com/images/posts/egyptian-brackets.png"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:45:32.573",
"Id": "46594",
"ParentId": "46590",
"Score": "30"
}
},
{
"body": "<p>One thing you might want to look at is more efficient code. You're running a loop for each number you want to check. Using a Sieve of Eratosthenes means you do all your looping once and the index of the vector returns true or false according to whether it's prime:</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <cmath>\n\nstd::vector<bool> MakePrimes(int upperlimit)\n{\n int bound = (int) floor(sqrt(upperlimit));\n upperlimit++;\n std::vector<bool> primes(upperlimit, true);\n\n primes[0] = false;\n primes[1] = false;\n //Since 2 is a special case if we do it separately we can optimize the rest since they will all be odd\n for(int i = 4; i < upperlimit; i += 2)\n {\n primes[i] = false;\n }\n //Since the only ones we need to look at are odd we can step by 2\n for (int i = 3; i <= bound; i += 2)\n {\n if (primes[i]) \n {\n //Since all the even multiples are already accounted for we start at the first one \n //and skip to every other multiple\n for (int j = i*i; j < upperlimit; j += i * 2)\n {\n primes[j] = false;\n }\n }\n }\n return primes;\n}\nint main()\n{\n int limit = 1000;\n std::vector<bool>checkPrime = MakePrimes(limit);\n int currentNum = 1;\n while (currentNum++ < limit)\n {\n if (checkPrime[currentNum]) \n std::cout << currentNum << \"\\n\";\n } \n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T01:29:58.493",
"Id": "46603",
"ParentId": "46590",
"Score": "15"
}
}
] | {
"AcceptedAnswerId": "46594",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:19:16.990",
"Id": "46590",
"Score": "23",
"Tags": [
"c++",
"beginner",
"primes"
],
"Title": "Prime number generator in C++"
} | 46590 |
<p>For this project, I do not have access to Boost or C++11.</p>
<p><strong>Note:</strong> I updated the question's description to clarify what I am doing. I have not changed the code though, so no answer has been invalidated.</p>
<p>I have to deal with functions that return error codes.<br>
When one of these functions fails in exceptional cases, I would like to construct an error message and throw a custom exception. Constructing an error message is rather cumbersome though because different functions in different contexts have varying information that would be useful to pass.</p>
<p>An example would be: </p>
<p>Let's say I'm trying to read data from an XML file and this is my interface:</p>
<pre><code>// In header file
struct FooData
{
std::string strName ;
std::vector <int> vecScores ;
};
struct FooDataException : public std::runtime_error
{
FooDataException (const std::string &strWhat) : std::runtime_error (strWhat) {}
}
class FooDataLoader
{
public:
FooDataLoader () ;
~FooDataLoader () ;
std::vector <FooData> LoadFooData (const std::string &strPath) const ;
};
</code></pre>
<p>In my implementation file, I have two functions that help construct error messages to throw:</p>
<pre><code>static void ThrowFunctionFailure (
const std::string &strWhere,
const std::string &strFunction,
const std::string &strMessage)
{
std::stringstream ss ;
ss << "In " << strWhere
<< ", " << strFunction << "failed. "
<< strMessage ;
throw FooDataException (ss.str ()) ;
}
static void ThrowError (const std::string &strWhere, const std::string &strMessage)
{
std::stringstream ss ;
ss << "In " << strWhere << ", an error occurred. " << strMessage ;
throw FooDataException (ss.str ()) ;
}
</code></pre>
<p>Now, these functions remove a lot of code duplication, but I still have to construct an error message at the site:</p>
<pre><code>FooDataLoader::FooDataLoader ()
{
const HRESULT hr = ::CoInitialize (NULL) ;
if (FAILED (hr)) {
std::stringstream ss ;
ss << "HRESULT: " << hr << "." ;
throw ThrowFunctionFailure (
"FooDataLoader::FooDataLoader ()",
"::CoInitialize ()",
ss.str ()
) ;
}
}
FooDataLoader::~FooDataLoader ()
{
::CoUninitialize () ;
}
std::vector <FooData> FooDataLoader::LoadFooData (const std::string &strPath) const
{
if (FileExist (strPath) == false) {
std::stringstream ss ;
ss << "The file, " << strPath << ", does not exist." ;
ThrowError ("FooDataLoader::LoadFooData ()", ss.str ()) ;
}
// Some xml library I have to use.
XmlReader xml ;
if (xml.read (strPath.data ()) == -1) {
std::stringstream ss ;
ss << "File: " << strPath << "." ;
ThrowFunctionFailure (
"FooDataLoader::LoadFooData ()",
"XmlReader::read ()",
ss.str ()
) ;
}
// More stuff...
}
</code></pre>
<p>I would like to do something like:</p>
<pre><code>ThrowFunctionFailure (
"FooDataLoader::LoadFooData ()",
"XmlReader::read ()",
(std::stringstream () << "File: " << strPath << ".").str ()
) ;
</code></pre>
<p>But that doesn't work for <code>std::stringstream</code> (at least it doesn't work on my compiler (Visual Studio 2008)).</p>
<p>Based on <a href="https://stackoverflow.com/a/5966638/3033711">this answer</a>, I wrote a quick and dirty workaround:</p>
<pre><code>#include <string>
#include <sstream>
template <typename StringStreamT = std::stringstream, typename StringT = std::string>
class QuickStringStream
{
public:
typedef StringStreamT stringstream_type ;
typedef StringT string_type ;
QuickStringStream () {}
QuickStringStream (const string_type strData) {
ss_ << strData ;
}
template <typename T>
QuickStringStream& operator<< (const T &tVal) {
ss_ << tVal ;
return *this ;
}
string_type str () const
{
return ss_.str () ;
}
private:
stringstream_type ss_ ;
};
</code></pre>
<p>This does what I want, but I can't get rid of the feeling that this is a horrible idea.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T00:17:38.490",
"Id": "81434",
"Score": "0",
"body": "In your example at the end, i'd much rather see you provide a function that returns an `ostream` ref. Then the caller doesn't have to do all that farting around with converting strings to streams and back. It can just write to the stream. (This won't work everywhere, of course...but for I/O, it's a lot less ugly.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T02:21:34.887",
"Id": "81438",
"Score": "1",
"body": "Have you considered using `std::to_string` or `boost::lexical_cast` to just concatenate strings rather than using streams? (If you're not using C++11 or you don't want to use boost or one function, you can write your own in about 2 lines using streams.) You give up the ability to use manipulators, and it would likely end up being less efficient from all the implicit `std::string` constructions, but... It would be a lot less verbose and would fit your current usecase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:37:23.620",
"Id": "81556",
"Score": "0",
"body": "@Corbin No I haven't considered those options. I might just create a custom set of functions that simulate `std::to_string`."
}
] | [
{
"body": "<p>This strikes me as really fitting better on SO than here. At least IMO, what you need more than a review of this code is an idea of how to replace it with something better.</p>\n\n<p>I guess for the sake of topicality, I'll review at least the interface you've devised. You start with a function that prints a single string to standard output, but it could apparently be just about any function that takes a single string as its input. If you really just wanted to print to standard output, it would be easiest to just use <code>std::cout</code> directly, so I'm going to assume you want to be able to use other functions as well.</p>\n\n<p>Anyhow, you then devise a class that (unlike a stringstream) actually works as a temporary object, then pass its <code>.str()</code> to your function.</p>\n\n<p>To put things simply, that strikes me as a fairly poor approach. In particular, it makes the client code fairly ugly. It still requires that client code to be shaped by the fact that your function accepts only one argument of fixed type, but you want to pass arbitrary arguments to it. As such, my honest conclusion on the code would be that it's ripe (and then a little) to be thrown out and replaced with something better.</p>\n\n<p>Now comes the part of the answer that probably belongs more on SO than here: how to design something better suited to the task, but more starting over from the apparent requirements than really improving the code in your question.</p>\n\n<p>I'd consider two rather different approaches. One would be to simply write a manipulator to invoke your function with the current content of the stringstream. As luck would have it, I posted an <a href=\"https://codereview.stackexchange.com/a/46234/489\">answer like this</a> just a couple days ago. This does still involve creating a named stringstream object (can't use a temporary, sorry), streaming things to it, and as the last argument, passing the name of your manipulator that will execute a function on the current content of the stream. An improvement over a plain stream, but I'd guess still not quite what you'd like.</p>\n\n<p>My second (and preferred, if you can use C++11 features) suggestion would be to use a variadic function, something like this:</p>\n\n<pre><code>#include <sstream>\n#include <string>\n#include <iostream>\n\ntemplate <class T>\nstd::string stringify(T const &t) {\n // This could use lexical_cast, but for now we'll keep dependencies to a minimum\n std::stringstream b;\n b << t;\n return b.str();\n}\n\ntemplate<typename T, typename... Args>\nstd::string stringify(T arg, const Args&... args) {\n return stringify(arg) + stringify(args...);\n}\n\ntemplate<typename F, typename... Args>\nvoid send_cmd(F &f, const Args&... args) {\n std::string buffer = stringify(args...);\n f(buffer);\n}\n\nvoid print(std::string const &s) { std::cout << s; }\n\nint main() {\n std::string three{ \" three\" };\n\n send_cmd(print, \"one: \", 1, \" two plus: \", 2.01, three, '\\n');\n\n return 0;\n}\n</code></pre>\n\n<p>This lets us pass an arbitrary number of arguments, each of arbitrary type. It writes each to a stringstream, then concatenates those strings. The demo code passes a few C-style strings, an int, a double, an <code>std::string</code> and a <code>char</code>, but it should also work with essentially anything else you can insert into a stream (including types using user-defined overloads).</p>\n\n<p>Although I've used a <code>print</code> that works about like your <code>println</code> (just prints out the string), essentially any other function that can be called with a single string parameter should work as well.</p>\n\n<p>When/if you just want to put the items together into a string like your:</p>\n\n<pre><code>std::string s = (\n QuickStringStream <> () << \"Hello, \" << 5 << \" + \" << 5 << \" = \" << 10 << \".\"\n ).str () ;\n</code></pre>\n\n<p>...you can just call <code>stringify</code> directly:</p>\n\n<pre><code>std::string s = stringify(\"Hello, \", 5, \" + \", 5, \" = \", 10, \".\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:36:00.477",
"Id": "81555",
"Score": "0",
"body": "I wish I could use variadic templates, but I can't use C++11 for this project. Boost is also not available. I'll have too look into writing my own manipulator."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T05:35:33.457",
"Id": "46614",
"ParentId": "46596",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:03:01.573",
"Id": "46596",
"Score": "4",
"Tags": [
"c++",
"strings",
"formatting",
"stream"
],
"Title": "Format string inline"
} | 46596 |
<p>This function checks if a list is sorted.</p>
<pre><code>isSorted' :: (Ord a) => [a] -> [a] -> a -> Bool
isSorted' [] [] _ = True
isSorted' (x:xs) [] _ = isSorted' xs xs (head xs)
isSorted' orig (x:xs) a
| a > x = False
| otherwise = isSorted' orig xs a
</code></pre>
<p>I don't like how this function requires that the list be entered twice. But, I need to check all items of the list.</p>
<p>For example, if I only checked if the head was greater than any of the other items, then the following could happen:</p>
<pre><code>[-5, 10, -6] -- check only first element and will evaluate to true
--
</code></pre>
<p>But, we'll find out that this list is not sorted given the fact that 10 is greater than -6.</p>
<pre><code>[10, -6] -- evaluates to False
</code></pre>
<p>How can I simplify/clean up this function?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T02:34:38.190",
"Id": "81443",
"Score": "0",
"body": "The classic formulation would be something like: the first item in the list is less than the second, and the rest of the list (after the first item) is sorted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T06:58:15.407",
"Id": "81449",
"Score": "0",
"body": "Did you write this function? Looking at the prime (') in the function name and the auxiliary parameters; this function clearly is supposed to be called from a wrapper function like this: `isSorted xs = isSorted' xs xs (head xs)` (trivial case ignored) Although still badly written (clunky and inefficient) the wrapper has the correct type signature, so that you do not need to pass the input list twice."
}
] | [
{
"body": "<p>Generally, when you're using explicit recursion in Haskell, there is an easier way. There are many higher order function that will do this recursion for you (<code>map</code>, <code>fold</code> and <code>filter</code> being the quintessential examples).</p>\n\n<p>In this case, we want to go through the list, checking each element against the next element. Whenever you want to do something on a list element and the next list element, you should start thinking of <code>zip</code>: this takes two lists and \"zips\" them together. For example:</p>\n\n<blockquote>\n <p>zip [1, 2, 3] [4, 5, 6] == [(1, 4), (2, 5), (3, 6)]</p>\n</blockquote>\n\n<p>In this case, we want to offset this by one, however. The easiest way of doing this is to simply use <code>tail</code>:</p>\n\n<pre><code>zip xs (tail xs)\n</code></pre>\n\n<p>So if we had a list like:</p>\n\n<blockquote>\n <p>[1,2,3,4]</p>\n</blockquote>\n\n<p>This would give us back:</p>\n\n<blockquote>\n <p>[(1, 2), (2, 3), (3, 4)]</p>\n</blockquote>\n\n<p>Ok, so now we have this list of pairs that we need to compare. Instead of using recursion and pattern matching, we'll use a higher order function: in this case, <code>all</code> is what we're looking for. This has the type signature:</p>\n\n<pre><code>all :: (a -> Bool) -> [a] -> Bool\n</code></pre>\n\n<p>Ok, so this takes a function from <code>(a -> Bool)</code> and a list of <code>a</code>, and gives back a <code>Bool</code>. </p>\n\n<p>Now, all we need to do is decide on the function <code>(a -> Bool)</code>. In this case, it's pretty simple: we just want to take a tuple of two values and check if the first is less than the second. We can write this succinctly using a lambda:</p>\n\n<pre><code>(\\(x, y) -> x <= y)\n</code></pre>\n\n<p>Putting this all together, we get:</p>\n\n<pre><code>isSorted :: (Ord a) => [a] -> Bool\nisSorted xs = all (\\(x, y) -> x <= y) $ zip xs (tail xs)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T11:27:29.793",
"Id": "82096",
"Score": "3",
"body": "`isSorted xs = and $ zipWith (<=) xs (tail xs)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T03:04:16.293",
"Id": "46608",
"ParentId": "46606",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46608",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T02:16:40.880",
"Id": "46606",
"Score": "6",
"Tags": [
"haskell"
],
"Title": "Is a List Sorted?"
} | 46606 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.