body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>My User model has multiple roles (utilizing CanCan). Each role's dashboard view is different enough to warrant a partial for each role (admins get big-picture reports of users and app activity, students get big-picture overviews of grades, current courses, and lessons to be taken).</p>
<p>At first I had a case statement to iterate through the views based on <code>current_user.role</code> (of course, that was just temporary, even I know that!). Now, I have this:</p>
<pre><code><%= render "#{current_user.role}" %>
</code></pre>
<p>This doesn't feel right. What's the proper way to dynamically render partials (or maybe this method is perfectly fine)? Also, please mention why the proper way is best, as I want to learn from this.</p>
|
[] |
[
{
"body": "<p>You can override <code>ActiveModel#to_partial_path</code> if you want - same as how you might override <code>to_param</code>. See <a href=\"http://api.rubyonrails.org/classes/ActiveModel/Conversion.html\" rel=\"nofollow\">the documentation</a> (and be sure to check <a href=\"https://github.com/rails/rails/blob/64146cf7babe35fd962576b699fa0deb4cfe0d70/activemodel/lib/active_model/conversion.rb\" rel=\"nofollow\">the source</a> too - they're doing some caching that's elided in the docs, but might be worth looking in to).</p>\n\n<p>Anyway, in your case, you could likely just redefine the method on the User model like so:</p>\n\n<pre><code># in app/models/user.rb\nclass User < ActiveRecord::Base\n # ...\n def to_partial_path\n collection = ActiveSupport::Inflector.tableize(self)\n \"#{collection}/#{self.role}\"\n end\nend\n</code></pre>\n\n<p>This way, you can use <code>render</code> as you would normally. You'll only be doing what Rails is already doing - just a little differently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T21:59:44.120",
"Id": "29663",
"Score": "0",
"body": "Thanks Flambino. I'm wondering though, what benefits would this have over the method I'm using currently? It's a bit more verbose and, to me at least, the other method seems more readable. Also, I'm guessing from the code that I'd call this with something like `render user` and `to_partial_path` would select the correct partial, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T22:19:11.570",
"Id": "29666",
"Score": "0",
"body": "@GorrillaMcD it's (negligibly) more verbose, but arguably more correct, since it's \"the Rails Way\" to have a model define its partial path. Besides, role is defined on the model, so why shouldn't the partial path be when it's dependent on the role? But really, there aren't many alternatives: The partial path is an expression; it's either inline in the view, or in a method. Your code uses the former, this uses the latter (which can be anywhere, but this is in keeping with conventions). Not much else you can do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T22:28:47.913",
"Id": "29668",
"Score": "0",
"body": "Thanks for the explanation. I was just curious as to why it's better that's all. Thanks again."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T20:01:49.640",
"Id": "18629",
"ParentId": "18627",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18629",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T19:48:35.223",
"Id": "18627",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Rendering partials dynamically in Rails 3"
}
|
18627
|
<p>I have two scripts written by my co-workers for auto-filling a form with information from the Facebook graph-api. I am trying to figure out which has been coded in a more efficient style?</p>
<p>This is the first one. <a href="http://jsfiddle.net/TcGGZ/30/" rel="nofollow">http://jsfiddle.net/TcGGZ/30/</a></p>
<pre><code>$('#account_get').click(function(){
$.getJSON('http://graph.facebook.com/'+$('#facebook').val(), function(fd) {
$('#id').val(fd.id);
$('#name').val(fd.name);
$('#first_name').val(fd.first_name);
$('#last_name').val(fd.last_name);
$('#link').val(fd.link);
$('#username').val(fd.username);
$('#gender').val(fd.gender);
$('#locale').val(fd.locale);
});
});
</code></pre>
<p>This is the second one I am trying to decide about. <a href="http://jsfiddle.net/VuY2b/46/" rel="nofollow">http://jsfiddle.net/VuY2b/46/</a></p>
<pre><code>var facebook_account = '';
function fillForm() {
facebook_account = $('#facebook').val();
$.getJSON('http://graph.facebook.com/' + facebook_account, function(data) {
var facebook_data = data;
console.log(facebook_data);
var inputs = $('form > input');
for (var key in facebook_data) {
for (var l = 0; l < inputs.length; l++) {
if (inputs[l].getAttribute('name') === key) {
inputs[l].value = facebook_data[key];
}
}
}
});
}
var x = document.getElementById('account_get');
x.addEventListener("click", fillForm, false);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T14:36:53.047",
"Id": "29976",
"Score": "0",
"body": "On the second one, I would consider to do it reversed: for each input, if `facebook_data[input.getAttribute('name')]` has anything, then fill in the input."
}
] |
[
{
"body": "<p>The first one will be slow because of all the jQuery selection.</p>\n\n<p>The second one will be slow because of the two loops. It keeps looping over what was already found. BUT it is going to be faster than the first one.</p>\n\n<p>I made a basic jSPerf with a basic object: <a href=\"http://jsperf.com/some-random-beef\">http://jsperf.com/some-random-beef</a></p>\n\n<p>I also added two more cases to show you faster ways. NOW, if the object contains more junk in it, the results may differ.</p>\n\n<pre><code>var inputs = document.forms[0];\nfor (var key in fd) {\n var elem = inputs[key];\n if (elem) {\n elem.value = fd[key];\n } \n}\n</code></pre>\n\n<p>Now what version of the code would I want to read? The first one. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T08:15:12.337",
"Id": "29681",
"Score": "0",
"body": "Isn't getting an element by ID really fast on any browser from the past 5 years?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T15:31:47.867",
"Id": "29707",
"Score": "1",
"body": "this is just a snippet of what going in to the project, you should really consider the fact that the final form is gonna be pretty huge, we are collecting lots of data from multiple social media sites. The first choice might look better, and using document.getElementById might be faster, but in the end to write out a line of code for every single form element that needs to be filled would be less pleasant to look at then a loop that matches attribute names and fills in data when a match is found"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T21:04:40.670",
"Id": "18633",
"ParentId": "18631",
"Score": "5"
}
},
{
"body": "<p>The first one is very readable but is hard coded to specific ids and fields. This increases support costs. The ids of the html elements have a potential name conflict with any other forms you may add.</p>\n\n<p>The second is harder to read but will adapt to changes in the model without changing JS. It also avoids the chance of id conflicts. This code also uses dom functions, so it doesn't give you the compatibility advantage afforded by jQuery.</p>\n\n<p>you should probably abstract your automapper to its own utility class. That way you end up with the following:</p>\n\n<pre><code>var getFacebookData = function() {\n var path = 'http://graph.facebook.com/'+$('#facebook').val();\n var inputElements = $('form > input');\n $.getJSON(path, function(facebookData) { Utility.dataMapper( facebookData, inputElements )});\n };\n\n$('#account_get').click( getFacebookData );\n</code></pre>\n\n<p>And add this to your utility class:</p>\n\n<pre><code>//General purpose method for copying a hash to corresponding input elements.\nUtility.prototype.dataMapper = function( hash, elementList )\n{\n for (var key in hash) {\n for (var l = 0; l < elementList.length; l++) {\n if (elementList[l].getAttribute('name') === key) {\n elementList[l].value = hash[key];\n }\n }\n }\n\n}\n</code></pre>\n\n<p>I do alot of datamapping so something like dataMapper() can be re-used frequently. For UI operations you usually don't need to worry about performance as the time between user clicks or ajax requests is large compared to the time to copy over fields. the focus should be on readability and code support.</p>\n\n<p>It is wise to use the name attribute to denote the field as you did with the name attribute. You can also use class attrivute for nicer looking jQuery searches, but it is much slower. </p>\n\n<p>If you want to get the performance gains of epascarello's method, with the added performance gain of having the data mapper predefined in a utility library and have good looking concise code you can do this.</p>\n\n<pre><code>//Put dataMapper into your utility library.\nUtility = {};\nUtility.dataMapper = function(hash, elementList) {\n for (var key in hash){\n var element = elementList[key]; \n if ( element ) element.value = hash[key];\n }\n}\n//use this in your initialization code\nvar getFacebookData = function() {\n var path = 'http://graph.facebook.com/'+$('#facebook').val();\n var inputElements = document.forms[0];\n $.getJSON(path, function(facebookData) { Utility.dataMapper( facebookData, inputElements )});\n };\n\n$('#account_get').click( getFacebookData );\n</code></pre>\n\n<p>I benchmarked this on epascarello JSPerf - <a href=\"http://jsperf.com/some-random-beef/8\" rel=\"nofollow\">http://jsperf.com/some-random-beef/8</a> and it increased performance a slight amount from the grim reaper method I mostly copied. I think a combination of his performance increase and the concise code of this example would be your best bet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T13:06:59.093",
"Id": "18791",
"ParentId": "18631",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T20:30:11.870",
"Id": "18631",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"facebook"
],
"Title": "Javascript coding wager"
}
|
18631
|
<blockquote>
<p>Given an array of words, print all anagrams together. For example, if
the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output
may be “cat tac act dog god”.</p>
</blockquote>
<p>My idea is to sort individual words firstly. And then sort the array of words.
In this way, the anagrams will be together. The following is my code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct word_with_ind
{
char* word;
int ind;
}*word_with_ind_ptr;
int comp_char(const void* x, const void* y)
{
char* c1 = (char*)x;
char* c2 = (char*)y;
return *c1 - *c2;
}
int comp_str(const void* x, const void* y)
{
const word_with_ind_ptr w1 = (word_with_ind_ptr)x;
const word_with_ind_ptr w2 = (word_with_ind_ptr)y;
return strcmp(w1->word, w2->word);
}
void destroy(word_with_ind_ptr x, int size)
{
for(int i = 0; i < size; ++i)
{
free(x[i].word);
}
free(x);
}
void print_anagrams_together(char* word[], int size)
{
//make a copy of the original word array. And sort
//the individual words
word_with_ind_ptr x = (word_with_ind_ptr)malloc(sizeof(struct word_with_ind)*size);
for(int i = 0; i < size; ++i)
{
x[i].ind = i;
x[i].word = (char*)malloc(sizeof(char)*(strlen(word[i])+1));
strcpy(x[i].word, word[i]);
qsort(x[i].word, strlen(x[i].word), sizeof(char), comp_char);
}
//sort the array of words
qsort(x, size, sizeof(struct word_with_ind), comp_str);
//print result
for(int i = 0; i < size; ++i)
{
printf("%s\n", word[x[i].ind]);
}
//free memory
destroy(x, size);
}
int main()
{
char* word[] = {"cat", "dog", "tac", "god", "act"};
int size = sizeof(word)/sizeof(word[0]);
print_anagrams_together(word, size);
getchar();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>FiHopZz, your concept seems fine. A few comments:</p>\n\n<ul>\n<li><p>in general, don't typedef pointers. It is confusing.</p></li>\n<li><p>your functions are not const-correct. In other words they cast const values\nto non-const values. The compiler will warn you of this if you enable\nwarnings.</p></li>\n<li><p>I prefer pointers to be declared like this: <code>char *p</code>, not <code>char* p</code>.\nConsider <code>char* a, b</code> if in doubt (<code>b</code> is not a pointer but looks as if it\nshould be).</p></li>\n<li><p>all local functions should be declared <code>static</code></p></li>\n<li><p>print_anagrams_together should take a const word array and a size_t size\n(<code>destroy</code> should also take <code>size_t</code> not <code>int</code>)</p></li>\n<li><p>don't cast the return from <code>malloc</code> and note that malloc can fail.</p></li>\n<li><p>sizeof(char) is 1 by definition.</p></li>\n<li><p>use <code>strdup</code> to copy a word, not malloc. strdup can also fail.</p></li>\n<li><p>you took the length of the string twice, once in the <code>malloc</code> call and once\nin the <code>qsort</code> call.</p></li>\n<li><p>you also used <code>strcpy</code> on a string of which you already knew the\nlength. <code>memcpy</code> is better (but remember to copy length+1).</p></li>\n<li><p>print_anagrams_together is arguably better broken into several\nsub-functions: <code>copy_words</code>, <code>sort_words</code>, <code>print_words</code>. Well done for making\n<code>destroy</code> as function. This would be renamed <code>destroy_words</code> for symmetry.</p></li>\n<li><p>arguably, <code>copy_words</code> and <code>sort_words</code> above could be combined. This is how\nyour loop is written, with a word copied and then sorted in the same loop.\nThis is clearly slightly more efficient, but in some way it does not appeal\nto me. For a start what do you call it? - <code>copy_and_sort_words</code> is rather\nugly. But also a copy_words that just duplicates the array is easily tested;\none that duplicates it <strong>and</strong> modifies it is not. These are perhaps not\nconsiderations that belong to a simple program such as this, but they are\nworth beaaring in mind for more complicated tasks.</p></li>\n<li><p>comments should be useful. Yours are mainly noise. If nothing needs\nsaying, say nothing.</p></li>\n<li><p>the <code>word</code> array in <code>main</code> should be <code>const</code></p></li>\n<li><p>the <code>size</code> in <code>main</code> should be <code>const size_t</code>, not <code>int</code></p></li>\n<li><p><code>main</code> should have a parameter list</p></li>\n</ul>\n\n<p>Don't take my comments on breaking your <code>print_anagrams_together</code> into separate\nfunctions too seriously. It is not a big function and it is easily understood.\nBreaking it apart would probably make the program worse. However, for bigger\nor more complicated applications, having several loops in the same function\nin my opinion often indicates a lack of proper subdivision. Just my opinion\nthough and others may differ.</p>\n\n<p>Note also that although I say that malloc/strdup can fail, they are of course\nunlikely to fail in a small program like this. You might say that it is\npointless testing for NULL pointers when you know they will probably be okay.\nThe only thing you can sensibly do is to print an error and exit anyway\n(<code>perror(\"malloc\"); exit(EXIT_FAILURE);</code>). But it is a good discipline always\nto check the return values of functions that can fail. Just do it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T06:03:03.273",
"Id": "29678",
"Score": "0",
"body": "Another issue - don't bother to allocate memory on the heap, if you release it in scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T14:31:27.717",
"Id": "29701",
"Score": "1",
"body": "Good comments. Just a few things: \"`I prefer pointers to be declared like this: char *p, not char* p`\". This is subjective coding style, you cannot easily say that one form is better than the other. \"`use strdup`\", I disagree, strdup is not standard C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T14:44:12.840",
"Id": "29702",
"Score": "0",
"body": "That is why I said \"I prefer\" rather than \"you should\" :-) On `strdup`, really? The OP had three issues with his use of `malloc` to copy a single string and that is not uncommon. Can it really be preferable to `strdup`, standard or not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T02:01:53.280",
"Id": "29753",
"Score": "0",
"body": "@avip, In the function `print_anagrams_together`, If I don't use `malloc` to allocate memory, how should I do? You can't allocate memory statically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T04:40:02.240",
"Id": "29762",
"Score": "0",
"body": "@FihopZz: My apologies, I got too used to c99."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T04:25:15.480",
"Id": "18641",
"ParentId": "18640",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T01:57:23.680",
"Id": "18640",
"Score": "1",
"Tags": [
"c",
"algorithm",
"strings",
"interview-questions"
],
"Title": "Given a sequence of words, print all anagrams together"
}
|
18640
|
<pre><code>start:
try
{
oleDbDataAdapter1.Fill(myDataTable);
}
catch (Exception ex) {
DialogResult res = MessageBox.Show("Can't load data:\n" + ex.Message, "Error",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
if (res == DialogResult.Retry)
{
goto start;
}
}
</code></pre>
<ol>
<li>Is it ok to use <code>goto</code> operators, which lead outside a <code>try</code>/<code>catch</code> block? What consequences may it lead to?</li>
<li>How can I make this code better?</li>
</ol>
|
[] |
[
{
"body": "<p>I'm personally not a fan of goto's and to be honest I don't even know if I've ever used on in c#. I tend to find they are a bit hard to follow as you have to jump around a bit too much and the natural flow of the code is potentially broken. </p>\n\n<p>Here's an idea for using a different approach (Updated as suggested by <a href=\"https://codereview.stackexchange.com/users/2041/svick\">svick</a>)</p>\n\n<pre><code>string errorMessage;\nwhile(!TryTableFill(myDataTable, out errorMessage))\n{\n DialogResult result = MessageBox.Show(\"Can't load data:\\n\" + errorMessage, \"Error\", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);\n\n if(result != DialogResult.Retry)\n break;\n}\n\nprivate boolean TryTableFill(myDataTable, out string errorMessage)\n{\n errorMessage = string.Empty;\n\n try\n {\n oleDbDataAdapter1.Fill(myDataTable);\n return true; \n }\n catch (Exception ex) { \n errorMessage = ex.Message;\n return false;\n } \n}\n</code></pre>\n\n<p>or alternatively (I like this way but I'm not sure if it's better. Added just to provide an alternative):</p>\n\n<pre><code>private boolean TryTableFill(myDataTable, out string errorMessage)\n{\n errorMessage = string.Empty;\n\n try\n {\n oleDbDataAdapter1.Fill(myDataTable);\n }\n catch (Exception ex) { \n errorMessage = string.Format(\"Error occured: {0}\", ex.Message);\n } \n\n return !string.isNullOrEmpty(errorMessage);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T01:33:16.673",
"Id": "29749",
"Score": "0",
"body": "Are you sure it's a good idea to rely on the fact that a `Message` of an exception won't be `null` or empty? I think using multiple `return` statements (one in `try`, one in `catch`) would be a better solution here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T01:59:16.960",
"Id": "29752",
"Score": "0",
"body": "@svick valid point. I've updated answer to reflect this. cheers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T15:15:06.487",
"Id": "29861",
"Score": "0",
"body": "How about limiting the number of attempts? Also, sometimes you should capitalize the s in `String`. Run StyleCop on your code and you will see."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:20:04.850",
"Id": "29870",
"Score": "0",
"body": "@Leonid Fair point. I think it's more of a style (team) preference though so might leave that to the OP to decide. Check this out http://stackoverflow.com/questions/263191/in-c-should-i-use-string-empty-or-string-empty-or. I tend to listen to his suggestions. As for limiting requests. Another good point that the OP can look into if required."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:26:59.483",
"Id": "29903",
"Score": "0",
"body": "Oh how I abhor `string.Empty`. `\"\"` is *so* much shorter and not a jot less clear. But in general, this is a very clean implementation. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T09:22:01.523",
"Id": "29959",
"Score": "0",
"body": "@Leonid \"sometimes\", such as? Do you mean `String.Empty`? (abhor++)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T07:51:47.150",
"Id": "18647",
"ParentId": "18643",
"Score": "32"
}
},
{
"body": "<p>You can also use recursion to avoid the goto in this case. Wrap the code in a method and let the method call itself instead of using goto.</p>\n\n<p><strong>Warning:</strong> Recursion can lead to a stack overflow. It's no problem here as long as the user doesn't click \"Retry\" too often, but when you remove the dialog the code becomes dangerous. Using an iterative solution (including the <code>goto</code> solution) doesn't have that drawback.</p>\n\n<pre><code>private void TableFill(myDataTable)\n{\n try\n {\n oleDbDataAdapter1.Fill(myDataTable);\n }\n catch (Exception ex) {\n DialogResult res = MessageBox.Show(\"Can't load data:\\n\" + ex.Message, \"Error\",\n MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);\n if (res == DialogResult.Retry)\n {\n TableFill(myDataTable);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T08:31:50.080",
"Id": "29682",
"Score": "2",
"body": "Recursion would be a different approach. Fancy sharing the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T10:08:16.807",
"Id": "29687",
"Score": "0",
"body": "I added some sample code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T13:34:36.237",
"Id": "29696",
"Score": "3",
"body": "Recursion is a dangerous option here. If the problem is persistent you could end up with a stack overflow from repeated attempts. It's not likely in the current form with a user prompt between each cycle; but you're creating a bomb that will be armed when a maintenance developer either replaces the prompt with an automatic retry, or uses this code as a template for an option that never has UI interaction, but doesn't otherwise change the implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T14:51:26.193",
"Id": "29703",
"Score": "0",
"body": "@DanNeely That's true, recursion should always be used with care. It's still a working solution in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T17:31:25.660",
"Id": "29724",
"Score": "0",
"body": "Sorry, I felt I had to downvote as this is a very dangerous answer that can result in a stack overflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T22:54:24.877",
"Id": "29743",
"Score": "2",
"body": "I understand the downvote(s), but the code is still perfectly fine in a simple situation. I added a warning to my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T15:16:12.880",
"Id": "29862",
"Score": "3",
"body": "Good answer. One thing I would add is a number of retries parameter and deal with them tail-recursively."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T08:17:28.413",
"Id": "18648",
"ParentId": "18643",
"Score": "8"
}
},
{
"body": "<p>Do not use <code>goto</code> as it is a clear sign of what is called spaghetti code. @dreza has provided a much better solution. You routines should be tightly cohesive, meaning they do one thing and they do it well. Only wrap calls in <code>try</code>/<code>catch</code> if the call might throw an exception, then handle the exception and continue execution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T09:28:28.897",
"Id": "29685",
"Score": "3",
"body": "What about using goto inside switch, or to [`get out of deeply nested loops`](http://msdn.microsoft.com/en-us/library/13940fs2%28v=vs.71%29.aspx), is it also spaghetti code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T11:12:59.443",
"Id": "29689",
"Score": "3",
"body": "@ANeves +1 Using a goto once for a specific situation is \"ok\", but I personally try to find other solutions (exceptions, recursion, refactoring, etc.) first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T17:25:19.780",
"Id": "29722",
"Score": "4",
"body": "@ANeves - `goto case` is a perfectly legitimate use of `goto`. Getting out of a deep loop should be refactored so that you can use a return statement instead, if possible."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T08:34:13.947",
"Id": "18650",
"ParentId": "18643",
"Score": "3"
}
},
{
"body": "<p>You probably want to use some form of asynchronous callback to call the method after its ended. It has been a year or so since I've programmed in C# and I've probably messed up the syntax, but you can use the Dispatcher to do this. You may need to use the Dispatcher appropriate to your UI framework (wpf, winforms, etc).</p>\n\n<pre><code>void myMethodName(myDataTable) \n{\n try { oleDbDataAdapter1.Fill(myDataTable); }\n catch (Exception ex) \n {\n DialogResult res = MessageBox.Show(\"Can't load data:\\n\" + ex.Message, \"Error\", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);\n if (res == DialogResult.Retry) \n Dispatcher.BeginInvoke(() => { myMethodName(myDataTable); }); // myMethodName will be called after the method ends.\n }\n}\n</code></pre>\n\n<p>This uses the dispatcher to schedule a myMethodName() to be called again after your current instance of myMethodName() has exited and other queued methods have executed. This should avoid any problems of a stackoverflow.</p>\n\n<p>Update:\nAnother way to do this, if you want to stay in the same method could be something like this. It is fairly concise and give the closest match to your current architecture. It does block which may or may not be desirable. </p>\n\n<pre><code>do \n{ \n DialogResult retry = null;\n try { oleDbDataAdapter1.Fill(myDataTable); }\n catch (Exception ex) { retry = MessageBox.Show(\"Can't load data:\\n\" + ex.Message, \"Error\", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); } \n\n} while (retry == DialogResult.Retry);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T15:18:35.807",
"Id": "29863",
"Score": "1",
"body": "This approach increases the level of complexity (volume of skull sweat required to reason about code that contains such a call) for such a simple problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T11:22:24.160",
"Id": "29898",
"Score": "0",
"body": "Asynchronous callbacks are considered very simple to experienced programmers. Novices should learn this pattern. It should be a standard part of a programmers tool box to increase code readability and decrease bugs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T09:33:42.790",
"Id": "29961",
"Score": "0",
"body": "(*\"and decrease bugs\"* would benefit from an example.) I don't like this approach, because if other methods rely on this method's side-effects this approach will bite the programmer's hand. But it's a nice tool to know, yes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T12:14:02.980",
"Id": "29968",
"Score": "1",
"body": "I think the classic bug it reduces is preventing recursion overflow in an automated retry situation. Using asynchronous calls also frees up other items to render between retries and does not block the UI. I can imagine a situation where a coder does an automated retry every second in a while loop, the code always raises an exception and the user never gets back control of the UI. I agree it could cause problems if following code depended on success. Though, any code depending on the table fill should be placed in the try block."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T12:55:29.883",
"Id": "18739",
"ParentId": "18643",
"Score": "2"
}
},
{
"body": "<p>I'm not a fan of the <code>TrySomething</code> with out parameter pattern, so I would sooner do the following:</p>\n\n<pre><code>while (true) {\n try {\n possiblyFailingOperation();\n break;\n }\n catch (Exception e) {\n reportError();\n if (abortRequested())\n throw;\n }\n}\n</code></pre>\n\n<p>A <code>TrySomething</code> function makes sense when there's several places that call the same exception-throwing function and they all want to immediately catch and handle a single kind of exception said function may throw. For example, <code>TryParse</code> often makes sense as parsing may be common and may have only one failure state (no parse). It makes sense to do</p>\n\n<pre><code>if (!TryParse(x, out i))\n i = default_value;\n</code></pre>\n\n<p>When there's only one function that calls the <code>TrySomething</code> function, the added benefit is significantly less; we end up obscuring what exception is thrown and losing the ability to rethrow if necessary.</p>\n\n<p>If this is all insignificant, a try function may be worthwhile; however, I'd use it in reaction to a common pattern, not in anticipation of one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T09:25:10.767",
"Id": "29960",
"Score": "0",
"body": "*\"I'm not a fan of the TrySomething with out parameter pattern\"*: **why not?** If `DoSomething` returns void, why should `TryDoSomething` need any out parameter? A concrete example: `TrySendEmail(to, message)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T10:27:02.863",
"Id": "29962",
"Score": "0",
"body": "@ANeves: I've updated the answer to explain my reasoning."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T13:16:51.903",
"Id": "18764",
"ParentId": "18643",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18647",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T06:04:38.557",
"Id": "18643",
"Score": "17",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Is it ok to use goto in catch?"
}
|
18643
|
<p>Here is a problem from the book <em>Programming Challenges</em> by Skiena and Revilla:</p>
<blockquote>
<p><strong>The Trip</strong></p>
<p>A number of students are members of a club that travels annually to
exotic locations. Their destinations in the past have included
Indianapolis, Phoenix, Nashville, Philadelphia, San Jose, and Atlanta.
This spring they are planning a trip to Eindhoven. The group agrees in
advance to share expenses equally, but it is not practical to have
them share every expense as it occurs. So individuals in the group pay
for particular things, like meals, hotels, taxi rides, plane tickets,
etc. After the trip, each student's expenses are tallied and money is
exchanged so that the net cost to each is the same, to within one
cent. In the past, this money exchange has been tedious and time
consuming. Your job is to compute, from a list of expenses, the
minimum amount of money that must change hands in order to equalize
(within a cent) all the students' costs.</p>
<p><strong>The Input</strong></p>
<p>Standard input will contain the information for several trips. The
information for each trip consists of a line containing a positive
integer, n, the number of students on the trip, followed by n lines of
input, each containing the amount, in dollars and cents, spent by a
student. There are no more than 1000 students and no student spent
more than $10,000.00. A single line containing 0 follows the
information for the last trip.</p>
<p><strong>The Output</strong></p>
<p>For each trip, output a line stating the total amount of money, in
dollars and cents, that must be exchanged to equalize the students'
costs.</p>
<p><strong>Sample Input</strong></p>
<pre><code>3
10.00
20.00
30.00
4
15.00
15.01
3.00
3.01
0
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>$10.00
$11.99
</code></pre>
</blockquote>
<p>Here is my solution which gives correct answer for all inputs I have tried so far, but there must be some case when it does not work because the judge says so. Can anybody help me to understand why?</p>
<pre><code>int main (int argc, char * argv[]) {
int64_t a;
float paid[1000];
std::vector<float> results;
while (std::cin >> a && a != 0) {
int sum = 0;
for (int i = 0; i < a; i++) {
std::cin >> paid[i];
paid[i] *= 100;
sum += paid[i];
}
int result = 0;
int avg = (std::ceil)((float)sum/a);
int mod = sum % a;
int c = 0;
if (mod > 0) {
for (int i = 0; i < a; i++) {
if (c >= a - mod)
break;
if (paid[i] < avg) {
paid[i]++;
c++;
}
}
for (int i = 0; i < a; i++) {
if (c >= a - mod)
break;
if (paid[i] > avg) {
paid[i] += a - mod - c;
break;
}
}
}
for (int i = 0; i < a; i++) {
if (paid[i] > avg) {
result += (paid[i] - avg);
}
}
results.push_back((float)result/100);
}
std::cout << std::fixed;
std::cout << std::setprecision(2);
for (std::vector<float>::iterator it = results.begin(); it != results.end(); ++it) {
std::cout << "$" << *it << std::endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T17:27:10.820",
"Id": "29723",
"Score": "0",
"body": "My C++ is very rusty, but I can suggest some possible test cases which might break it. What happens if one student doesn't have any expenses? More than one? What if one student pays for everything? What if the total bill is smaller than the number of students? Do you return 0 if everyone paid equal amounts? What about if everyone was within one cent of each other?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T20:50:13.547",
"Id": "29732",
"Score": "0",
"body": "@Bobson thanks for suggestion for the test cases. I tried but do not see any wrong solution: 10.01 0 -> $5.00 (2 students); 10.01 0 0 -> $6.67; 3.01 1.11 0 0 0 -> $2.46; 3.01 3.00 3.00 -> $0.00"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T21:59:47.197",
"Id": "29739",
"Score": "0",
"body": "What about `0 0 0 -> 0`? You might get a divide-by-zero error somewhere in that case. It's the only thing I can think of. Good luck!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T01:58:31.023",
"Id": "29751",
"Score": "0",
"body": "0 0 is not possible to input, the program exits when you input 0 students"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T14:28:54.000",
"Id": "29800",
"Score": "0",
"body": "Sorry, I meant `0.00 0.00 0.00 -> $0.00`."
}
] |
[
{
"body": "<p>Your algorithm seems to be correct though a bit overcomplicated.\nBut the code is not correct. consider:</p>\n\n<pre><code>9999.1\n9999.1\n9999.0\n9999.1\n\n$0.05\n</code></pre>\n\n<p>And the correct answer is $0.07</p>\n\n<p>This is due to lack of precision in float implementation. It does not mean you should use double, it mean you should check your casts and try to avoid using float at money computations at all.</p>\n\n<p>Also, i suggest to check your inputs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T12:13:57.100",
"Id": "18702",
"ParentId": "18652",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>Try not to use single-character variables (with the exception of loop counter variables, such as <code>i</code>). It makes it harder for others to read your code.</p></li>\n<li><p>This isn't quite ideal:</p>\n\n<blockquote>\n<pre><code>int avg = (std::ceil)((float)sum/a);\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/numeric/math/ceil\" rel=\"nofollow noreferrer\"><code>std::ceil</code>'s return type is actually a floating-point type</a> (can be either <code>float</code> or <code>double</code> depending on the overload). For an <code>int</code> value, you just need to have <code>sum / a</code>.</p></li>\n<li><p>You're mixing in some C features:</p>\n\n<p><strong>Casting</strong></p>\n\n<p>Instead of this C-style cast:</p>\n\n<blockquote>\n<pre><code>results.push_back((float)result/100);\n</code></pre>\n</blockquote>\n\n<p>use this C++-style cast:</p>\n\n<pre><code>results.push_back(static_cast<float>(result)/100);\n</code></pre>\n\n<p><strong>C-style arrays</strong></p>\n\n<p>You have this C-style array:</p>\n\n<blockquote>\n<pre><code>float paid[1000];\n</code></pre>\n</blockquote>\n\n<p>but you also use an <code>std::vector</code>. You can just use an <code>std::vector</code> for everything here, unless you may need a different storage container. If you have C++11, you can instead use an <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a> in place of static arrays.</p></li>\n<li><p>You don't need to keep flushing the buffer with <code>std::endl</code> in the last loop. You can instead output <code>\"\\n\"</code>, which will just give you a newline. This is explained in more detail <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">here</a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-15T18:21:57.220",
"Id": "86990",
"ParentId": "18652",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T09:05:35.973",
"Id": "18652",
"Score": "3",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "\"The Trip\" challenge from Programming Challenges"
}
|
18652
|
<p>I have a function in App Engine Java where I compare two patterns stored in an int array:</p>
<pre><code>public static int patternMatch(int [] pattern1, int [] pattern2, int range) {
int max = range * pattern1.length;
int match = (pattern1.length - pattern2.length) * range;
for(int i = 0; i < pattern2.length; i++) {
match += Math.abs(pattern1[i] - pattern2[i]);
}
return (max - match) * 100 / max;
}
</code></pre>
<p>I am facing very weird problems with respect to performance of this function between the development server and deployment on app engine as listed below:</p>
<ol>
<li>This function is called in a loop with the intention of finding best match(es).</li>
<li>Performance for a single iteration is critical as there are lot of iterations.</li>
<li>If I were to not have any logic in this code and directly return any integer, my overall code takes 100 ms to complete on an average.</li>
<li>The above code takes anywhere between 200 - 600 ms.</li>
<li><p>On the development server, if I replace</p>
<pre><code>int match = (pattern1.length - pattern2.length) * range;
</code></pre>
<p>by</p>
<pre><code>int match = Math.abs(pattern1.length - pattern2.length) * range;
</code></pre>
<p>somehow the performance improves bringing the time taken down to 200 - 300 ms only. No impact on deployment server.</p></li>
<li>If I remove <code>Math.abs</code>, the performance improves, bringing the average to 150 ms.</li>
<li>I tried replacing <code>Math.abs</code> with bit operations to derive absolute value. I see huge performance improvement on development server ~160 ms. On deployment server it makes things worse ~700 ms.</li>
</ol>
<p>What I would like to know here is:</p>
<ol>
<li>Why and how differently do Development server (Windows 7/eclipse/JDK6) and Deployment server behave in terms of performance tweaks?</li>
<li>Is there any better algorithm to the match?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T19:05:27.360",
"Id": "29727",
"Score": "0",
"body": "Maybe the development server runs in client mode while the deployment runs in client mode. http://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T05:42:52.080",
"Id": "29770",
"Score": "0",
"body": "Didn't get it. Your comment says both running in client mode. Either way if you meant one is running in client mode and another in server, then it should actually run faster on the server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T06:39:16.977",
"Id": "29773",
"Score": "0",
"body": "Did you check how much CPU/memory you get from App Engine? https://developers.google.com/appengine/docs/adminconsole/performancesettings"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T14:50:28.363",
"Id": "29801",
"Score": "0",
"body": "It would help to have more info. How many iterations? What is the range typically? How large are the arrays? Is pattern1 always the same? You might be overflowing an int if the range and iterations are both large for example. You also may be better unrolling the abs ( diff = b - a; match = (diff < 0) ? -diff : diff) if the compiler doesn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:52:20.273",
"Id": "29910",
"Score": "0",
"body": "Iterations are close to 20000 in one run. Range is < 100. Arrays are max 60 size. Pattern 1 in one run will be the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:53:24.793",
"Id": "29911",
"Score": "0",
"body": "CPU/Memory is of the free instance."
}
] |
[
{
"body": "<p>It's hard to say anything without profiling <em>the whole</em> application. Two possible scenarios about this point:</p>\n\n<blockquote>\n <p>If I were to not have any logic in this code and directly return any integer, my overall code takes 100 ms to complete on an average.</p>\n</blockquote>\n\n<h2>#1</h2>\n\n<p>I guess the application processes the output of <code>patternMatch</code>, so maybe it handles different results differently which varies in time. Consider the following example:</p>\n\n<pre><code>public static int patternMatch(int [] pattern1, int [] pattern2, int range) {\n return 5;\n}\n\nint result = patternMatch( [] pattern1, int [] pattern2, int range) {\nif (result < 10) {\n // do nothing\n} else {\n // do something complicated and slow\n}\n</code></pre>\n\n<p>Of course, it might not be so obvious. Profile it!</p>\n\n<h2>#2</h2>\n\n<p>JMV is smart about optimizations. If you put the simple <code>return 5</code> statement into the method (as above) the JVM might have fooled you and did not even call the <code>patternMatch</code> method and probably eliminated or optimized other codes too which call <code>patternMatch</code>.</p>\n\n<blockquote>\n <p>For example, reconsider the code in Listing 4: note \n that <code>main</code> not only computes <code>result</code> but also uses <code>result</code>\n in the output that it prints. Suppose that I make just\n one tiny change and remove <code>result</code> from the <code>println</code>. In \n this case, an aggressive compiler might conclude that it \n does not need to compute <code>result</code> at all. </p>\n</blockquote>\n\n<p>Source: <a href=\"http://www.ibm.com/developerworks/java/library/j-benchmark1/index.html\" rel=\"nofollow\">Robust Java benchmarking, Part 1: Issues</a></p>\n\n<hr>\n\n<p>I've created a test class for testing the runtime. It takes only 8,766 ms on my machine.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\nimport org.junit.Test;\n\nimport com.google.common.base.Stopwatch;\n\npublic class AppEngineCompareTest {\n\n private final Random random = new Random();\n\n @Test\n public void test() {\n final Stopwatch stopwatch = Stopwatch.createStarted();\n final int count = 20000;\n final int[] ranges = createRandomIntegerArray(count);\n final List<int[]> patternOneList = createPatterns(count);\n final List<int[]> patternTwoList = createPatterns(count);\n System.out.println(\"gen: \" + stopwatch);\n stopwatch.reset();\n stopwatch.start();\n int result = 0;\n for (int index = 0; index < count; index++) {\n final int[] pattern1 = patternOneList.get(index);\n final int[] pattern2 = patternTwoList.get(index);\n final int range = ranges[index];\n result += AppEngineCompare.patternMatch(pattern1, pattern2, range);\n }\n System.out.println(\"run: \" + stopwatch);\n System.out.println(result);\n }\n\n private int[] createRandomIntegerArray(final int count) {\n final int[] ranges = new int[count];\n for (int index = 0; index < count; index++) {\n ranges[index] = random.nextInt();\n }\n return ranges;\n }\n\n private List<int[]> createPatterns(final int count) {\n final List<int[]> result = new ArrayList<>(count);\n for (int index = 0; index < count; index++) {\n final int[] patterns = createRandomIntegerArray(60);\n result.add(patterns);\n }\n return result;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T11:47:12.780",
"Id": "43851",
"ParentId": "18653",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T09:06:26.807",
"Id": "18653",
"Score": "3",
"Tags": [
"java",
"performance",
"array",
"google-app-engine"
],
"Title": "Sum the difference of two arrays"
}
|
18653
|
<p>I've created a create a console app that would:</p>
<ol>
<li>Call a method to check an email account (I've done this step)</li>
<li>Convert the attachment to pdf (I've done this step)</li>
<li>Then once the conversion is complete wait 30 seconds</li>
<li>Repeat the previous 3 steps continuously</li>
</ol>
<p>I've done Step 1 and 2 int the ProcessMailMessages() method.
The following code works but I want to know if I am on the right track or is there a better way to poll a email client?</p>
<pre><code> private static int secondsToWait = 30 * 1000;
static void Main(string[] args)
{
bool run = true;
do
{
try
{
Task theTask = ProcessEmailTaskAsync();
theTask.Wait();
}
catch (Exception e)
{
Debug.WriteLine("<p>Error in Client</p> <p>Exception</p> <p>" + e.Message + "</p><p>" + e.StackTrace + "</p> ");
}
GC.Collect();
} while (run);
}
static async Task ProcessEmailTaskAsync()
{
var result = await EmailTaskAsync();
}
static async Task<int> EmailTaskAsync()
{
await ProcessMailMessages();
await Task.Delay(secondsToWait);
return 1;
}
static async Task ProcessMailMessages()
{
...............................................................................
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T16:50:51.000",
"Id": "29718",
"Score": "2",
"body": "Why are you calling `CG.Collect();`?"
}
] |
[
{
"body": "<p>I would rather do smth. like that (I added CancellationToken in case you would want to be able to cancel email parsing while it's in progress):</p>\n\n<pre><code>private static TimeSpan timeToWait = TimeSpan.FromSeconds(30);\n\n//somewhere in your code:\n_cancellationTokenSource = new CancellationTokenSource();\n\nprivate static void Main(string[] args)\n{\n CancellationToken token = _cancellationTokenSource.Token;\n do\n {\n try\n {\n ProcessEmailsAndWaitAsync(token).Wait();\n }\n catch (Exception e)\n {\n Debug.WriteLine(\"<p>Error in Client</p> <p>Exception</p> <p>\" + e.Message + \"</p><p>\" + e.StackTrace + \"</p> \");\n }\n } while (!token.IsCancellationRequested);\n}\n\nprivate static async Task ProcessEmailsAndWaitAsync(CancellationToken token)\n{\n await ProcessMailMessages(token);\n await Task.Delay(timeToWait, token);\n}\n\nprivate static async Task ProcessMailMessages(CancellationToken token)\n{\n //...............................................................................\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T14:29:31.807",
"Id": "18662",
"ParentId": "18654",
"Score": "1"
}
},
{
"body": "<p>I believe you could use a much more elegant solution using the ContineWith method on the Task object</p>\n\n<p>Here is some basic pseudo code...</p>\n\n<pre><code>function RecursiveEmailPollRoutine()\n{\n var PollEmailTask = new Task(() => {\n //Poll the email\n //Pause for your delay\n }).ContinueWith(()=> {\n //check your cancel var\n //and cancel if need be\n //otherwise recursively \n //call this function\n }).Start();\n)\n</code></pre>\n\n<p>This hasn't been tested but you get the gist. I hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T18:12:17.170",
"Id": "29725",
"Score": "4",
"body": "Please don't link to your blog in every (or any) answer. Linking to a specific blog post that's relevant to the question is fine as long as you summarize the content of the post in your answer, but just linking to your blog without any indication of how it's relevant to the question is against the rules."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T10:54:24.637",
"Id": "29855",
"Score": "2",
"body": "Are you seriously saying this code is more readable than using `async`-`await`? The whole point of that is to *avoid* code like this. Besides, your code won't work, because you can't `Start()` the `Task` returned from `ContinueWith()`. On the other hand, you have to `Start()` the `Task` if you create it directly using an constructor."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T16:07:09.033",
"Id": "18669",
"ParentId": "18654",
"Score": "-2"
}
},
{
"body": "<ol>\n<li>Calling <code>GC.Collect()</code> shouldn't be necessary except in very specific circumstances. Don't do it if you don't have a very good reason.</li>\n<li>Why are do you have unused local variable in <code>ProcessEmailTaskAsync()</code>? It's not useful for anything. What's more, what is the whole point of the method? You can <code>Wait()</code> on <code>Task<int></code> too.</li>\n<li>It's not clear what does the <code>int</code> returned from <code>EmailTaskAsync()</code> mean. If it's supposed to represent status, an <code>enum</code> would be much better. If you do need to use <code>int</code> for some reason, you really should document what each value means. And in your case, you always return the same value and it doesn't seem to be used anywhere, so you should just change the return type to <code>Task</code> and don't return anything.</li>\n<li><p>Using <code>async</code>-<code>await</code> won't give you any benefit in your case. Basically, there are two reasons for using <code>async</code>-<code>await</code>:</p>\n\n<ol>\n<li>It can use smaller number of threads, improving efficiency.</li>\n<li>It can avoid blocking the UI thread, improving responsiveness.</li>\n</ol>\n\n<p>Neither of those reasons is relevant in your case (you don't have a UI thread and using <code>async</code>-<code>await</code> this way will use more threads, not less, because of the <code>Wait()</code>), so you should consider whether using <code>async</code>-<code>await</code> will give you any benefit at all.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T05:50:53.460",
"Id": "29936",
"Score": "0",
"body": "Hi Svick,\nThanks for the constructive feedback, Are you able to provide an alternative implementation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T19:21:25.190",
"Id": "29991",
"Score": "0",
"body": "Why? Are any of my suggestions unclear?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T11:06:46.543",
"Id": "18734",
"ParentId": "18654",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "18662",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T09:23:25.333",
"Id": "18654",
"Score": "3",
"Tags": [
"c#",
"asynchronous"
],
"Title": "Polling a email using async / await"
}
|
18654
|
<p>I have the following concise-ish (and working) approach to getting all the forward permutations of a list of string. So with the list: </p>
<blockquote>
<p>w = ["Vehicula", "Sem", "Risus", "Tortor"]</p>
</blockquote>
<p>the results should be:</p>
<blockquote>
<p>['Vehicula', 'Vehicula Sem', 'Vehicula Sem Risus', 'Vehicula Sem Risus Tortor', 'Sem', 'Sem Risus', 'Sem Risus Tortor', 'Risus', 'Risus Tortor', 'Tortor']</p>
</blockquote>
<p>To do this, we loop through each element, and perform an inner loop that looks ahead and saves slices of the remaining elements to a result array. </p>
<pre><code>w = ["Vehicula", "Sem", "Risus", "Tortor"]
results = []
i = 0
l = len(w)
while i < l:
j, k = i, i + 1
while k <= l:
results.append(" ".join(w[j:k]))
k = k + 1
i = i + 1
print results
</code></pre>
<p>With Python, I always feel like I'm missing a trick, so I'm curios to see if there are any native Python functions that will make this more efficient? </p>
<p><strong>Edit</strong></p>
<p>I tested all three with <code>timeit</code> and mine is definitely the slowest. I've got to get to grips with <code>itertools</code> - it is very powerful. </p>
<pre><code>Verbose (Mine): 3.61756896973
Comprehensions: 3.02565908432
Itertools: 2.83112883568
</code></pre>
|
[] |
[
{
"body": "<p>This should work. I don't know if it is more readable than your approach though.</p>\n\n<pre><code>w = [\"Vehicula\", \"Sem\", \"Risus\", \"Tortor\"]\nresults = [' '.join(w[i:i+j+1]) for i in range(len(w)) for j in range(len(w)-i)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T13:04:19.827",
"Id": "18658",
"ParentId": "18656",
"Score": "1"
}
},
{
"body": "<p>Here's an alternative approach using <a href=\"http://docs.python.org/2/library/itertools.html#itertools.combinations\"><code>itertools.combinations</code></a> to generate the (start, end) pairs:</p>\n\n<pre><code>from itertools import combinations\nw = \"Vehicula Sem Risus Tortor\".split()\nresults = [' '.join(w[i:j]) for i, j in combinations(range(len(w) + 1), 2)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T13:18:20.143",
"Id": "18659",
"ParentId": "18656",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18659",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T12:50:35.500",
"Id": "18656",
"Score": "3",
"Tags": [
"python",
"algorithm",
"combinatorics"
],
"Title": "Getting all (forward) permutations of a list of strings"
}
|
18656
|
<p>I have a <code>Customer</code> class:</p>
<pre><code>public class Customer
{
public Guid Id { get; set; }
// Some other properties...}
</code></pre>
<p>And three transactions classes that have a reference to <code>Customer</code>: </p>
<pre><code>public class Order
{
public Guid CustomerId { get; set; }
// Some other properties...}
public class Invoice
{
public Guid CustomerId { get; set; }
// Some other properties...}
public class Payment
{
public Guid CustomerId { get; set; }
// Some other properties...}
</code></pre>
<p>I have a collection for each of transaction type. And I want to get this collection to be "grouped" by their elements <code>CustomerId</code> properties. So, as a result I'd like to get a collection of such objects:</p>
<pre><code>public class CustomerInfo
{
public CustomerInfo(Guid customerId, IEnumerable<Order> orders,
IEnumerable<Invoice> invoices, IEnumerable<Payment> payments){...}
public Guid CustomerId { get; set; }
public IEnumerable<Invoice> Invoices { get; set; }
public IEnumerable<Order> Orders { get; set; }
public IEnumerable<Payment> Payments { get; set; }
}
</code></pre>
<p>Right now I am doing so by this function:</p>
<pre><code>private IEnumerable<CustomerInfo> _GetCustomerInfo(
IEnumerable<Payment> payments, IEnumerable<Invoice> invoices,
IEnumerable<Order> orders)
{
var invoicesGroupdByCustomers = invoices.GroupBy(x => x.CustomerId);
var ordersGroupdByCustomers = orders.GroupBy(x => x.CustomerId);
var paymentsGroupdByCustomers = payments.GroupBy(x => x.CustomerId);
var result = new List<CustomerInfo>();
foreach (var group in invoicesGroupdByCustomers)
result.Add(new CustomerInfo(group.Key,
ordersGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
group,
paymentsGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key)));
foreach (var group in ordersGroupdByCustomers)
if (!result.Any(x => x.CustomerId == group.Key))
result.Add(new CustomerInfo(group.Key,
group,
invoicesGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
paymentsGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key)));
foreach (var group in paymentsGroupdByCustomers)
if (!result.Any(x => x.CustomerId == group.Key))
result.Add(new CustomerInfo(group.Key,
ordersGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
invoicesGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
group));
return result;
}
</code></pre>
<p>Here is sample of calculations where I use these transactions collections:</p>
<pre><code>private Dictionary<Guid, decimal> _CalculateSales(
IEnumerable<CustomerInfo> customersSalesInfo)
{
var result = new Dictionary<Guid, decimal>();
foreach (var customerInfo in customersSalesInfo)
{
var sales = customerInfo.Invoices.Sum(x => x.Header.SubTotalAmt) +
customerInfo.Orders.Sum(x => x.Header.SubTotalAmt) -
customerInfo.Payments.Sum(x => x.Header.SubTotalAmt);
result.Add(customerInfo.CustomerId, sales);
}
return result;
}
</code></pre>
<p>Is there a better approach?</p>
|
[] |
[
{
"body": "<p>If they all implemented a common interface then you could simplify it.</p>\n\n<pre><code> public interface ICustomerItem\n {\n Guid CustomerId {get;}\n }\n</code></pre>\n\n<p>Concat the the items together</p>\n\n<pre><code>var items = invoices.Concat(payments).Concat(orders);\n</code></pre>\n\n<p>Then project them into your class</p>\n\n<pre><code> items\n.GroupBy(x => x.CustomerId)\n.Select(g => \n new CustomerInfo(g.Key, \n g.OfType<Order>(), \n g.OfType<Payment>(),\n g.OfType<Invoice>())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T14:25:11.100",
"Id": "29700",
"Score": "0",
"body": "Thanks for \"Concat\", I've forgot about it. But in my case these classes aren't implementing common interface(in fact, they are implementing, but there is no such property as \"CustomerId\"). And these classes are from 3d party dll, which I couldn't change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T15:22:17.627",
"Id": "29705",
"Score": "0",
"body": "You could use DLINQ or create a wrapper classes for each item that implements the interface. i.e. OrderWrapper, PaymentWrapper and InvoiceWrapper. When you concat them, first project each item into the wrapper."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T13:49:11.047",
"Id": "18660",
"ParentId": "18657",
"Score": "6"
}
},
{
"body": "<p>You could take your original approach and use .ToList()</p>\n\n<pre><code>var invoicesGroupdByCustomers = invoices.GroupBy(x => x.CustomerId).ToList();\nvar ordersGroupdByCustomers = orders.GroupBy(x => x.CustomerId).ToList();\nvar paymentsGroupdByCustomers = payments.GroupBy(x => x.CustomerId).ToList();\n</code></pre>\n\n<p>Just another option to be aware of. I hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T18:24:21.913",
"Id": "29726",
"Score": "2",
"body": "-1. How is this helpful? What does it improve? How could this be used to make the original code better? That said, please don't get upset with the downvotes, it's a natural and neutral thing... we value your participation, welcome to the community!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T15:57:46.660",
"Id": "18668",
"ParentId": "18657",
"Score": "-2"
}
},
{
"body": "<p>Maybe I'm missing something but it seems that your code have strange behavior. If orders and payments collections have items with same CustomerId as in invoices collection then by checking</p>\n\n<blockquote>\n <p>if (!result.Any(x => x.CustomerId == group.Key))</p>\n</blockquote>\n\n<p>you will lose all of them and result collection will contain one CustomerInfo element per customer with some invoices and orders == null, payments == null.</p>\n\n<p>If this behavior is ok I would recommend using Dictionary to avoid multiple list scanning with Any()</p>\n\n<pre><code>private IEnumerable<CustomerInfo> _GetCustomerInfo(\n IEnumerable<Payment> payments,\n IEnumerable<Invoice> invoices,\n IEnumerable<Order> orders)\n {\n if (payments == null) throw new ArgumentNullException(\"payments\");\n if (invoices == null) throw new ArgumentNullException(\"invoices\");\n if (orders == null) throw new ArgumentNullException(\"orders\");\n\n var invoicesGroupdByCustomers = invoices.GroupBy(x => x.CustomerId);\n var ordersGroupdByCustomers = orders.GroupBy(x => x.CustomerId);\n var paymentsGroupdByCustomers = payments.GroupBy(x => x.CustomerId);\n\n var result = new Dictionary<Guid, CustomerInfo>();\n foreach (var group in invoicesGroupdByCustomers)\n result.Add(group.Key, new CustomerInfo(group.Key, null, group, null));\n\n foreach (var group in ordersGroupdByCustomers)\n if (!result.ContainsKey(group.Key))\n result.Add(group.Key, new CustomerInfo(group.Key, group, null, null));\n\n foreach (var group in paymentsGroupdByCustomers)\n if (!result.ContainsKey(group.Key))\n result.Add(group.Key, new CustomerInfo(group.Key, null, null, group));\n\n return result.Values;\n }\n</code></pre>\n\n<p>Hope this helps</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T05:27:41.023",
"Id": "29766",
"Score": "0",
"body": "Thanks for pointing out my error. Nope thats not what I want, I've fixed code in question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T08:54:46.263",
"Id": "29783",
"Score": "0",
"body": "-1: so instead of losing orders and payments for customer that have invoices (and payments for customers that already have orders), you make the code throw an exception on the `.Add()` method? That hardly seems an improvement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T21:04:21.667",
"Id": "18677",
"ParentId": "18657",
"Score": "0"
}
},
{
"body": "<p>If you're developing a production solution I would rather think how to avoid loading all the customers/invoices/etc at first place. If that's the case then please describe the use cases in which <code>Customerinfo</code> is going to be used, how do you get invoices/orders/payments collections, and is there a chance to leverage ORM capabilities (assuming that you get the data via some sort of ORM) to load these collections for customers?</p>\n\n<p>But if we are just talking about programming exercise then I would probably go with the following solution (influenced by RavenDB's map/reduce approach):</p>\n\n<pre><code>IEnumerable<CustomerInfo> infos = (\n from invoice in invoices\n select new { invoice.CustomerId, Invoice = invoice, Order = null, Payment = null }\n ).Concat(\n from order in orders\n select new { order.CustomerId, Invoice = null, Order = order, Payment = null }\n ).Concat(\n from payment in payments\n select new { payment.CustomerId, Invoice = null, Order = null, Payment = payment }\n ).GroupBy(x=>x.CustomerId, (key, group) => new CustomerInfo(key, \n group.Select(x => x.Invoice).Where(i => i != null),\n group.Select(x => x.Order).Where(o => o != null),\n group.Select(x => x.Payment).Where(p => p != null));\n</code></pre>\n\n<p>I can't test this code right now, you might have to explicitly specify types in anonymous objects.</p>\n\n<p><strong>Update</strong>:\nBased on your usage of <code>CustomerInfo</code> you might not actually need it at all (if that's all you do with it) :). I would rather try to reduce the amount of data straight away, thus improving performance and reducing memory usage:</p>\n\n<pre><code>private Dictionary<Guid, decimal> _CalculateSales(\n IEnumerable<Payment> payments, IEnumerable<Invoice> invoices,\n IEnumerable<Order> orders)\n{\n var result = (\n from invoice in invoices\n select new { invoice.CustomerId, Amount = invoice.Header.SubTotalAmt}\n ).Concat(\n from order in orders\n select new { order.CustomerId, Amount = order.Header.SubTotalAmt}\n ).Concat(\n from payment in payments\n select new { payment.CustomerId, Amount = -payment.Header.SubTotalAmt}\n ).GroupBy(x => x.CustomerId)\n .ToDictionary(g => g.Key, g => g.Sum(x => x.Amount));\n return result;\n}\n</code></pre>\n\n<p>The benefit of this solution comparing to original code is that it iterates over collections only once, and the only <code>Dictionary</code> created is the actual result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T05:33:57.187",
"Id": "29767",
"Score": "0",
"body": "I really need to load all transactions. The task is to calculate sales for all customer for some period of time. So, first I'd get list of all transactions for this time, then to group them by customer, then calculate sales for each customer. \nThanks for nice code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T05:42:40.350",
"Id": "29769",
"Score": "0",
"body": "In this case I would rather use DB capabilities to groups transactions by CustomerId, unless you are doing some complex calculations there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T05:48:02.443",
"Id": "29771",
"Score": "0",
"body": "Can you provide a sample of calculations you're doing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T06:16:10.533",
"Id": "29772",
"Score": "0",
"body": "problem is that I am getting transaction not from DB, but from really dumb web service, it can't do grouping.\nI've updated question with a sample of calculations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T06:44:52.010",
"Id": "29774",
"Score": "0",
"body": "I've updated my response according to your update"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:51:40.170",
"Id": "29952",
"Score": "0",
"body": "Thanks a lot for such solution. As soon as number of transaction can be really big, it can save a lot of time. \nI'll compare it with svick's code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T21:17:00.673",
"Id": "18678",
"ParentId": "18657",
"Score": "2"
}
},
{
"body": "<p>I think a better way would be to extract all of the ids first and then create your result based on that:</p>\n\n<pre><code>private IEnumerable<CustomerInfo> GetCustomerInfo(\n IEnumerable<Payment> payments, IEnumerable<Invoice> invoices,\n IEnumerable<Order> orders)\n{\n // if the parameters were ILists, this wouldn't be necessary\n payments = payments.ToArray();\n invoices = invoices.ToArray();\n orders = orders.ToArray();\n\n var customerIds = payments.Select(p => p.CustomerId)\n .Concat(invoices.Select(i => i.CustomerId))\n .Concat(orders.Select(o => o.CustomerId))\n .Distinct()\n .ToArray();\n\n // using ToLookup() means we can efficiently retrieve items based on id\n var paymentsLookup = payments.ToLookup(p => p.CustomerId);\n var invoicesLookup = invoices.ToLookup(i => i.CustomerId);\n var ordersLookup = orders.ToLookup(o => o.CustomerId);\n\n return customerIds.Select(\n id => new CustomerInfo(id, ordersLookup[id], invoicesLookup[id], paymentsLookup[id]));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T11:33:29.300",
"Id": "18735",
"ParentId": "18657",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18678",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T13:03:51.857",
"Id": "18657",
"Score": "6",
"Tags": [
"c#",
"linq"
],
"Title": "Group collections by their elements property"
}
|
18657
|
<p>I have a class that has a method which takes a user as an argument and performs several validation checks on the user and returns a boolean to indicate if theyare valid. </p>
<p>I want to be able to get error messages back from the validation method along with the boolean return value.</p>
<p>I was thinking of doing it by passing a StringBuffer as an argument along with the user and in the validation code appending error messages to the buffer so that the caller gets the boolean returned and then can look at the StringBuffer for error messages.</p>
<pre><code>// validation class
public boolean validateUser(User user, StringBuffer errors) {
...
}
// caller
StringBuffer errors = new StringBuffer();
boolean validUser = validateUser(user, errors);
if (!validUser) {
log(errors.toString();
}
</code></pre>
<p>Is this good practice in Java? Or would it be better to log the errors to a buffer in the validation class and have a public method to get the errors? Or should the validateUser() method return an object that contains the boolean and errors?</p>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T09:32:04.293",
"Id": "29786",
"Score": "0",
"body": "An `Appendable` or `CharSequence` parameter instead of a `StringBuffer` would be more flexible and allow e.g. `StringBuilder`s."
}
] |
[
{
"body": "<p>I quite like the idea when implementing error handlers to do stuff through an interface to remove any dependencies on modules. Sometimes I've used that in conjunction with a global static Log method. I've typically done this in c# but the theory is the same across to Java I believe.</p>\n\n<p>So how about something like this?</p>\n\n<pre><code>interface IErrorHandler\n{\n void addError(string message);\n bool hasErrors();\n void persist();\n}\n</code></pre>\n\n<p>Then you could do either:</p>\n\n<pre><code>// Possibly return an IErrorHandler instead of boolean here?\npublic boolean validateUser(User user, IErrorHandler errorHandler) {\n\n // on error\n errorHandler.AddError(...);\n}\n</code></pre>\n\n<p>Then create an implementation of errorHandler that wraps a StringBuffer (if you wish or whatever i.e. FileWriter, DbWriter etc)</p>\n\n<pre><code>class MemoryErrorHandler implements IErrorHandler\n{\n private final StringBuffer _errors;\n\n public MemoryErrorHandler() {\n _errors = new StringBuffer();\n }\n\n public void addError(string message) {\n _errors.append(message);\n }\n\n public bool hasErrors() {\n _errors.length() > 0;\n }\n\n public void persist() {\n System.out.console.printlin(_errors.toString();\n }\n}\n</code></pre>\n\n<p>Then from the caller something like</p>\n\n<pre><code>IErrorHandler errorHandler = new MemoryErrorHandler();\nvalidateUser(user, errorHandler);\nif (errorHandler.hasErrors()) {\n // do something with the errors\n errorHandler.persist();\n}\n</code></pre>\n\n<p>A further enhancement would be to consider DI of the IErrorHandler into your application so that it is only ever defined in one place. That way will end up having dependencies on IErrorHandler throughout the code which would make it easier to unit test as required.</p>\n\n<p>Of course the IErrorHandler interface could include other methods, these were just suggestions based on your original code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T19:07:27.460",
"Id": "29728",
"Score": "0",
"body": "I agree with your comment regarding the `validateUser()` method: passing only a User and returning an `IErrorHandler` seems to be more clean than a validation method with side-effects. You could check the `hasErrors()` method after, and then handle with any errors as necessary."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T19:01:09.050",
"Id": "18672",
"ParentId": "18671",
"Score": "2"
}
},
{
"body": "<p>Since you are dealing with a validation method, I believe you will want to read my question <em><a href=\"https://codereview.stackexchange.com/questions/11724/is-it-better-practice-to-have-void-method-throw-an-exception-or-to-have-the-meth\">Is it better practice to have void method throw an exception or to have the method return a boolean?</a></em> and its answers. My point there is that you don't really need to return a boolean, you could also have a void method throw an exception if the validation fails. The exception could then, in your case, contain the errors as its payload. But I think that passing a logger as a parameter isn't a bad practice, just basically a matter of personal preference and to be decided on a case by case basis, much like the question about whether to return a boolean or to throw an exception.</p>\n\n<p>In any case, however, I would never use a StringBuffer as an error logger like in your case. For one, I might be building a web application where the output is rendered in HTML. In that case the StringBuffer would basically need to contain the HTML markup, which would then become a problem once you one day figure out that you need to run your process from the command line as well, and then you get all the HTML markup to mess up the output there. Also, with the StringBuffer you cannot easily get the error count, just whether there were any errors or not. So I would probably create an implementation of some IErrorHandler kind of interface wrapping a <code>List<String></code> rather than a StringBuffer, as in @dreza's answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T00:36:10.127",
"Id": "18686",
"ParentId": "18671",
"Score": "5"
}
},
{
"body": "<p>I would prefer to have a method that returns a class instance:</p>\n\n<pre><code>public ValidateUserResult validateUser(User user, StringBuffer errors) {\n ...\n}\n\nValidateUserResult result = validateUser(user);\nif (!result.isValid()) {\n for (String error: result.getErrors()) {\n System.out.println(\"Error: \" + error);\n }\n}\n</code></pre>\n\n<p>Java doesn't have the concept of \"output\" parameters and I think that anything that tries to mimic that behavior is confusing. Alternatively, you can just return a list of errors, and if that list is empty, then the user is valid. Or you can create a generic \"validation result\" class similar to what dreza suggested.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T16:25:04.590",
"Id": "18774",
"ParentId": "18671",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18672",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T18:28:20.533",
"Id": "18671",
"Score": "3",
"Tags": [
"java"
],
"Title": "Is it good practice in Java to pass a StringBuffer to a method to get error messages"
}
|
18671
|
<p>This program will filter the input by replacing matching bad words with "Bleep!". I'd like the code to be more concise and C++ style where possible. One thing that bugs me is the <code>was_bad</code> flag I think is needed to skip printing a word that has matched one of my bad words - if there was some better way to skip the rest of the <code>while</code> loop upon encountering a bad word so I don't print <code>Bleep! poop</code>, for instance.</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(void)
{
int i, was_bad = false;
string input, bad[] = {"poop", "balls"};
vector <string> badwords(bad, bad + sizeof(bad) / sizeof(string));
while (cin >> input)
{
for (i = 0; i < badwords.size(); ++i)
if (badwords[i] == input)
{
cout << "Bleep! ";
was_bad = true;
break;
}
if (!was_bad)
cout << input << " ";
was_bad = false;
}
return 0;
}
</code></pre>
<p>One thing that did strike me was to use a ternary operator:</p>
<pre><code>while (cin >> input)
{
for (i = 0; i < badwords.size(); ++i)
if (badwords[i] == input)
{
is_bad = true;
break;
}
cout << (is_bad ? "Bleep! " : input + " ");
is_bad = false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T00:08:15.090",
"Id": "62773",
"Score": "3",
"body": "so I *can't* say poop, but I *can* say POOP and pooop p00p I would recommend looking at c++11 regular expressions.\nhttp://www.cplusplus.com/reference/std/regex/"
}
] |
[
{
"body": "<p>Instead of iterating over a vector I'd use <code>std::find()</code>.\nEven better, instead of <code>std::vector</code> I'd use <code>std::set</code>:</p>\n\n<pre><code>#include <iostream>\n#include <set>\n#include <string>\n\nusing namespace std;\n\nint main(int argc, const char * argv[])\n{\n string bad[] = {\"poop\", \"balls\"};\n set<string> bad_words(bad, bad + sizeof(bad) / sizeof(string));\n\n string input;\n while(cin >> input)\n {\n if(bad_words.find(input)!=bad_words.end()){\n cout << \"bleep! \";\n }\n else {\n cout << input << \" \";\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T15:37:17.837",
"Id": "420134",
"Score": "0",
"body": "This answer can be improved slightly by getting rid of the string array and using the initializer-list constructor for std::set directly:\n`set<string> bad_words{\"poop\", \"balls\"};`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-11-15T21:32:12.620",
"Id": "18680",
"ParentId": "18673",
"Score": "6"
}
},
{
"body": "<p>The word you are looking for is <code>continue</code>;</p>\n\n<pre><code>while (cin >> input)\n{\n for (i = 0; i < badwords.size(); ++i)\n if (badwords[i] == input)\n {\n cout << \"Bleep! \";\n continue; // This starts the next iteration of the loop.\n // ie we go back to the while loop and read the\n // the next word (or attempt to do so).\n }\n\n cout << input << \" \";\n}\n</code></pre>\n\n<p>You can also improve your search. Rather than using <code>std::vector<std::string></code> use a <code>std::set<std::string></code>. Then a find will automatically do a <span class=\"math-container\">\\$O(\\log n)\\$</span> search of the data.</p>\n\n<pre><code>while (cin >> input)\n{\n if (badwords.find(input) != badwords.end())\n {\n cout << \"Bleep! \";\n continue;\n }\n\n cout << input << \" \";\n}\n</code></pre>\n\n<p>Now that we have the basic algorithm we can use some of the standard algorithms:</p>\n\n<p>So now replace the main loop:</p>\n\n<pre><code>std::transform(std::istream_iterator<std::string>(std::cin),\n std::istream_iterator<std::string>(),\n std::ostream_iterator<std::string>(std::cout, \" \"),\n BadWordFilter(badwords));\n</code></pre>\n\n<p>Then you just need to define the <code>BadWordFilter</code></p>\n\n<pre><code>struct BadWordFilter\n{\n std::set<std::string> const& badWordSet;\n BadWordFilter(std::set<std::string> const& badWordSet) : badWordSet(badWordSet) {}\n\n std::string operator()(std::string const& word) const\n {\n static std::string badWord(\"Bleep!\");\n\n return (badWordSet.find(word) == badWordSet.end())\n ? word\n : badWord;\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T21:45:31.800",
"Id": "29734",
"Score": "0",
"body": "Hm, I tried `continue` intially but it didn't work, I think in this case it just skipped remaining code and started the next iteration of the `for` loop (as `i` may not have reached its limit yet), whereas `break` would terminate all future iterations of the `for` loop and thus fall back into the `while` loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T21:49:27.163",
"Id": "29736",
"Score": "0",
"body": "@DesmondWolf: The problem with your code is the variable `was_bad` as this was set just before the break. Then when you do a break the loop is re-started but now the next word is also ignored because you did not reset `was_bad`. Just drop this variable and its use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T21:53:25.557",
"Id": "29738",
"Score": "0",
"body": "Insightful post, lots to learn! Thankyou."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-11-15T21:39:03.850",
"Id": "18681",
"ParentId": "18673",
"Score": "6"
}
},
{
"body": "<p>I'm not sure I'd use <code>std::set</code> to hold the list of bad words in a case like this. <code>std::set</code> is (at least normally) implemented as a balanced tree, with each node separately allocated. This tends to reduce locality of reference.</p>\n\n<p>By contrast, a <code>vector</code> is always contiguously allocated, improving locality of reference so it's more cache-friendly (and also tending to reduce heap fragmentation, for whatever that may be worth).</p>\n\n<p>That doesn't mean you should forego the wonders of standard algorithms though. Quite the contrary, standard algorithms will do the job quite nicely. Since you only care about the presence/absence of a word in the \"set\", you can use <code>std::binary_search</code> to check:</p>\n\n<pre><code>std::vector<std::string> bad(std::istream_iterator<std::string>(bad_file), \n std::istream_iterator<std::string>);\n\n// You can remove this sort if you're sure the words are already sorted.\nstd::sort(bad.begin(), bad.end());\n\n// process the data\nstd::replace_copy_if(\n std::istream_iterator<std::string>(infile),\n std::istream_iterator<std::string>(),\n std::ostream_iterator<std::string>(outfile, \" \"),\n [&](std::string const &s) { \n return std::binary_search(bad.begin(), bad.end(), s); \n }, \n \"bleep\");\n</code></pre>\n\n<p>If memory serves, <code>replace_copy_if</code> is new with C++11, but it's fairly easy to write your own if necessary. If you don't have that, chances are pretty good you won't have lambdas available either. In this case, you should be able to replace it with a suitable invocation using <code>std::bind1st</code> and <code>std::bind2nd</code>, but I'll leave that as an exercise for the reader (personally, I'd at least consider a function object or something like <code>boost::bind</code> instead).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-11-16T02:01:54.467",
"Id": "18690",
"ParentId": "18673",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18681",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T19:15:43.007",
"Id": "18673",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Filtering out rude words"
}
|
18673
|
<p>I am a self-taught programmer who has been programming for a long time, but mainly just for personal projects. I would like to improve my skills and am open to any suggestions that you may have, but am particularly interested in your thoughts about:</p>
<ul>
<li>The number of methods in this class: Too few/too many?</li>
<li>Method/variable names: Descriptive enough?/too descriptive?</li>
<li>Comments: Too few/too many?</li>
<li>Code formatting: Any suggestions?</li>
</ul>
<p>Full project is hosted on <a href="https://github.com/lnafziger/Numberpad" rel="nofollow noreferrer" title="Github">GitHub</a>.</p>
<p><strong>Numberpad.m</strong></p>
<pre><code>/******************************************************************************
* v. 0.9.1 15 NOV 2012
* Filename Numberpad.m
* Project: NumberPad
* Purpose: Class to display a custom numberpad on an iPad and properly handle
* the text input.
* Author: Louis Nafziger
*
* Copyright 2012 Louis Nafziger
******************************************************************************
*
* This file is part of NumberPad.
*
* NumberPad is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NumberPad is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU LesserGeneral Public License
* along with NumberPad. If not, see <http://www.gnu.org/licenses/>. *
*
*****************************************************************************/
#import "Numberpad.h"
#pragma mark - Private methods
@interface Numberpad ()
@property (nonatomic, weak) id<UITextInput> targetTextInput;
@end
#pragma mark - Numberpad Implementation
@implementation Numberpad
@synthesize targetTextInput;
#pragma mark - Singleton method
+ (Numberpad *)defaultNumberpad {
static Numberpad *defaultNumberpad = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
defaultNumberpad = [[Numberpad alloc] init];
});
return defaultNumberpad;
}
#pragma mark - view lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
// Keep track of the textView/Field that we are editing
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(editingDidBegin:)
name:UITextFieldTextDidBeginEditingNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(editingDidBegin:)
name:UITextViewTextDidBeginEditingNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(editingDidEnd:)
name:UITextFieldTextDidEndEditingNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(editingDidEnd:)
name:UITextViewTextDidEndEditingNotification
object:nil];
}
- (void)viewDidUnload {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextFieldTextDidBeginEditingNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextViewTextDidBeginEditingNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextFieldTextDidEndEditingNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextViewTextDidEndEditingNotification
object:nil];
self.targetTextInput = nil;
[super viewDidUnload];
}
#pragma mark - editingDidBegin/End
// Editing just began, store a reference to the object that just became the firstResponder
- (void)editingDidBegin:(NSNotification *)notification {
if (![notification.object conformsToProtocol:@protocol(UITextInput)]) {
self.targetTextInput = nil;
return;
}
self.targetTextInput = notification.object;
}
// Editing just ended.
- (void)editingDidEnd:(NSNotification *)notification {
self.targetTextInput = nil;
}
#pragma mark - Keypad IBAction's
// A number (0-9) was just pressed on the number pad
- (IBAction)numberpadNumberPressed:(UIButton *)sender {
if (self.targetTextInput == nil) {
return;
}
NSString *numberPressed = sender.titleLabel.text;
if ([numberPressed length] == 0) {
return;
}
UITextRange *selectedTextRange = self.targetTextInput.selectedTextRange;
if (selectedTextRange == nil) {
return;
}
[self textInput:self.targetTextInput replaceTextAtTextRange:selectedTextRange withString:numberPressed];
}
// The delete button was just pressed on the number pad
- (IBAction)numberpadDeletePressed:(UIButton *)sender {
if (self.targetTextInput == nil) {
return;
}
UITextRange *selectedTextRange = self.targetTextInput.selectedTextRange;
if (selectedTextRange == nil) {
return;
}
// Calculate the selected text to delete
UITextPosition *startPosition = [self.targetTextInput positionFromPosition:selectedTextRange.start offset:-1];
if (startPosition == nil) {
return;
}
UITextPosition *endPosition = selectedTextRange.end;
if (endPosition == nil) {
return;
}
UITextRange *rangeToDelete = [self.targetTextInput textRangeFromPosition:startPosition
toPosition:endPosition];
[self textInput:self.targetTextInput replaceTextAtTextRange:rangeToDelete withString:@""];
}
// The clear button was just pressed on the number pad
- (IBAction)numberpadClearPressed:(UIButton *)sender {
if (self.targetTextInput == nil) {
return;
}
UITextRange *allTextRange = [self.targetTextInput textRangeFromPosition:self.targetTextInput.beginningOfDocument
toPosition:self.targetTextInput.endOfDocument];
[self textInput:self.targetTextInput replaceTextAtTextRange:allTextRange withString:@""];
}
// The done button was just pressed on the number pad
- (IBAction)numberpadDonePressed:(UIButton *)sender {
if (self.targetTextInput == nil) {
return;
}
// Call the delegate methods and resign the first responder if appropriate
if ([self.targetTextInput isKindOfClass:[UITextView class]]) {
UITextView *textView = (UITextView *)self.targetTextInput;
if ([textView.delegate respondsToSelector:@selector(textViewShouldEndEditing:)]) {
if ([textView.delegate textViewShouldEndEditing:textView])
{
[textView resignFirstResponder];
}
}
} else if ([self.targetTextInput isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)self.targetTextInput;
if ([textField.delegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) {
if ([textField.delegate textFieldShouldEndEditing:textField])
{
[textField resignFirstResponder];
}
}
}
}
#pragma mark - text replacement routines
// Check delegate methods to see if we should change the characters in range
- (BOOL)textInput:(id <UITextInput>)textInput shouldChangeCharactersInRange:(NSRange)range withString:(NSString *)string
{
if ([textInput isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)textInput;
if ([textField.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
if (![textField.delegate textField:textField
shouldChangeCharactersInRange:range
replacementString:string]) {
return NO;
}
}
} else if ([textInput isKindOfClass:[UITextView class]]) {
UITextView *textView = (UITextView *)textInput;
if ([textView.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) {
if (![textView.delegate textView:textView
shouldChangeTextInRange:range
replacementText:string]) {
return NO;
}
}
}
return YES;
}
// Replace the text of the textInput in textRange with string if the delegate approves
- (void)textInput:(id <UITextInput>)textInput replaceTextAtTextRange:(UITextRange *)textRange withString:(NSString *)string {
if (textInput == nil) {
return;
}
if (textRange == nil) {
return;
}
// Calculate the NSRange for the textInput text in the UITextRange textRange:
int startPos = [textInput offsetFromPosition:textInput.beginningOfDocument
toPosition:textRange.start];
int length = [textInput offsetFromPosition:textRange.start
toPosition:textRange.end];
NSRange selectedRange = NSMakeRange(startPos, length);
if ([self textInput:textInput shouldChangeCharactersInRange:selectedRange withString:string]) {
// Make the replacement:
[textInput replaceRange:textRange withText:string];
}
}
@end
</code></pre>
|
[] |
[
{
"body": "<p>I'm not that much experienced in iOS development, but I can give a great deal about code formatting. These are my suggestions, which are mostly my own opinion and in no way the only way of doing things.</p>\n\n<p>I'll start by saying that in your situation (working on your own), formatting your code properly is mostly so <strong>you</strong> can read your code easily, and find your way through if you leave the project for a certain amount of time, and come back to it later. So, you should really do it the way you like, and in a way you're sure you'll always understand.</p>\n\n<p>That being said, here is what I think, answering to the points you gave in your question.</p>\n\n<p><strong>The number of methods in this class:</strong></p>\n\n<p>It seems about right. There doesn't seems to be code duplicates, and I mostly see methods as a way of avoiding this situation.</p>\n\n<p><strong>Method/variable names:</strong></p>\n\n<p>They're explicit, and as I said earlier, as long as you understand them, it's fine.</p>\n\n<p>One thing though, you declare the property <code>targetTextInput</code> in your .m file. Someone stop me if I'm wrong, but I think you only get for this the fact that the property becomes private. To do so, I would personally declare it in the <code>@implementation</code> directive :</p>\n\n<pre><code>@implementation Numberpad {\n\n id<UITextInput> targetTextInput;\n}\n</code></pre>\n\n<p>The variable is still private, and I think it's more readable. Again, if someone else could confirm that one, I really think the outcome is the same.</p>\n\n<p><strong>Comments:</strong></p>\n\n<p>The code is well commented, most importantly all your methods have a comment explaining what they do. I wouldn't care for a couple more comments inside the methods, but they don't seem that complex here. Methods involving intense use of <code>while</code>, <code>if</code>, <code>switch</code>, <code>for</code>, etc. would require more comments to understand them.</p>\n\n<p><strong>Code formatting:</strong></p>\n\n<p>It's clear and well-structured, nothing strikes at sees.</p>\n\n<p>One thing I really don't like though is the way you align all the \"=\" signs. I don't think it helps readability, so I find pretty useless doing so. You also do it with some declarations:</p>\n\n<pre><code>UITextPosition *endPosition = selectedTextRange.end;\nUITextRange *rangeToDelete = [self.targetTextInput textRangeFromPosition:startPosition\n toPosition:endPosition];\n</code></pre>\n\n<p>I don't find it very useful...</p>\n\n<p>I'd also say there's a bit of a lack of consistency in your formatting. For example (a minor thing though), you may use</p>\n\n<pre><code>if (my condition) {\n\n // my actions\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (my condition)\n{\n // my actions\n}\n</code></pre>\n\n<p>The position of the left brace is not really important, but if you really want a perfectly-formatted code, I'd consider picking one and use only this one throughout your code. Apple's code uses the first one, and I like it too. But again, personal choice.</p>\n\n<p>Also, when you call methods in your <code>if</code>s, you sometimes use an inline format, and sometimes you do it that way:</p>\n\n<pre><code>if (![textField.delegate textField:textField\n shouldChangeCharactersInRange:range\n replacementString:string]) {\n return NO;\n }\n</code></pre>\n\n<p>I think an inline presentation is better, and I would drop the braces if your <code>if</code>'s action is a single line, giving this result :</p>\n\n<pre><code>if (![textField.delegate textField:textField shouldChangeCharactersInRange:range replacementString:string]) return NO;\n</code></pre>\n\n<p>One may argue on that one, saying it's a too long line and it my break, but if you're not developing on an iPad, I think it'll fit.</p>\n\n<p><strong>Any other thoughts?</strong></p>\n\n<p>When you declare a property, it's nice to synthesize it that way :</p>\n\n<pre><code>@synthesize targetTextInput = _targetTextInput;\n</code></pre>\n\n<p>and access the property with <code>_targetTextInput</code> instead of <code>self.targetTextInput</code>.This \"underscore convention\" is encouraged by Apple, and even more, since Xcode 4.5, you don't need to synthesize your properties anymore (Xcode does it for you), and you can access them directly using <code>_targetTextInput</code>. Apple has integrated the underscore convention to properties declaration. It takes a few lines out from your code, so that's always nice.</p>\n\n<p>When you check if an object is nil, there are two ways to do it :</p>\n\n<pre><code>if (self.targetTextInput == nil) {}\nif (!self.targetTextInput) {}\n</code></pre>\n\n<p>Not much to say here, choose whichever you like, but you seem to have a bunch of those in your code.</p>\n\n<p>Not everybody agrees on the use of <code>pragma</code>, as (I think ?) \"/* */\" can do the same (puts a link in the jump bar), but you can go further with it:</p>\n\n<pre><code>pragma -\n</code></pre>\n\n<p>will create a simple separator,</p>\n\n<pre><code>pragma My Label\n</code></pre>\n\n<p>will create a label, and</p>\n\n<pre><code>pragma - My Label\n</code></pre>\n\n<p>will create both (as you used it).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:28:45.900",
"Id": "29832",
"Score": "0",
"body": "Thank you for your detailed analysis! I have a few comments about what you have said (I'll add one comment for each subject to make them easier to follow. :))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:32:46.107",
"Id": "29833",
"Score": "0",
"body": "The difference between putting `targetTextInput` in the implementation block and putting it in the .m file is two-fold. 1. The way that you suggest creates an iVar which is different than adding a declared property. It creates no setters/getters and forces you to use the iVar directly. 2. Putting it in the .m file hides the implementation details of the class from external users of the class. When there is something that does not need to be exposed, it gives more flexibility down the road when it comes time to make changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:34:48.770",
"Id": "29834",
"Score": "0",
"body": "Aligning the = signs: While I do think that it makes code easier to read (you can easily scan down a list of variables without having to \"zig-zag\"), you bring up good points about maintainability. I'll try that moving forward, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:36:30.153",
"Id": "29835",
"Score": "0",
"body": "`if {` on one line -vs- two lines: Yeah, I have changed my style on this since originally writing the class and had mixed styles, which I thought that I had made all match before posting the question. Those two slipped through, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:39:06.717",
"Id": "29836",
"Score": "0",
"body": "Inline -vs- multiple line method calls: This one I really think improves the readability on long lines because it is very clear where each argument starts, and with the very long method names that we use on iOS, it often does wrap to multiple lines for me. Is there standardization on the inline format from most programmers? (If so, I guess I'll just have to deal with it, lol.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:40:30.113",
"Id": "29837",
"Score": "0",
"body": "\"I would drop the braces if your if's action is a single line\": I have read that this is a bad idea because it can be easy to break code when making changes later? Especially if you add an else, you can end up with unexpected behavior?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:43:59.577",
"Id": "29838",
"Score": "0",
"body": "\"@synthesize targetTextInput = _targetTextInput;\": Oh, the debate on this one... I think that there is something almost on scale with a holy war on this discussion. Let's just say that I ended up in the camp that doesn't use the underscore, lol. And, just FYI, Apple didn't add the auto synthesis, it is a new Objective-C language feature (and was not added by Apple). I have considered changing this since the language has evolved this way, and still may in the future. Before this though, even Apple had released example code both ways. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:46:11.397",
"Id": "29839",
"Score": "0",
"body": "To use `== nil` or not to use: I've actually switched to not using it anymore, but I wrote this code some time ago. You mention that I have a bunch of these. Do you feel that these checks are unnecessary, or should I be doing them in a different way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:47:14.887",
"Id": "29840",
"Score": "0",
"body": "I haven't heard anything negative about #pragma. Do you know the reasons against using it? You show examples of different ways to use it, do you have specific suggestions on something that I should be doing different with it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:47:35.947",
"Id": "29841",
"Score": "0",
"body": "+1 Thank you again for all of your help! I want to leave this question open a little longer to see if we get any further suggestions before I award it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:49:35.207",
"Id": "29950",
"Score": "0",
"body": "Well, that's a great lot of comments, lol. I don't think I need to answer to every single one, as you seem to know pretty well what you're talking about. About the \"Inline -vs- multiple line method calls\", I do use multiple lines calls and find them clearer, but I find them hard to read in an \"if\" call. About the braces, I drop them in 2 cases: a single \"if\" with a single line, or \"if/else if/else\"s where they all call a single line. Otherwise I keep them. Thanks for the note about @synthesize, I thought it was some Xcode feature :p."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:49:55.953",
"Id": "29951",
"Score": "0",
"body": "When I started iOS development, I did not use this _formatting, but since you don't need to synthesize anymore, I use it all the time, lol. About the \"==nil\" checks, I can't say they're un/necessary, it was just a quick note on using \"!\". About pragmas, I read somewhere (can't seem to find it again) an arguing about the fact that it's a preprocessor call, but I couldn't tell you more.. I use it the same way as you do, I was just giving tips on other ways to use it ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T07:45:58.827",
"Id": "30091",
"Score": "0",
"body": "The one thing that's nagging me over this whole thing is that you don't have your own class namespace (no prefixes on the Numberpad class). Perhaps consider a refactor>rename to IFNumberPad, or IFZNumberPad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T08:35:44.347",
"Id": "30092",
"Score": "0",
"body": "@CodaFi : why is that ? I never really got the point of doing so. Maybe I get it if you share your source code, so you \"know\" where it comes from, but otherwise you usually use your own classes a lot, and having to type \"IFZNu\" before the right auto-completion takes longer than typing \"Nu\", and if you call a custom class every couple of lines, I think you're just wasting time.. So (finally, the question), why should Objective-C devs do that ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T15:04:57.730",
"Id": "30109",
"Score": "0",
"body": "Because like you said a). If it's open sourced, it doesn't create conflicts with some other guy's crappily named methods, and it gets your name out there b) if it is a private class, then, say, Apple were to decide to internally name one of their symbols Numberpad, you're now completely future proofed (Apple has their namespace, you have yours). And another thing, you shouldn't have to type the names of classes a lot... And if you do, I feel sorry for the casting jobs you'd hypothetically be doing every five seconds (that's my definition of \"wasting time\" with a class name)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T15:11:06.867",
"Id": "30111",
"Score": "0",
"body": "I see your point. Now I don't understand why you're saying it's \"bad\" to use your custom classes a lot ? (trying to learn here :) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T02:35:07.050",
"Id": "31867",
"Score": "0",
"body": "@CodaFi: Thanks for the suggestion, I'll update that next time that I make some changes to the class. Any other suggestions?"
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T15:55:52.257",
"Id": "18712",
"ParentId": "18676",
"Score": "7"
}
},
{
"body": "<p>I agree with <em>@rdurand</em> about the code formatting. Aligning the right sides of assignment statements is too hard to maintain:</p>\n\n<pre><code>UITextPosition *startPosition = [self.targetTextInput positionFromPosition:selectedTextRange.start offset:-1];\n...\nUITextPosition *endPosition = selectedTextRange.end;\n...\nUITextRange *rangeToDelete = [self.targetTextInput textRangeFromPosition:startPosition\n toPosition:endPosition];\n</code></pre>\n\n<p>From <em>Code Complete, 2nd Edition</em> by <em>Steve McConnell</em>, p758:</p>\n\n<blockquote>\n <p><strong>Do not align right sides of assignment statements</strong></p>\n \n <p>[...]</p>\n \n <p>With the benefit of 10 years’ hindsight, I have found that, \n while this indentation style might look attractive, it becomes\n a headache to maintain the alignment of the equals signs as variable \n names change and code is run through tools that substitute tabs\n for spaces and spaces for tabs. It is also hard to maintain as\n lines are moved among different parts of the program that have \n different levels of indentation.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T16:48:50.757",
"Id": "29807",
"Score": "0",
"body": "Quoting this book ? http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T17:02:35.603",
"Id": "29808",
"Score": "0",
"body": "@rdurand: Oh, no, sorry, see the edit, please. Thanks for the comment!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T17:07:04.160",
"Id": "29809",
"Score": "0",
"body": "Seems like quite a read ! Looks instructive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T16:53:12.703",
"Id": "29864",
"Score": "0",
"body": "@lnafziger: That was my only one. I'm not familiar with iOS/Objective C at all."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T16:36:47.460",
"Id": "18716",
"ParentId": "18676",
"Score": "3"
}
},
{
"body": "<pre><code>if (![textField.delegate textField:textField\n shouldChangeCharactersInRange:range\n replacementString:string]) {\n return NO;\n}\n</code></pre>\n\n<p>This could be replaced by simply this:</p>\n\n<pre><code>return [textField.delegate textField:textField\n shouldChangeCharactersInRange:range\n replacementString:string];\n</code></pre>\n\n<p>And the same can be done for <code>textView</code>.</p>\n\n<hr>\n\n<pre><code>- (void)viewDidUnload\n</code></pre>\n\n<p><code>viewDidUnload</code> has been deprecated. We need to remove ourselves as observers in <code>dealloc</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T01:00:44.360",
"Id": "104712",
"Score": "0",
"body": "Yes, this is an old version that was written before viewDidUnload was deprecated. The current version [available here](https://github.com/lnafziger/Numberpad) has been updated since. Good suggestion on the first part though, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T00:08:37.693",
"Id": "58332",
"ParentId": "18676",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18712",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T20:36:31.133",
"Id": "18676",
"Score": "10",
"Tags": [
"objective-c",
"ios"
],
"Title": "Custom numberpad on an iPad"
}
|
18676
|
<p>The following is my code for printing all the substrings of an input string. For example, with "abc", it would be "a","ab","abc","b","bc","c". Could someone please review it for efficiency (and possibly suggest alternatives)?</p>
<pre><code>void findAllSubstrings(const char *s){
int x=0;
while(*(s+x)){
for(int y=0; y<=x; y++)
cout<<*(s+y);
cout<<'\n';
x++;
}
if(*(s+1))
findAllSubstrings(s+1);
else
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T08:31:02.947",
"Id": "29777",
"Score": "0",
"body": "one problem with this code is you have the for loop inside a while loop which is O(n^2)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T08:35:22.130",
"Id": "29778",
"Score": "2",
"body": "What about equal substrings in strings like \"aaa\"? Are you allowed to print \"aa\" twice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T00:40:49.383",
"Id": "29779",
"Score": "0",
"body": "what do you mean buy finding all sub strings? your code seams to print all characters in a string whith \"xxx\" it seems to print x\nxx\nxxx\nx\nxx\nx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T02:03:42.303",
"Id": "29780",
"Score": "0",
"body": "That would be all substrings, no? For example, with \"abc\", it would be \"a\",\"ab\",\"abc\",\"b\",\"bc\",\"c\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T04:58:11.020",
"Id": "29781",
"Score": "0",
"body": "How about saying this, findCombinations ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T09:48:56.613",
"Id": "29787",
"Score": "1",
"body": "@Kinjal Sets have n^2 subsets, so at the base of the problem, n^2 is unavoidable (not to say that this code couldn't be optimized though)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T13:40:14.197",
"Id": "29796",
"Score": "0",
"body": "@Frank No, you can't print any character twice unless it appears twice in succession within the original string, for example, in \"aabc\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T13:40:58.173",
"Id": "29797",
"Score": "0",
"body": "@Kinjal I'm not finding combinations either. Finding combinations from \"abc\" would also involve the string \"ac\", which is not a substring. It is a different problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T13:41:15.800",
"Id": "29798",
"Score": "0",
"body": "@Corbin So how about suggesting some of these optimizations, as this was the original question I posed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T21:06:55.127",
"Id": "29814",
"Score": "0",
"body": "@JohnRoberts My main suggestion would've been changing from recursive to iterative, though it seems Synxis has already covered that. From a style point of view, I might be tempted to switch to iterators since you could then generalize the algorithm, but that would probably have worse performance."
}
] |
[
{
"body": "<p>Your problem is in O(n²), at least. This seems not to be optimizable. If you want only distinct substrings, then you will have to use a table of already encountered strings, which will make your code slower.</p>\n\n<p>However, you can switch the algorithm from recursive to iterative, which is usually slightly faster. It's a micro-optimization, so do not expect a x2 improvement in speed... </p>\n\n<pre><code>void findAllSubstrings2(const char *s)\n{\n while(*s)\n {\n int x=0;\n while(*(s + x))\n {\n for(int y = 0; y <= x; y++)\n std::cout << *(s + y);\n std::cout << \"\\n\";\n x++;\n }\n s++;\n }\n}\n</code></pre>\n\n<p>I've done a profile test, on <a href=\"http://codepad.org/QcOkVgr6\">Codepad</a> and <a href=\"http://ideone.com/ug9Nb2\">Ideone</a> (different versions of same compilers + different machines). The io operations are left for the profile test, because what matters here is the comparison between the 2 functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T21:15:52.547",
"Id": "29816",
"Score": "0",
"body": "When an auxiliary stack isn't required and TCO isn't possible, converting recursion to iteration tends to have a very significant performance improvement. Definitely not a 2x improvement, but I definitely wouldn't consider it a micro optimization. In the case of a 3 character string, the recursion only goes 3 levels deep. What if the string were 100 characters?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T16:33:28.013",
"Id": "18715",
"ParentId": "18684",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "18715",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T00:03:07.013",
"Id": "18684",
"Score": "8",
"Tags": [
"c++",
"algorithm"
],
"Title": "Find All Substrings Interview Query in C++"
}
|
18684
|
<p>I use some basic cryptography in a project of mine. Because I want my application to run cross-platform and because it seems pretty sophisticated I decided to go with the Java Cryptography Architecture.</p>
<p>I'm pretty fresh with crypto in general, so I'd like to hear someone's opinion who has some experience with that.</p>
<p>First, I have some convenience wrapper classes for the different symmetric ciphers I support:</p>
<pre><code>public abstract class PwsCipher {
//=== methods ================================================================
/**
* Gets the cipher's block length.
* @return Block length in bytes.
*/
int getBlockLength()
throws NoSuchAlgorithmException, NoSuchPaddingException,
NoSuchAlgorithmException, NoSuchProviderException {
return createCipher().getBlockSize();
}
/**
* Creates a new {@link javax.crypto.cipher} instance of this
* cipher.
* @return Instance of {@link Cipher}.
*/
Cipher createCipher()
throws NoSuchAlgorithmException, NoSuchPaddingException,
NoSuchProviderException {
String provider = "SC"; // Spongy Castle for android
if ( !System.getProperty("java.vm.name").equals("Dalvik") ) {
provider = "BC"; // Bouncy Castle for everything else
}
return Cipher.getInstance(getName() + "/CBC/PKCS7Padding", provider);
}
//=== getter & setter ========================================================
/**
* Gets the name of the cipher.
* @return Cipher name.
*/
abstract String getName();
/**
* Gets the key length of the cipher in bytes.
* @return Key length in bytes.
*/
abstract int getKeyLength();
}
public class PwsCipherAES extends PwsCipher {
//=== getter & setter ========================================================
@Override
public String getName() {
return "AES";
}
@Override
public int getKeyLength() {
return 32;
}
}
public class PwsCipherBlowfish extends PwsCipher {
//=== getter & setter ========================================================
@Override
public String getName() {
return "Blowfish";
}
@Override
public int getKeyLength() {
return 56;
}
}
public class PwsCipherDES3 extends PwsCipher {
//=== getter & setter ========================================================
@Override
public String getName() {
return "DES3";
}
@Override
public int getKeyLength() {
return 24;
}
}
</code></pre>
<p>Then, I have a <code>Passphrase</code> class which I use to create a SHA-512 hash and salt for a clear text passphrase:</p>
<pre><code>public class Passphrase {
//=== attributes =============================================================
/** The salt value of the passphrase. */
private byte[] salt;
/** The hashed passphrase. */
private byte[] hashed;
//=== constructors ===========================================================
/**
* Creates a new instance of {@code Passphrase}.
* Assumes that the passphprase is not hashed, and that a new, random salt
* value should be created.
* @param phrase Clear text passphrase. Must not be hashed yet.
*/
public Passphrase(String clearPhrase) throws NoSuchAlgorithmException {
this(clearPhrase, false, null);
}
/**
* Creates a new instance of {@code Passphrase}.
* Assumes that the passphrase is not hashed.
* @param phrase Clear text passphrase.
* @param salt Salt of the passphrase. May be {@code null}. If so, a new
* random salt will be created.
*/
public Passphrase(String clearPhrase, byte[] salt)
throws NoSuchAlgorithmException {
this(clearPhrase, false, salt);
}
/**
* Creates a new instance of {@code Passphrase}.
* @param phrase Clear text or hashed passphrase.
* @param isHashed Tells if the passphrase is already hashed. If {@code false}
* the hash of the clear text passphrase will be created.
* @param salt Salt of the passphrase. May be {@code null}. If so, a new
* random salt will be created.
*/
public Passphrase(String phrase, boolean isHashed, byte[] salt)
throws NoSuchAlgorithmException {
setSalt(salt);
setHash(phrase, isHashed);
}
//=== static methods =========================================================
//=== methods ================================================================
/**
* Creates a random byte array with length 64.
* @return Random byte array.
*/
public final byte[] createRandomSalt() {
Random r = new SecureRandom();
byte[] slt = new byte[64];
r.nextBytes(slt);
return slt;
}
//=== getter & setter ========================================================
/**
* Sets the salt of the Passphrase. <br/>
* May be {@code null}. If that is the case, a new, random salt will created.
* @param salt Salt to be set. May be {@code null}. In that case a random salt
* will be generated. Should not be longer than hash length, which is 64 bytes
*/
private void setSalt(byte[] salt) {
if ( salt == null ) {
this.salt = createRandomSalt();
} else {
this.salt = salt;
}
}
/**
* Sets the hashed passphrase. <br/>
* If the passphrase is not hashed, it will be using SHA-512 and the
* previously set salt.
* @param phrase Hashed or clear text passphrase.
* @param isHashed Tells if the passphrase is already hashed.
*/
private void setHash(String phrase, boolean isHashed)
throws NoSuchAlgorithmException {
if ( isHashed ) {
this.hashed = phrase.getBytes();
} else {
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] salted = new byte[phrase.length() + salt.length];
byte[] clear = phrase.getBytes();
System.arraycopy(clear, 0, salted, 0, clear.length);
System.arraycopy(salt, 0, salted, clear.length, salt.length);
this.hashed = md.digest(salted);
//@TODO: nullify byte[] clear, as it contains clear text passphrase, which
// we don't want to be swapped or debugged
}
}
/**
* Gets the hashed passphrase.
* @return Hashed passphrase.
*/
public byte[] getHashedPassphrase() {
return hashed;
}
/**
* Gets the salt of the passphrase.
* @return Salt.
*/
public byte[] getSalt() {
return salt;
}
}
</code></pre>
<p>Finally there is my crypto code:</p>
<pre><code> /**
* Encrypts the given content with the given passphrase and configured cipher.
* @param content Content to be encrypted.
* @return Encrypted byte array.
*/
private byte[] encrypt(byte[] content)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
NoSuchProviderException, InvalidAlgorithmParameterException {
return performCrypto(content, Cipher.ENCRYPT_MODE);
}
/**
* Decrypts the given content with the given passphrase and configured cipher.
* @param content Content to be decrypted.
* @return Decrypted byte array.
*/
private byte[] decrypt(byte[] content)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
NoSuchProviderException, InvalidAlgorithmParameterException {
return performCrypto(content, Cipher.DECRYPT_MODE);
}
/**
* Performs the actual crypto operation based on the given mode. <br/>
* When encrypting, a new random initialization vector will be created, used
* during encryption and finally prepended to the encrypted data chunk, so
* it can be retrieved again during decryption.
* @param content Encrypted or decrypted content.
* @param mode {@link Cipher.ENCRYPT_MODE} or {@link Cipher.DECRYPT_MODE}.
* @return Transformed content
*/
private byte[] performCrypto(byte[] content, int mode)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
NoSuchProviderException, InvalidAlgorithmParameterException {
Cipher c = cipher.createCipher();
SecretKeySpec key = new SecretKeySpec(Arrays.copyOf(
passphrase.getHashedPassphrase(), cipher.getKeyLength()),
cipher.getName());
byte[] iv = createIV(); // always create iv to be able to get iv
// length in decrypt mode
int offset = 0;
int len = content.length;
if ( mode == Cipher.DECRYPT_MODE ) {
// read prepended iv from encrypted data
iv = Arrays.copyOf(content, iv.length);
// offset by length of iv
offset = iv.length;
len -= iv.length;
}
c.init(mode, key, new IvParameterSpec(iv));
byte[] cryptoresult = c.doFinal(content, offset, len);
byte[] finishedarray;
if ( mode == Cipher.ENCRYPT_MODE ) {
// prepend iv
finishedarray = new byte[iv.length + cryptoresult.length];
System.arraycopy(iv, 0,
finishedarray, 0,
iv.length);
System.arraycopy(cryptoresult, 0,
finishedarray, iv.length,
cryptoresult.length);
} else {
finishedarray = cryptoresult;
}
return finishedarray;
}
/**
* Creates a {@link SecureRandom} 16 byte sequence which can be used as
* initialization vector.
* @return Random byte sequence.
*/
private byte[] createIV() {
Random r = new SecureRandom();
byte[] iv = new byte[16];
r.nextBytes(iv);
return iv;
}
</code></pre>
<p>The clear text data that is supposed to be encrypted will be JSON structures. I'm mostly interested in finding more or less obvious "messups" I have in that code from a security point of view.</p>
<p>If you need access to the complete code, you can access it <a href="https://github.com/Hydrael/pws/tree/java/pws/de/simperium/pws/backend" rel="nofollow">here</a>.</p>
|
[] |
[
{
"body": "<p>The thing that jumps out at me is that you've got an issue with encoding strings. Use <code>getBytes(\"UTF8\")</code> instead of <code>getBytes()</code>. Why? Well, otherwise, the locale of the operating system can affect how a password gets hashed. </p>\n\n<p>I'm going to list possible issues now in no particular order.</p>\n\n<p>You're calling <code>createIV()</code> to find out the IV size. This uses up entropy needlessly. Instead, make a constant called IV_LENGTH and make both the loading functions and <code>createIV()</code> read it.</p>\n\n<p>You probably shouldn't use that particular <code>HEADER_MAGIC</code> constant, since most of the 4 byte value will be zeros.</p>\n\n<p>I don't know what getting a <code>DES3</code> instance is supposed to do. I assume you're after Triple-DES, in which case you could use a <code>DESede</code> instance.</p>\n\n<p><code>// I wish there was a direct equivalent to python's join method in Java :/</code></p>\n\n<p>Me too.</p>\n\n<p><code>if ( headerVersion < MINIMAL_JAVA_COMPATIBLE_HEADER_VERSION ) {</code></p>\n\n<p>As I understand this, it will bail out if the file it's reading is too old. Shouldn't it bail if the file is too <em>new</em>?</p>\n\n<pre><code>//@TODO: nullify byte[] clear, as it contains clear text passphrase, which\n// we don't want to be swapped or debugged\n</code></pre>\n\n<p>Kind of irrelevant, since 1) you keep it as a string in other places, and 2) it's a local variable, so it'll be garbage collected soon.</p>\n\n<p>It looks like your hash function is SHA 512. You should run chain together multiple calls to this (like 10,000 or so), because otherwise, <a href=\"http://thepasswordproject.com/oclhashcat_benchmarking\" rel=\"nofollow\">somebody with consumer hardware</a> can crack a totally random 8 character password with letters, numbers, and symbols in a few days. Using scrypt would be ideal, but clearly that's more difficult to implement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T08:27:35.047",
"Id": "29776",
"Score": "0",
"body": "Thanks for your feedback. All your suggestions seem to make sense, so I'll go ahead and implement them. The MINIMAL_JAVA_COMPATIBLE_HEADER_VERSION has historical reasons, since this project has already evolved a bit. Basically I was always able to migrate input files from older versions of my program to match the current file/header layout. With this switch to Java I won't bother with too old files, since it is very unlikely someone will feed the app with files from an early stage of my project...call it being lazy if you want ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T08:12:55.613",
"Id": "18695",
"ParentId": "18694",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18695",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T06:33:02.613",
"Id": "18694",
"Score": "2",
"Tags": [
"java",
"security",
"cryptography"
],
"Title": "Cipher and passphrase classes using Java cryptography"
}
|
18694
|
<p>This function runs very often. <code>cudaMemcpy</code> is at the start and works very slowly. How can I change this function to avoid this? I already have <code>inputs</code> in device memory.</p>
<pre><code>void OpenNNL::calculateNeuronsOutputsAndDerivatives(double * inputs, double * deviceOutputs, double * deviceDerivatives)
{
int inputsCount = _inputsCount;
double * deviceTemp;
double * deviceInputs;
cudaCall(cudaMalloc ( (void**)&deviceInputs, inputsCount*sizeof(double) ));
cudaCall(cudaMemcpy ( deviceInputs, inputs, inputsCount*sizeof(double), cudaMemcpyDeviceToDevice ));
for(int i=0;i<_layersCount;i++)
{
cudaCall(cudaMalloc((void**)&deviceTemp, _neuronsPerLayerCount[i]*inputsCount*sizeof(double)));
dim3 threadsMul = dim3(BLOCK_SIZE, 1);
int blocksCount = floor((double) _neuronsPerLayerCount[i]*inputsCount / threadsMul.x) + 1;
dim3 blocksMul = dim3(blocksCount, 1);
weighting<<<blocksMul, threadsMul>>>(deviceTemp, deviceInputs, _neuronsInputsWeights, _inputsInPreviousLayers[i], inputsCount, _neuronsPerLayerCount[i]);
cudaCall(cudaFree(deviceInputs));
cudaCall(cudaMalloc((void**)&deviceInputs, _neuronsPerLayerCount[i]*sizeof(double)));
dim3 threadsSum = dim3(BLOCK_SIZE, 1);
blocksCount = floor((double) _neuronsPerLayerCount[i] / threadsSum.x) + 1;
dim3 blocksSum = dim3(blocksCount, 1);
calculateOutputsAndDerivatives<<<blocksSum, threadsSum>>>(deviceOutputs, deviceDerivatives, deviceInputs, deviceTemp, _neuronsBiases, inputsCount, _neuronsPerLayerCount[i], _neuronsInPreviousLayers[i]);
inputsCount = _neuronsPerLayerCount[i];
cudaCall(cudaFree(deviceTemp));
}
cudaCall(cudaFree(deviceInputs));
}
</code></pre>
|
[] |
[
{
"body": "<p>Try to minimaze memory allocations.</p>\n\n<p>Allocate memory for <code>deviceTemp</code> and <code>deviceInputs</code> only once (in the constructor, for example):</p>\n\n<pre><code>cudaCall(cudaMalloc ( (void**)&deviceInputs, some_big_value * sizeof(double) ));\ncudaCall(cudaMalloc((void**)&deviceTemp, some_big_value * sizeof(double)));\n</code></pre>\n\n<p>And in <code>calculateNeuronsOutputsAndDerivatives</code>, reallocate memory only if needed:</p>\n\n<pre><code>if (cur_deviceInputs_size < inputsCount)\n{\n cudaCall(cudaFree(deviceInputs));\n cudaCall(cudaMalloc ( (void**)&deviceInputs, inputsCount*sizeof(double) ));\n cur_deviceInputs_size = inputsCount;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T10:27:00.910",
"Id": "18699",
"ParentId": "18698",
"Score": "5"
}
},
{
"body": "<p>There is some redundancy within the <code>for</code> loop which could be removed:</p>\n\n<pre><code> dim3 dimGrid = dim3(blocksCount, 1, 1);\n dim3 dimBlock = dim3(BLOCK_SIZE, 1, 1);\n\n for (int i = 0; i < _layersCount; i++)\n {\n cudaCall(cudaMalloc((void**)&deviceTemp, ... ));\n\n size_t blocksCount = ...\n\n weighting<<<dimGrid, dimBlock>>>(...);\n\n // no need to call cudaFree on deviceInputs every iteration \n // b/c cudaMalloc will be writing to the same location in device memory\n cudaCall(cudaMalloc((void**)&deviceInputs, ... ));\n\n blocksCount = ...\n\n calcOutputsAndDer<<<dimGrid, dimBlock>>>(...); \n\n // rest same as before\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-11T02:36:08.347",
"Id": "62590",
"ParentId": "18698",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18699",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-11-16T09:31:48.347",
"Id": "18698",
"Score": "4",
"Tags": [
"c++",
"performance",
"memory-management",
"neural-network",
"cuda"
],
"Title": "Calculating neuron outputs and derivatives"
}
|
18698
|
<h2>Definition (Wikipedia):</h2>
<blockquote>
<p>E<strong>x</strong>tensible <strong>A</strong>pplication <strong>M</strong>arkup <strong>L</strong>anguage is a declarative XML-based language developed by Microsoft that is used for initializing structured values and objects.</p>
</blockquote>
<h2>Definition (MSDN):</h2>
<blockquote>
<p>XAML is a declarative markup language. As applied to the .NET Framework programming model, XAML simplifies creating a UI for a .NET Framework application. </p>
</blockquote>
<h2>Sample button:</h2>
<pre><code><Button Content="Click Me"/>
</code></pre>
<p>In C# this would be:</p>
<pre><code>Button btn = new Button();
btn.Content = "Click Me";
//or
var btn = new Button { Content = "Click Me" };
</code></pre>
<h2>Advantages:</h2>
<p>All you can do in XAML can also be done in code but declaring the UI in XAML has some advantages:</p>
<ul>
<li>XAML code is short and clear to read</li>
<li>Separation of designer code and logic</li>
</ul>
<h2>More reading:</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms752059(v=vs.110).aspx" rel="nofollow"><strong>MSDN</strong></a></li>
<li><a href="http://en.wikipedia.org/wiki/Extensible_Application_Markup_Language" rel="nofollow"><strong>Wikipedia</strong></a></li>
<li><a href="http://wpftutorial.net/XAML.html" rel="nofollow"><strong>Introduction to XAML</strong></a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T13:32:22.857",
"Id": "18704",
"Score": "0",
"Tags": null,
"Title": null
}
|
18704
|
Extensible Application Markup Language (XAML) is an XML language used for defining user interfaces in WPF and Silverlight.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T13:32:22.857",
"Id": "18705",
"Score": "0",
"Tags": null,
"Title": null
}
|
18705
|
<p>I'm trying to write a portable CMake script for a simple Qt application. The target platforms are Win and Mac OSX. But as you can see, it's quite a monster already.</p>
<p>Are there any CMake profs? Can you see any essentially wrong approaches used in this script? I bet there are a few.</p>
<pre><code>CMAKE_MINIMUM_REQUIRED( VERSION 2.8.6 )
##################################################################################################################################
MACRO( CHOOSE_QT path )
FILE( GLOB QTROOTS "${path}/bin" )
FIND_PROGRAM( QT_QMAKE_EXECUTABLE NAMES qmake qmake4 qmake-qt4 qmake-mac PATHS ${QTROOTS} )
ENDMACRO( CHOOSE_QT path )
MACRO( ADD_FILES_TO_FILTER rootFilterName rootFilterPath files )
FOREACH( curFile ${files} )
FILE( RELATIVE_PATH curFilter "${CMAKE_CURRENT_SOURCE_DIR}/${rootFilterPath}" "${CMAKE_CURRENT_SOURCE_DIR}/${curFile}" )
FILE( RELATIVE_PATH test "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${curFile}" )
GET_FILENAME_COMPONENT( curFilter ${curFilter} PATH )
SET( curFilter "${rootFilterName}/${curFilter}" )
STRING( REPLACE "/" "\\\\" curFilter ${curFilter} )
SOURCE_GROUP( ${curFilter} FILES ${curFile} )
ENDFOREACH( curFile )
ENDMACRO( ADD_FILES_TO_FILTER rootFilterName rootFilterPath files )
MACRO( TO_RELATIVE_PATHS filePaths )
SET( resPaths "" )
FOREACH( curPath ${${filePaths}} )
FILE( RELATIVE_PATH relPath ${CMAKE_CURRENT_SOURCE_DIR} ${curPath} )
SET( resPaths ${resPaths} ${relPath} )
ENDFOREACH( curPath )
SET( ${filePaths} ${resPaths} )
ENDMACRO( TO_RELATIVE_PATHS filePaths )
MACRO( COPY_TO_BUNDLE resourcePath bundlePath )
LIST( APPEND BUNDLE_COPY_RESOURCES ${resourcePath} )
SET_SOURCE_FILES_PROPERTIES( ${resourcePath} PROPERTIES MACOSX_PACKAGE_LOCATION ${bundlePath} )
ENDMACRO( COPY_TO_BUNDLE )
MACRO( ADD_FRAMEWORK fwname fwpath appname )
TARGET_LINK_LIBRARIES( ${appname} ${fwpath}/${fwname} )
MESSAGE( STATUS "Framework ${fwname} found at ${fwpath}" )
ENDMACRO()
MACRO( ADD_SYSTEM_FRAMEWORK fwname appname )
FIND_LIBRARY( FRAMEWORK_${fwname} NAMES ${fwname} PATHS ${CMAKE_OSX_SYSROOT}/System/Library PATH_SUFFIXES Frameworks NO_DEFAULT_PATH )
if( ${FRAMEWORK_${fwname}} STREQUAL FRAMEWORK_${fwname}-NOTFOUND )
MESSAGE( ERROR ": Framework ${fwname} not found" )
else()
ADD_FRAMEWORK( ${fwname} ${FRAMEWORK_${fwname}} ${appname} )
endif()
ENDMACRO( ADD_SYSTEM_FRAMEWORK )
##################################################################################################################################
# Define project settings
PROJECT( TrackerSoftware )
SET( APP_NAME "TRACKer" )
# Find Qt library
if( WIN32 )
CHOOSE_QT( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/Qt" )
endif( WIN32 )
SET( CMAKE_AUTOMOC TRUE )
FIND_PACKAGE( Qt4 REQUIRED )
# Find Boost library
if( WIN32 )
SET( BOOST_ROOT "cxx/thirdparty/boost" )
elseif( APPLE )
SET( BOOST_ROOT "osx/FRP/vendors/libraries/include/boost" )
endif( WIN32 )
FIND_PACKAGE( Boost REQUIRED )
# Collect all required files for build
FILE( GLOB_RECURSE headers RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "cxx/src/RTCS/include/*.h" )
FILE( GLOB_RECURSE sources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "cxx/src/RTCS/src/*.cpp" )
FILE( GLOB_RECURSE resources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "cxx/src/*.qrc" )
FILE( GLOB_RECURSE win_resources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "cxx/src/*.rc" )
FILE( GLOB_RECURSE forms RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "cxx/src/*.ui" )
SET( thirdparty_sources "cxx/thirdparty/SimpleCrypt/simplecrypt.cpp" )
if( APPLE )
FILE( GLOB_RECURSE mac_sources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "cxx/src/RTCS/src/*.m" )
LIST( APPEND sources ${mac_sources} )
endif( APPLE )
# Preprocess forms
FILE( RELATIVE_PATH buildDir ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} )
QT4_WRAP_UI( form_headers ${forms} )
TO_RELATIVE_PATHS( form_headers )
ADD_FILES_TO_FILTER( "Forms" "${buildDir}/src/RTCS/include" "${form_headers}" )
# Preprocess resources
QT4_ADD_RESOURCES( resources_rcc ${resources} )
TO_RELATIVE_PATHS( resources_rcc )
ADD_FILES_TO_FILTER( "Resources" "${buildDir}" "${resources_rcc}" )
# Mark all sources as ObjectiveC++
if( APPLE )
foreach( curSource ${sources} )
SET_SOURCE_FILES_PROPERTIES( ${curSource} PROPERTIES COMPILE_FLAGS "-x objective-c++" )
endforeach( curSource )
endif( APPLE )
# Set all link libraries directories - it should be specified Before any targets creation
if( WIN32 )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/boost/lib" )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/libtwitcurl/lib/x86" )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/id3lib/lib/x86" )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/curl/curl/lib/lib/x86" )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/log4qt/lib/x86" )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/WinSparkle/lib/x86/$(ConfigurationName)" )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/fervor-auto/lib/$(Configuration)" )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/quazip/lib/$(Configuration)" )
elseif( APPLE )
LINK_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/osx/FRP/vendors/libraries/lib" )
endif( WIN32 )
# Set up Bundle settings for the Mac OSX
if( APPLE )
SET( MACOSX_BUNDLE true )
SET( MACOSX_BUNDLE_SHORT_VERSION_STRING 0.7-beta2 )
SET( MACOSX_BUNDLE_VERSION 0.7-beta2 )
SET( MACOSX_BUNDLE_LONG_VERSION_STRING Version 0.7-beta2 )
#SET( CMAKE_OSX_ARCHITECTURES ppc;i386 ) #Comment out if not universal binary
# Add a bundle icon
SET( MACOSX_BUNDLE_ICON_FILE multimonIcon.icns )
COPY_TO_BUNDLE( "osx/FRP/${MACOSX_BUNDLE_ICON_FILE}" Resources )
# Copy all private frameworks into the bundle
#COPY_TO_BUNDLE( "osx/FRP/vendors/libraries/lib/Sparkle.framework" Frameworks )
#foreach( curFramework ${QT_LIBRARIES} )
#COPY_TO_BUNDLE( "${curFramework}" Frameworks )
#endforeach( curFramework )
# Fixup bundle, copy dynamic libraries into app bundle
SET( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR}/out )
MESSAGE( STATUS "!!! BUNDLE PATH: ${EXECUTABLE_OUTPUT_PATH}/${APP_NAME}.app" )
SET( APPS "\${CMAKE_INSTALL_PREFIX}/${APP_NAME}.app" ) # paths to executables
SET( DIRS "${CMAKE_SOURCE_DIR}/osx/FRP/vendors/libraries/lib" ) # directories to search for prerequisites
INSTALL( CODE "
include(BundleUtilities)
fixup_bundle(\"${APPS}\" \"\" \"${DIRS}\")
")
endif( APPLE )
# Create executable
if( WIN32 )
ADD_EXECUTABLE( Tracker WIN32 ${headers} ${sources} ${form_headers} ${resources_rcc} ${thirdparty_sources} ${win_resources} )
SET_TARGET_PROPERTIES( Tracker PROPERTIES OUTPUT_NAME "tracker" )
SET_TARGET_PROPERTIES( Tracker PROPERTIES COMPILE_FLAGS "/Zc:wchar_t-" )
elseif( APPLE )
ADD_EXECUTABLE( Tracker MACOSX_BUNDLE ${headers} ${sources} ${form_headers} ${resources_rcc} ${thirdparty_sources} ${BUNDLE_COPY_RESOURCES} )
SET_TARGET_PROPERTIES( Tracker PROPERTIES OUTPUT_NAME ${APP_NAME} )
SET( CMAKE_XCODE_ATTRIBUTE_GCC_VERSION "com.apple.compilers.llvm.clang.1_0" )
endif( WIN32 )
# Set filters for project according to its namespaces
ADD_FILES_TO_FILTER( "Headers" "cxx/src/RTCS/include" "${headers}" )
ADD_FILES_TO_FILTER( "Sources" "cxx/src/RTCS/src" "${sources}" )
ADD_FILES_TO_FILTER( "Resources" "cxx/src/RTCS/rc" "${win_resources}" )
ADD_FILES_TO_FILTER( "Thirdparty" "cxx/thirdparty" "${thirdparty_sources}" )
# Set additional include directories
INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_BINARY_DIR} )
INCLUDE_DIRECTORIES( "cxx/src" )
INCLUDE_DIRECTORIES( "cxx/src/RTCS/include" )
INCLUDE_DIRECTORIES( "cxx/thirdparty" )
# Configure Qt
SET( QT_USE_QTNETWORK TRUE )
SET( QT_USE_QTSQL TRUE )
SET( QT_USE_QTSCRIPT TRUE )
SET( QT_USE_QTXML TRUE )
SET( QT_USE_QTWEBKIT TRUE )
INCLUDE( ${QT_USE_FILE} )
ADD_DEFINITIONS( ${QT_DEFINITIONS} )
TARGET_LINK_LIBRARIES( Tracker ${QT_LIBRARIES} )
TARGET_LINK_LIBRARIES( Tracker ${QT_QTMAIN_LIBRARY} )
# Add boost support
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )
TARGET_LINK_LIBRARIES( Tracker ${Boost_LIBRARIES} )
# Add other libs include dirs
INCLUDE_DIRECTORIES( "cxx/thirdparty/SimpleCrypt" )
INCLUDE_DIRECTORIES( "cxx/thirdparty/id3lib/include" )
INCLUDE_DIRECTORIES( "cxx/thirdparty/libtwitcurl" )
INCLUDE_DIRECTORIES( "cxx/thirdparty/curl/curl/include" )
INCLUDE_DIRECTORIES( "cxx/thirdparty/log4qt/include" )
INCLUDE_DIRECTORIES( "cxx/thirdparty/fervor-auto" )
# Add other libs to link
if( WIN32 )
TARGET_LINK_LIBRARIES( Tracker debug "twitcurlD.lib" )
TARGET_LINK_LIBRARIES( Tracker debug "id3libD.lib" )
TARGET_LINK_LIBRARIES( Tracker debug "libcurlD.lib" )
TARGET_LINK_LIBRARIES( Tracker debug "log4qtD.lib" )
TARGET_LINK_LIBRARIES( Tracker optimized "twitcurl.lib" )
TARGET_LINK_LIBRARIES( Tracker optimized "id3lib.lib" )
TARGET_LINK_LIBRARIES( Tracker optimized "libcurl.lib" )
TARGET_LINK_LIBRARIES( Tracker optimized "log4qt.lib" )
TARGET_LINK_LIBRARIES( Tracker "fervor.lib" )
TARGET_LINK_LIBRARIES( Tracker "quazip.lib" )
TARGET_LINK_LIBRARIES( Tracker "Wininet.lib" )
TARGET_LINK_LIBRARIES( Tracker "ws2_32.lib" )
TARGET_LINK_LIBRARIES( Tracker "winmm.lib" )
TARGET_LINK_LIBRARIES( Tracker "wldap32.lib" )
TARGET_LINK_LIBRARIES( Tracker "Shell32.lib" )
TARGET_LINK_LIBRARIES( Tracker "Version.lib" )
elseif( APPLE )
TARGET_LINK_LIBRARIES( Tracker "libiconv.a" )
TARGET_LINK_LIBRARIES( Tracker "libid3.a" )
TARGET_LINK_LIBRARIES( Tracker "liblibtwitcurl.a" )
TARGET_LINK_LIBRARIES( Tracker "libLog4Qt.a" )
TARGET_LINK_LIBRARIES( Tracker "libz.a" )
TARGET_LINK_LIBRARIES( Tracker "libboost_date_time.a" )
TARGET_LINK_LIBRARIES( Tracker "libboost_iostreams.a" )
TARGET_LINK_LIBRARIES( Tracker "libboost_serialization.a" )
TARGET_LINK_LIBRARIES( Tracker "libboost_thread-mt.a" )
TARGET_LINK_LIBRARIES( Tracker "curl" )
# Add frameworks
ADD_FRAMEWORK( "Sparkle.framework" "${CMAKE_CURRENT_SOURCE_DIR}/osx/FRP/vendors/libraries/lib" Tracker )
# Add system frameworks
ADD_SYSTEM_FRAMEWORK( Foundation Tracker )
ADD_SYSTEM_FRAMEWORK( CoreFoundation Tracker )
ADD_SYSTEM_FRAMEWORK( AppKit Tracker )
endif( WIN32 )
# Add defines
ADD_DEFINITIONS( -DQUAZIP_STATIC )
ADD_DEFINITIONS( -DBUILDING_LIBCURL )
ADD_DEFINITIONS( -DID3LIB_LINKOPTION=1 )
ADD_DEFINITIONS( -DUNICODE -D_UNICODE ) #enable unicode support
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T01:24:52.503",
"Id": "57896",
"Score": "0",
"body": "Would [Win x64] fall under the `Win32` branch?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T09:54:25.647",
"Id": "57921",
"Score": "0",
"body": "@retailcoder as i remember, yes, it would and it does. those are selectors among platforms like windows, linux and mac."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:06:50.943",
"Id": "77610",
"Score": "0",
"body": "Isn't there a tool called qmake that people normally use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-19T17:46:54.887",
"Id": "88291",
"Score": "0",
"body": "I've worked with a CMake file that invoked `FIND_PACKAGE (Qt4 4.8.0 COMPONENTS QtCore QtNetwork REQUIRED)` and `INCLUDE(${QT_USE_FILE})` early in the script, invoked `QT4_WRAP_CPP` once, and included `${QT_LIBRARIES}` as one of the input arguments of `TARGET_LINK_LIBRARIES`. Other than that, it seems not to need to mention Qt, in particular there is nothing like `CHOOSE_QT( \"${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty/Qt\" )`. But perhaps this depends on how you install Qt."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T08:38:56.263",
"Id": "88360",
"Score": "0",
"body": "@DavidK we don't install Qt, we keep several repos of different Qt builds and use them as subrepos or just clone somewhere and set env variables for paths. So, all scripts were made to support that scheme. We do it because we have various projects that use different Qts and we don't wanna port some old projects to a new Qt, because it occasionally introduces bugs. You can read about all that mess in my question about selecting a Qt instance on stackoverflow right here http://stackoverflow.com/questions/12511370/how-to-include-a-certain-qt-installation-using-cmake"
}
] |
[
{
"body": "<p>My CMake-fu is a bit rusty - probably as old as this question -, but I still see some things that could be trivially improved:</p>\n\n<ul>\n<li><p>CMake doesn't require <code>else()</code> and <code>endif()</code> to contain the original <code>if()</code> expression anymore. It seems that this restriction disappeared a long time ago, so you can simplify your code by leaving empty <code>else()</code> and <code>endif()</code> expressions. Your indentation already does a great job to document where an <code>if()</code> is ending.</p></li>\n<li><p>The remark above also applies for <code>endmacro()</code> and <code>endforeach</code> and more generally any <code>endxxx()</code> instruction. Note that it works even with your version: you left the <code>endmacro()</code> empty for <code>ADD_FRAMEWORK</code>.</p></li>\n<li><p>Your capitalization is not consistent. You sometimes use <code>FOREACH</code> while you sometimes use <code>foreach</code>. I know that CMake is not really case-sensitive, but being consistent doesn't hurt and helps case-sensitive search in code editors.</p></li>\n<li><p>There are too many occurrences of <code>\"${CMAKE_CURRENT_SOURCE_DIR}/cxx/thirdparty</code>. You should define a <code>${THIRD_PARTY_DIR}</code> variable or something to having repeating the full path over and over. It will avoid many problems if the path changes. It seems that there isn't a portable way to make it work for both <code>WIN32</code> and <code>APPLE</code>, but doing it for <code>WIN32</code> would already help.</p></li>\n<li><p>You should remove commented out code. If you need an old version of your code, you should simply rely on revision control software. If you have comments like \"comment out to do something\", it generally means that the \"something\" in question should be a command line option.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-19T19:41:26.540",
"Id": "74202",
"ParentId": "18706",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "74202",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T14:40:28.503",
"Id": "18706",
"Score": "23",
"Tags": [
"c++",
"makefile",
"portability"
],
"Title": "Portable CMake script"
}
|
18706
|
<p>I am using this query to generate a conversation stream between user 184 and 192- </p>
<pre><code>SELECT events.event_time, messages . *
FROM events , messages
WHERE events.global_id=messages.global_ref_id AND
(messages.to =184 AND messages.from =192) OR
events.global_id=messages.global_ref_id AND
(messages.to =192 AND messages.from =184) AND
messages.global_ref_id < 495
ORDER BY `messages`.`global_ref_id` ASC
</code></pre>
<p>This query is working good for generating conversation between two users.
Can you help me with converting this query to something more readable. Because I believe it is just a workaround and will cause some problems in future.
Schema of messages table</p>
<pre><code>Field Type
global_ref_id int(12)
to int(12)
from int(12)
message text
status int(1)
viewed int(1)
</code></pre>
<p>where global_ref_id is foreign key.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T09:37:13.650",
"Id": "29802",
"Score": "3",
"body": "Please try making your title more descriptive. As it stands, users have no idea what this question contains."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T09:39:05.970",
"Id": "29803",
"Score": "0",
"body": "What exactly do you not like about the query? It's perfectly correct. The only thing I would do is pull the `global_ref_id` check out and do it once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T09:51:06.143",
"Id": "29804",
"Score": "0",
"body": "Actually In this query if I want to pull only those messages which have global_id greater than say 455 then what should I put the query."
}
] |
[
{
"body": "<p>I would use a syntax like this:</p>\n\n<pre><code>SELECT events.event_time, messages .*\nFROM events , messages\nWHERE events.global_id=messages.global_ref_id \nAND ((messages.to = 184 AND messages.from = 192) OR (messages.to = 192 AND messages.from = 184))\nAND messages.global_ref_id < 495\nORDER BY `messages`.`global_ref_id` ASC\n</code></pre>\n\n<p>or use a <code>left outer join</code> instead:</p>\n\n<pre><code>SELECT e.event_time, m.*\nFROM events e left outer join messages m ON e.global_id=m.global_ref_id \nWHERE ((m.to = 184 AND m.from = 192) OR (m.to = 192 AND m.from = 184))\nAND m.global_ref_id < 495\nORDER BY m.`global_ref_id` ASC\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T09:57:26.360",
"Id": "29805",
"Score": "0",
"body": "Thanks for this.This worked to get results greater than 495."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T09:48:11.437",
"Id": "18710",
"ParentId": "18709",
"Score": "0"
}
},
{
"body": "<p>I prefer using JOIN...ON, clarifying an intention of priority of OR and AND phrase.</p>\n\n<pre><code>SELECT\n events.event_time,\n messages . *\nFROM\n events\n JOIN messages ON events.global_id = messages.global_ref_id\nWHERE\n ((messages.to =184 AND messages.from =192)\n OR (messages.to =192 AND messages.from =184))\n AND messages.global_ref_id < 495\nORDER BY\n messages.global_ref_id ASC\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T10:01:03.953",
"Id": "18711",
"ParentId": "18709",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18710",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T09:35:42.060",
"Id": "18709",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "How should I format my code to make it easier to read and understand in the future"
}
|
18709
|
<p>CMake is a cross-platform, open-source build system. It generates native makefiles and project files that can be used from the command line or integrated development environment of your choice.</p>
<h2>Official</h2>
<ul>
<li><a href="http://www.cmake.org/" rel="nofollow">Homepage</a> </li>
<li><a href="http://www.cmake.org/cmake/help/documentation.html" rel="nofollow">Documentation</a></li>
<li><a href="http://www.cmake.org/Wiki/CMake" rel="nofollow">Community Wiki</a></li>
<li><a href="http://www.cmake.org/Wiki/CMake_FAQ" rel="nofollow">FAQ</a></li>
<li><a href="http://www.cmake.org/mailman/listinfo/cmake" rel="nofollow">Mailing List</a></li>
</ul>
<h2>Quick Start / Howtos</h2>
<ul>
<li><a href="http://playcontrol.net/ewing/screencasts/getting_started_with_cmake_.html" rel="nofollow">Getting Started With CMake Screencasts</a></li>
<li><a href="http://www.cmake.org/cmake/help/runningcmake.html" rel="nofollow">Running CMake</a></li>
<li><a href="http://www.cs.swarthmore.edu/~adanner/tips/cmake.php" rel="nofollow">CMake Howto</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T16:01:36.960",
"Id": "18713",
"Score": "0",
"Tags": null,
"Title": null
}
|
18713
|
CMake is a cross-platform, open-source build system. It generates native makefiles and project files that can be used from the command line or integrated development environment of your choice.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T16:01:36.960",
"Id": "18714",
"Score": "0",
"Tags": null,
"Title": null
}
|
18714
|
<p>I've made a python script to properly organise D&D monster stats in a directory. The script brings up the stats as instance variables of a Monster (class) instance.</p>
<p>For those unfamiliar with the game, keeping track of monsters (to me at least) is cumbersome and prone to many dead trees. You have to flip through the Monster Manual to find the monster, write down any change done to it (like health) on a piece of paper, keep track of the initiative order, different encounters...</p>
<p>There is a lot to do, so I decided to use technology to my advantage. I have folders set up under the Monsters folder. In each folder is a subfolder (the same types across all of them). In each subfolder is a .txt document with the stats (as dictated by the book) for each monster. </p>
<ul>
<li>Main Types = Animate, Beast, Humanoid, Magical Beast</li>
<li>Sub Types = Abberant Elemental Fey Immortal Natural Shadow</li>
</ul>
<p>Each text document is set up like the following example:</p>
<pre><code>Example Monster # This is up here, and skipped, so I keep track of each one easily without having to remember to look at the name of the file.
HP = 50
Initiative = 5
Senses = [5, 'Darkvision'] # In auto, this is Perception and Vision combined
Defence = {"AC" : 5, "Fortitude" : 4, "Reflex" : 6, "Will" : 7}
Saving_Throw = 2
Speed = 6
AP = 1 # Action Points
Attacks = {'An attack that hurts the opponent and does permanent damage to its armour' : 'Example.alterstat({"HP" : -5, "Defence[0] : -3})'
</code></pre>
<p>Here is my entire Monster class, plus some unbound functions. What I want to know is if any of the functions can be improved (especially the <code>__init__</code>, <code>addmonster</code>, and <code>LoadAll</code>)</p>
<pre><code> import os
types = 'Animate Beast Humanoid Magical_Beast'.split()
sub_types = 'Abberant Elemental Fey Immortal Natural Shadow'.split()
LoadedMonsters = []
class Monster:
def __init__(self, monster, LoadedMonsters = LoadedMonsters):
'''Checks if monsters is defined. If it is defined, sets class attributes to be the monster's as decided in Monsters.txt. If it is already loaded in LoadedMonsters, makes a copy'''
self.name = monster.capitalize()
self.isdead = False
monstercheck = monsterfind(self.name)
if monstercheck != False:
with open(monstercheck, 'r') as monstercheck:
print monstercheck.next()
for stat in monstercheck:
print stat[:-1] # Show what stats are loaded
var, value = stat.split('=')
var, value = val.strip(), value.strip()
try:
value = eval(value) # Fixes non-string values
except:
pass
setattr(self, var, value)
self.Bloodied = self.HP / 2
AllMonsters = open('Monsters.txt', 'w+') # List (.txt) of all monsters
AllMonsters.read() # Get to end of text
AllMonsters.write(self.name)
AllMonsters.close()
monstercheck.close()
LoadedMonsters += [self.name] # A list of all loaded monsters
print 'Monster loaded'
else: # If can't find the monster in the folders
print '{} Not found, add it?'.format(self.name)
if raw_input('Y/n\n').capitalize() == 'Y':
self.addmonster()
self = Monster(self)
else:
self.name = 'UNKNOWN'
def setMonsterLevel(self, monster, level):
"Changes the given monster's level to the given value."
if monster not in LoadedMonsters:
print 'Monster not loaded'
raise NotImplementedError # I'll get to it, it's harder then it seems
def attack(self, monsters, changes, buff = None):
'''Takes a list of targets [Variable names!],a dictionary of stats and values w/ the stats as the key, and applies it to the list of targets. Optional parametre, buff, can be applied at the end as a dictionary'''
for monster in monsters:
for change in changes:
monster.alterstat( {change : changes.get(change)} )
if buff is not None:
self.alterstat(buff.keys()[0], buff.get(buff.keys()[0]))# Messy way of saying get key and value of dictionary
def monsterfind(name): # For use in __init__
'''name = monster Return folder path if monster exists, False otherwise'''
monster = name + '.txt'
for folder in types:
for subfolder in sub_types:
path = os.path.abspath('Monsters' + '\\{}\\{}\\{}'.format(
folder, subfolder, monster))
if os.path.exists(path):
return path
return False
def addmonster(name): # Bit wordy
'''Name = string representation of a monster name makes monster name'''
print 'Checking if available'
if os.path.exists(name): # Can't have names across sub folders
print '{} is taken!'.format(name)
name = raw_input('Choose a different name: ')
addmonster() # Start again
print 'Name available!'
while True:
option = raw_input(
'Choose the main folder:{}\n'.format(types)).capitalize()
if option in types:
while True:
sub_option = raw_input(
'Choose a sub-folder {}\n'.format(sub_types)).capitalize()
if sub_option in sub_types:
newmonster = open(
os.path.abspath(
'Monsters') + '\\{}\\{}\\{}.txt'.format(
option, sub_option, name), 'w')
break
break
if raw_input('Automatic data entry, or Manual? \n').capitalize() == ('Manual'):
print '''Enter your information. (Press enter for every line, press enter on a blank line to finish)'''
newmonster.write(name + ':\n')
while True:
newline = raw_input('>') + '\n' # Starts on newline, gives last
if newline == '\n': # a new line
break
newmonster.write(newline)
else:
while True:
Information = []
print '''Follow the steps below. If you do not want to add a value then leave it blank. This will NOT be saved until you confirm it at the end'''
print "Enter a number for the monster's health"
HP = 'HP = ' + raw_input('HP = ')
Information.append(HP)
print "Enter a # bonus (or penalty) for the monster's Initiative"
print "0 if no bonus/penalty"
Initiative = 'Initiative = ' + raw_input('Initiative = ')
Information.append(Initiative)
print "Enter a # bonus (or penalty) for the monster's perception"
Senses = list(raw_input('Perception = '))
print "Enter the vision type of the monster"
print "I.E: Darkvision, Normal, Low-Light, etc."
Senses.append(raw_input('Vision = '))
Senses = 'Sense =' + str(Senses)
Information.append(Senses)
print 'Enter the following defence stats as numbers:'
Defence = 'Defence = ' + str({
"AC" : input('AC = '),
"Fortitude": input('Fortitude = '),
"Reflex" : input('Reflex = '),
"Will" : input('Will = ')
})
Information.append(Defence)
print '''Enter a # bonus (or penalty) for the monster's Saving Throw'''
Saving_Throw = 'Saving Throw = ' + raw_input('Saving Throw = ')
Information.append(Saving_Throw)
print "Enter the value (not bonus) for speed. It is usually 6"
Speed = 'Speed = ' + raw_input('Speed = ')
Information.append(Speed)
print "Enter how many AP's (Action Points) the monster has"
AP = 'AP = ' + raw_input('AP = ')
Information.append(AP)
print 'Monster Stats:'
print
# Attacks will be added in GUI (if I do that): Too complicated for user here
for stat in Information:
print stat
print 'Verify that this is correct'
while True:
print 'Y/N\n'
answer = raw_input('>').capitalize()
if answer == 'Y':
newmonster.write(name + '\n')
AllMonsters = open('All Monsters.txt', 'w+')
AllMonsters.read()
AllMonsters.write(name + '\n')
AllMonsters.close()
for stat in Information:
newmonster.write(str(stat) + '\n')
newmonster.close()
return
elif answer == 'N':
'Press enter to start over'
newmonster.close()
raw_input()
continue
def LoadAll(): # This should probably do the last step too...
'''Opens Monsters.txt, a list of all monster names, and returns a list of instances of Monster to be loaded by iterating exec() it'''
AllMonsters = open(os.path.abspath('Monsters\\All Monsters.txt'), 'r')
for monster in AllMonsters:
yield '{0} = Monster("{0}")'.format(monster[:-1]) # -1 cause \n function
# Returns generator to load all monsters as instances of Monster class
</code></pre>
<p>If there are any mistakes let me know, as I had to rewrite the whole thing in spaces during a class period (curse bad programming habits!)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T18:28:03.683",
"Id": "29812",
"Score": "0",
"body": "You may want to adopt a consistent code style: the obvious suggestion for this is [PEP8](http://www.python.org/dev/peps/pep-0008/). The [pep8 - Python style guide checker](http://pypi.python.org/pypi/pep8/) can help you with that task."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T02:03:25.813",
"Id": "29822",
"Score": "0",
"body": "Have you thought about open sourcing this and putting it on github?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T02:16:36.057",
"Id": "29826",
"Score": "0",
"body": "actually yes :P. Of course, I (might) take this further. I.E: actually simulate a battle. This would be useful (in my opinion) because I can 1) Make the (arguably) most interesting thing about a table-top game quicker and easier and 2) I can test exactly WHAT you need to defeat Orcus"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T04:51:05.347",
"Id": "29843",
"Score": "0",
"body": "@Nick by virtue of Preston placing it on this site, it's now released by its author under the creative commons license. That's a pretty open license. :) http://codereview.stackexchange.com/faq#editing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T05:11:26.030",
"Id": "29844",
"Score": "0",
"body": "@corsiKa, sure, but to run this, you'd need to copy+paste all the files out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T05:12:39.897",
"Id": "29845",
"Score": "2",
"body": "@PrestonCarpenter, my advice is release early and often."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T05:28:51.610",
"Id": "29847",
"Score": "0",
"body": "Would storing everything in say an XML file be easier than multiple folders and files?"
}
] |
[
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>What you are doing here is <em>creating and querying a persistent database</em>, so it's a good idea to use an existing relational database rather than trying to implement your own in an ad-hoc fashion.</p>\n\n<p>In particular, with a relational database you can issue <em>queries</em> (\"select a chaotic evil monster with challenge rating 2\"). Queries are going to be a pain to write if you pursue your current path of having lots of small text files containing assignments.</p>\n\n<p>Another advantage of using a relational database is that you get to learn how to use and program relational databases. Time spent on this won't be wasted.</p>\n\n<p>See section 2 below for an example of how you might go about this, using Python's built-in <a href=\"http://docs.python.org/2/library/sqlite3.html\" rel=\"nofollow\"><code>sqlite3</code></a> module.</p></li>\n<li><p>Your constructor function (<code>Monster.__init__</code>) does two different jobs: if the monster already exists in your database, it loads it, but if it doesn't exist, it prompts the user interactively to create it. This kind of dual-use method is usually a bad idea: it's better to separate the two uses into two methods (this makes the code easier to read, and is more flexible since you can pick which method you actually want).</p>\n\n<p>There could be several reasons why a monster can't be found (e.g. the program is being run in the wrong directory) and you don't always want to be prompted to create it.</p></li>\n<li><p>Using <code>eval(value)</code> is a bad idea because <code>value</code> is untrusted. It could contain code that you'd really rather not run. See \"<a href=\"http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html\" rel=\"nofollow\">Eval really is dangerous</a>\" by Ned Batchelder.</p></li>\n<li><p>You write <code>self.addmonster()</code> in one place. This should be <code>addmonster(name)</code> (or else <code>addmonster</code> should be made a method of the <code>Monster</code> class).</p></li>\n<li><p>The docstring for <code>Monster.__init__</code> says \"If it is already loaded in LoadedMonsters, makes a copy\", but this isn't true.</p></li>\n<li><p>The pathname code is Windows-specific and might not work on other operating systems. Python provides the <a href=\"http://docs.python.org/2/library/os.path.html\" rel=\"nofollow\"><code>os.path</code></a> module for manipulating pathnames in a platform-independent way.</p></li>\n<li><p>There's no input validation.</p></li>\n<li><p>You use <code>setattr</code> to update the attributes of the <code>Monster</code> object. This means that the attributes share the same namespace as the methods. So for example if the monster database contains an <code>attack</code> statistic, then this will overwrite the monster's <code>attack</code> method. It's probably best to keep the statistics in their own namespace, except for a few statistics that you refer to frequently.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>Here's some code that shows how you might start storing your data in table in a SQLite relational database, and how you might go about validating user input.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections\nimport itertools\nimport random\nimport re\nimport readline\nimport sqlite3\n\n# Input validation functions.\ndef validate_integer(s):\n return int(s)\n\ndef validate_positive(s):\n s = int(s)\n if s <= 0: raise ValueError('not positive')\n return s\n\ndef validate_name(s):\n if not s: raise ValueError('empty string')\n return s\n\nDICE_RE = re.compile(r'([1-9]\\d*)d([1-9]\\d*)([+-]\\d+)?$')\n\ndef validate_dice(s):\n if not DICE_RE.match(s): raise ValueError('bad dice description')\n return s\n\ndef roll_dice(s):\n \"\"\"\n Roll dice according to the description in `s` (e.g. \"2d6+1\") and\n return their sum.\n \"\"\"\n m = DICE_RE.match(s)\n n, d, bonus = int(m.group(1)), int(m.group(2)), int(m.group(3) or '0')\n return sum(1 + random.randrange(d) for _ in range(n)) + bonus\n\nALIGNMENTS = [\n 'lawful good', 'neutral good', 'chaotic good',\n 'lawful neutral', 'neutral', 'chaotic neutral',\n 'lawful evil', 'neutral evil', 'chaotic evil',\n]\n\ndef validate_alignment(s):\n if not s in ALIGNMENTS: raise ValueError('bad alignment')\n return s\n\n# Monster statistics.\nStat = collections.namedtuple('Stat', 'stat sql desc validator advice'.split())\nSTATS = [\n # Stat SQL Desc Validator Advice\n Stat('name', 'TEXT UNIQUE', \"name\", validate_name, 'a string'),\n Stat('hitdice', 'TEXT', \"hit dice\", validate_dice, 'like \"2d6+1\"'),\n Stat('armour', 'INTEGER', \"armour class\", validate_integer, 'an integer'),\n Stat('challenge', 'INTEGER', \"challenge rating\", validate_positive, 'a positive integer'),\n Stat('alignment', 'TEXT', \"alignment\", validate_alignment, 'e.g. \"chaotic evil\"'),\n]\n\nclass MonsterDB(object):\n \"\"\"\n Interface to the monster database.\n \"\"\"\n def __init__(self, database = 'monsters.db'):\n \"\"\"\n Connect to `database`, creating it if it doesn't already exist.\n \"\"\"\n self.conn = sqlite3.connect(database)\n self.conn.row_factory = sqlite3.Row\n self.execute('CREATE TABLE IF NOT EXISTS monster ({})'\n .format(','.join('{0.stat} {0.sql}'.format(stat)\n for stat in STATS)))\n self.conn.commit()\n\n def all(self):\n \"\"\"\n Generate the names of all monsters found in the database.\n \"\"\"\n for name, in self.execute('SELECT name FROM monster').fetchall():\n yield name\n\n def execute(self, *args, **kwargs):\n \"\"\"\n Execute a database query and return a cursor.\n \"\"\"\n c = self.conn.cursor()\n c.execute(*args, **kwargs)\n return c\n\n def exists(self, name):\n \"\"\"\n Return True iff a monster with the given name exists in the\n database.\n \"\"\"\n c = self.execute('SELECT EXISTS(SELECT * FROM monster WHERE name=?)',\n (name,))\n return bool(c.fetchone()[0])\n\n def load(self, name):\n \"\"\"\n Load the monster with the given name from the database and\n return it as a new Monster object. If it does not exist, raise\n KeyError.\n \"\"\"\n if not self.exists(name):\n raise KeyError(\"No such monster: {}\".format(name))\n c = self.execute('SELECT * FROM monster WHERE name = ?', (name,))\n return Monster(**c.fetchone())\n\n def update(self, **kwargs):\n \"\"\"\n Update some stats for a monster (creating it if it doesn't exist).\n \"\"\"\n if 'name' not in kwargs:\n raise ValueError(\"missing name\")\n keys, values = zip(*kwargs.items())\n query = ('INSERT OR REPLACE INTO monster ({}) VALUES ({})'\n .format(','.join(keys), ','.join(('?',) * len(keys))))\n self.execute(query, values)\n self.conn.commit()\n\n def input(self, stat, value = None):\n \"\"\"\n Input statistic `stat`, with default `value`.\n \"\"\"\n if value:\n prompt = \"{0.desc} ({0.advice}; default: {1}) > \".format(stat, value)\n else:\n prompt = \"{0.desc} ({0.advice}) > \".format(stat)\n while True:\n try:\n v = raw_input(prompt)\n if not v and value:\n return value\n return stat.validator(v)\n except ValueError as e:\n print(e)\n\n def update_interactively(self):\n \"\"\"\n Update a monster interactively (creating it if doesn't exist).\n \"\"\"\n action = 'create'\n assert STATS[0].stat == 'name'\n name = self.input(STATS[0])\n if self.exists(name):\n action = 'update'\n c = self.execute('SELECT * FROM monster WHERE name = ?', (name,))\n stats = dict(c.fetchone())\n else:\n stats = dict(name = name)\n for stat in STATS[1:]:\n stats[stat.stat] = self.input(stat, stats.get(stat.stat))\n desc_width = max(len(stat.desc) for stat in STATS)\n value_width = max(len(str(stats[stat.stat])) for stat in STATS)\n print('\\n{:{}} {}'.format('STAT', desc_width, 'VALUE'))\n print('{:-<{}} {:-<{}}'.format('', desc_width, '', value_width))\n for stat in STATS:\n print('{:{}} {}'.format(stat.desc, desc_width, stats[stat.stat]))\n if raw_input(\"OK to {}? > \".format(action))[0].upper() != 'Y':\n print('Abandoned.')\n else:\n self.update(**stats)\n\nclass Monster(object):\n def __init__(self, **kwargs):\n self.stat = kwargs\n self.name = kwargs['name']\n self.hp = roll_dice(kwargs['hitdice'])\n\n def __repr__(self):\n return '<Monster {} HP:{}>'.format(self.name, self.hp)\n</code></pre>\n\n<h3>3. Example interaction</h3>\n\n<pre class=\"lang-default prettyprint-override\"><code>>>> db = MonsterDB()\n>>> db.update_interactively()\nname (a string) > iron golem\nhit dice (like \"2d6+1\") > 18d10+30\narmour class (an integer) > 30\nchallenge rating (a positive integer) > 13\nalignment (e.g. \"chaotic evil\") > neutral\n\nSTAT VALUE\n---------------- ----------\nname iron golem\nhit dice 18d10+30\narmour class 30\nchallenge rating 13\nalignment neutral\nOK to create? > yes\n>>> db.load('iron golem')\n<Monster iron golem HP:122>\n>>> _.stat\n{'hitdice': u'18d10+30', 'challenge': 13, 'armour': 30, 'alignment': u'neutral', 'name': u'iron golem'}\n</code></pre>\n\n<p>And in SQL you can issue queries:</p>\n\n<pre class=\"lang-default prettyprint-override\"><code>sqlite> select * from monster where challenge = 1;\nname hitdice armour challenge alignment \n------------ ---------- ---------- ---------- ------------\ngoblin 1d8+1 15 1 neutral evil\nhobgoblin 1d8+2 15 1 lawful evil \ngiant bee 3d8 14 1 neutral \nspider swarm 2d8 17 1 neutral \n</code></pre>\n\n<h3>4. Looking ahead</h3>\n\n<p>If you follow this implementation strategy, you'll find eventually that even with a relational database, it becomes fiddly to maintain the mapping between Python and the database. Each time you add a new stat you have to update the database schema. And the mapping will get more complex: for example you will probably want to put special powers/attacks into their own database table.</p>\n\n<p>When you get to this point you'll probably want to look at <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow\">Object-Relational Mapping</a> (ORM) toolkits like <a href=\"http://www.sqlalchemy.org/\" rel=\"nofollow\">SQLAlchemy</a>. (But I think it's worth learning to use plain old SQL first: you can't properly understand ORM unless you understand both the Object and the Relational side of the mapping.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T21:54:56.583",
"Id": "30077",
"Score": "0",
"body": "Thank you very much for the time you put in to your answer. I feared that this 'question' would go unanswered as I want to do some fun things while learning in Python for a while before I move on to Java. I will look more in depth in changing these things tomorrow. Thank you again for such a great response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T19:55:20.700",
"Id": "30142",
"Score": "0",
"body": "+1, though I feel your revised Monster class has too many responsibilities. Perhaps `Monster` should be decoupled from database, and there could be a separate `MonsterDb` class that can store and retrieve Monsters to/from database?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T11:40:42.367",
"Id": "30162",
"Score": "0",
"body": "@Janne: Good point! I re-organized the code along the lines you suggested."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T17:51:23.913",
"Id": "18848",
"ParentId": "18717",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "18848",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T16:37:31.903",
"Id": "18717",
"Score": "10",
"Tags": [
"python",
"object-oriented"
],
"Title": "D&D Monster Organiser"
}
|
18717
|
<p>I just started coding in Objective-C and would like to know if my simple implementation of a Stack is acceptable & what ways would you improve the Stack code, or the Main code? i'm curious of things such as (but not limited to):</p>
<ol>
<li>formatting</li>
<li>edge cases</li>
<li>run time (like one part where try to manipulate strings in <code>description</code>)</li>
<li>general good practice</li>
<li>memory management practices (i'm using ARC in this code)</li>
</ol>
<p>Stack.h:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface Stack : NSObject
-(void)push:(id)obj;
-(id)pop;
-(NSUInteger)size;
-(id)peek;
-(BOOL)isEmpty;
@end
</code></pre>
<p>Stack.m file:</p>
<pre><code>#import "Stack.h"
@implementation Stack{
NSMutableArray *stack;
}
-(id)init{
self = [super init];
if(self!=nil){
stack = [[NSMutableArray alloc] init];
}
return self;
}
-(void)push:(id)obj{
[stack addObject:obj];
}
-(id)pop{
id lastObj = [stack lastObject];
[stack removeLastObject];
return lastObj;
}
-(NSUInteger)size{
return stack.count;
}
-(id)peek{
return [[stack lastObject] copy];
}
-(BOOL)isEmpty{
return stack.count == 0;
}
-(NSString *)description{
NSMutableString *result = [[NSMutableString alloc] initWithString:@"["];
for (id s in stack) {
[result appendFormat:@"%@, ",[s description]];
}
if (stack.count>0) {
result = [[result stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]] mutableCopy];
}
[result appendString:@"]"];
return result;
}
@end
</code></pre>
<p>Lastly, this is how i verify my code is "working":</p>
<pre><code>#import <Foundation/Foundation.h>
#import "Stack.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Stack *s1 = [[Stack alloc] init];
assert([s1 size]==0);
assert([s1 pop]==nil);
assert([s1 peek]==nil);
assert([s1 isEmpty]==YES);
NSLog(@"first set of tests passed");
[s1 push:[NSNumber numberWithInt:0]];
[s1 push:[NSNumber numberWithInt:3]];
[s1 push:[NSNumber numberWithInt:5]];
NSLog(@"%@",[s1 description]);
assert(![s1 isEmpty]);
assert(s1.size == 3);
assert([[s1 peek] isEqual:[NSNumber numberWithInt:5]]);
assert([[s1 pop] isEqual:[NSNumber numberWithInt:5]]);
assert(s1.size == 2);
assert([[s1 pop] isEqual:[NSNumber numberWithInt:3]]);
assert(![[s1 pop] isEqual:[NSNumber numberWithInt:3]]);
assert([s1 pop] == nil);
assert(s1.isEmpty);
NSLog(@"second set of tests passed");
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>-(id)pop{\n id lastObj = [stack lastObject];\n [stack removeLastObject];\n return lastObj;\n}\n</code></pre>\n\n<p>Not sure if you are using ARC, but without ARC this is a potential use-after-free bug. If you are not using ARC you should consider:</p>\n\n<pre><code>-(id)pop{\n id lastObj = [stack lastObject];\n\n if (lastObj) // < -- now checking for nil\n {\n [[lastObj retain] autorelease]; // < -- this line added\n\n [stack removeLastObject];\n }\n return lastObj;\n}\n</code></pre>\n\n<p>(This also assumes that the objects in the stack are <code>NSObject</code>s, but I believe <code>NSMutableArray</code> makes the same assumption...)</p>\n\n<p>This bumps the ref count up so that the next line (which will cause the <code>NSMutableArray</code> to release its reference to the object) does not end up deallocating the object.</p>\n\n<p><b>Update on second reading:</b></p>\n\n<p>Also, what do you do when <code>lastObj</code> is <code>nil</code> (i.e. too many <code>pop</code>s)? Doesn't seem like you've handled that case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T01:23:00.647",
"Id": "29818",
"Score": "0",
"body": "sorry, forgot to mention i'm using ARC, the edit is in now. Oh, and when you do `[[lastObj retain] autorelease];` in non-ARC code, do you have to also manually release the `lastObj` later? like... in the `dealloc`? or where?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T01:32:01.263",
"Id": "29819",
"Score": "0",
"body": "@DavidT. - `retain` increments the count, then `autorelease` will set it up to be decremented later. (When the pool is drained, usually inside the run loop.) When the count reaches 0 (inside `release`) then `dealloc` is called."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T00:45:58.340",
"Id": "18722",
"ParentId": "18718",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T19:51:45.883",
"Id": "18718",
"Score": "2",
"Tags": [
"objective-c",
"stack"
],
"Title": "Objective-C Stack implementation"
}
|
18718
|
<p>I have a project for solving Diophantine equations, where a solution exists if</p>
<p>$$A^5 + B^5 + C^5 + D^5 + E^5 = F^5$$</p>
<p>where \$0 < A <= B <= C <= D <=E <= F <= N\$</p>
<p>The program will take an input N and first generate all values from 1 to \$N^5\$. Then it will get all possible sum values of \$A^5 + B^5 + C^5\$ and store the sum in an doubly linked list. Then it gets the possible sum values of \$F^5 - (D^5 + E^5)\$ and store that into a separate list. When creating the list, it also does a check to make sure the condition also holds (so like \$A^5 <= B^5\$ etc).</p>
<p>It will then do quicksort on both lists and then compare both values. During comparison, there is also a check in place to make sure that the value for \$C <= D\$.</p>
<p>So far my code is running, however it isn't running at optimal performance. It takes a considerable amount of time to find a solution for large \$N\$ values. The code should be running at a time complexity of \$O(N^3LogN)\$. Can anyone please give me some hints or suggestions as to how I can improve my current code?</p>
<pre><code>import java.util.Scanner;
import java.lang.Math;
public class EquationSolver {
private long[] values;
private long numVal;
private long sum1, sum2;
private long a, b, c, d, e, f;
private DLList list1, list2;
public EquationSolver(String command) {
numVal = Integer.parseInt(command);
values = new long[(int) numVal];
Node refNode1 = new Node(0, 0, 0, 0, null, null);
Node refNode2 = new Node(0, 0, 0, 0, null, null);
for (int i = 0; i < numVal; i++) {
int x = (int) Math.pow(i+1, 5);
values[i] = x;
}
list1 = new DLList();
for (int i = 1; i < numVal; i++) {
c = values[i];
for (int j = 1; j < numVal; j++) {
b = values[j];
if (b > c) {
break;
}
else {
for (int k = 1; k < numVal; k++) {
a = values[k];
if (a > b || a > c) {
break;
}
else {
sum1 = a + b + c;
Node tempNode1 = new Node(sum1, a, b, c, null, null);
if (list1.isEmpty()) {
list1.addFirst(tempNode1);
refNode1 = tempNode1;
}
else {
list1.addAfter(refNode1, tempNode1);
refNode1 = tempNode1;
}
}
}
}
}
}
list2 = new DLList();
for (int i = 1; i < numVal; i++) {
f = values[i];
for (int j = 1; j < numVal; j++) {
e = values[j];
if (e > f) {
break;
}
else {
for (int k = 1; k < numVal; k++) {
d = values[k];
if (d > e || d > f) {
break;
}
else {
sum2 = f - (d + e);
if (sum2 < 0) {
break;
}
else {
Node tempNode2 = new Node(sum2, d, e, f, null, null);
if (list2.isEmpty()) {
list2.addFirst(tempNode2);
refNode2 = tempNode2;
}
else {
list2.addAfter(refNode2, tempNode2);
refNode2 = tempNode2;
}
}
}
}
}
}
}
list1 = quickSort(list1);
list2 = quickSort(list2);
int z = 0;
long temp1 = 0;
long temp2 = 0;
long checkA = 0;
long checkB = 0;
long checkC = 0;
long checkD = 0;
long checkE = 0;
long checkF = 0;
Node tempNode1 = new Node(0, 0, 0, 0, null, null);
Node tempNode2 = new Node(0, 0, 0, 0, null, null);
for (int x = 0; x < list1.size(); x++) {
if (x == 0) {
tempNode1 = list1.getFirst();
temp1 = tempNode1.getSum();
checkA = tempNode1.getValue1();
checkB = tempNode1.getValue2();
checkC = tempNode1.getValue3();
}
else {
tempNode1 = tempNode1.getNext();
temp1 = tempNode1.getSum();
checkA = tempNode1.getValue1();
checkB = tempNode1.getValue2();
checkC = tempNode1.getValue3();
}
for (int y = 0; y < list2.size(); y++) {
if (y == 0) {
tempNode2 = list2.getFirst();
temp2 = tempNode2.getSum();
checkD = tempNode2.getValue1();
checkE = tempNode2.getValue2();
checkF = tempNode2.getValue3();
}
else {
tempNode2 = tempNode2.getNext();
temp2 = tempNode2.getSum();
checkD = tempNode2.getValue1();
checkE = tempNode2.getValue2();
checkF = tempNode2.getValue3();
}
if (temp1 == temp2 && checkC <= checkD) {
checkA = (long) Math.pow(checkA, 1.0/5);
checkB = (long) Math.pow(checkB, 1.0/5);
checkC = (long) Math.pow(checkC, 1.0/5);
checkD = (long) Math.pow(checkD, 1.0/5);
checkE = (long) Math.pow(checkE, 1.0/5);
checkF = (long) Math.pow(checkF, 1.0/5);
System.out.println("Solution: "+checkA+"," + checkB+"," + checkC+"," + checkD+"," + checkE+"," + checkF);
}
if (x == list1.size()-1) {
System.exit(0);
}
}
}
}
public DLList quickSort(DLList S) {
DLList L = new DLList();
DLList E = new DLList();
DLList G = new DLList();
if (S.size() <= 1) {
return S;
}
long p = S.getLast().getSum();
while (!S.isEmpty()) {
if (S.getLast().getSum() < p) {
L.addLast(S.remove(S.getLast()));
}
else if (S.getLast().getSum() == p) {
E.addLast(S.remove(S.getLast()));
}
else {
G.addLast(S.remove(S.getLast()));
}
}
quickSort(L);
quickSort(G);
while (!L.isEmpty()) {
S.addLast(L.remove(L.getFirst()));
}
while (!E.isEmpty()) {
S.addLast(E.remove(E.getFirst()));
}
while (!G.isEmpty()) {
S.addLast(G.remove(G.getFirst()));
}
return S;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a value of 72 or higher: ");
String command = input.nextLine();
EquationSolver solver = new EquationSolver(command);
}
}
public class Node {
private long sum, val1, val2, val3;
private Node prev, next;
public Node(long sumVal, long value1, long value2, long value3, Node p, Node n) { // stores the values in a node
this.sum = sumVal;
this.val1 = value1;
this.val2 = value2;
this.val3 = value3;
this.prev = p;
this.next = n;
}
public long getSum() { // returns the value for key
return sum;
}
public long getValue1() { // returns length value of the node
return val1;
}
public long getValue2() {
return val2;
}
public long getValue3() {
return val3;
}
public Node getPrev() {
return prev;
}
public Node getNext() { // returns the next node of current node
return next;
}
public void setPrev(Node nPrev) {
prev = nPrev;
}
public void setNext(Node nNext) { // sets the next node of current node
next = nNext;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T00:09:17.743",
"Id": "29817",
"Score": "1",
"body": "As a general piece of advice, when you're stuck, use a profiler like `jvisualvm`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T02:11:43.217",
"Id": "29825",
"Score": "2",
"body": "\"doubly linked list\" What's wrong with ArrayList?"
}
] |
[
{
"body": "<p>The most important point is the comment in the accepted answer in your related post in SO: You are not using that the lists are ordered. Instead of checking every value in <code>list1</code> and <code>list2</code> you could move along them at the same time.</p>\n\n<p>Rough idea:</p>\n\n<blockquote>\n <p>When <code>y</code> in <code>list2</code> is larger than <code>x</code> in <code>list1</code> then select a larger\n <code>x</code> until you get a value larger than <code>y</code> and then select a larger\n <code>y</code>, etc. As it is the code seem to me to be O(n^6).</p>\n</blockquote>\n\n<p>Another minor thing is the list generation: you don't need to compare <code>b</code> and <code>c</code> in the second nested loop since <code>c = i^5</code> and <code>b=j^5</code> then you can make the second cycle go up to <code>i</code> instead of <code>numVal</code>. The same applies to the third nested loop.</p>\n\n<p>The result would be something like:</p>\n\n<pre><code>for (int i = 1; i < numVal; i++) {\n c = values[i];\n\n for (int j = 1; j < i; j++) {\n b = values[j];\n\n for (int k = 1; k < j; k++) {\n a = values[k];\n</code></pre>\n\n<p>Hope this things help.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T01:52:12.483",
"Id": "29820",
"Score": "0",
"body": "So basically rather than using two nested loops for comparison, I should compare the lists while iterating through them at the same time? Also if I do it the way you mention it, will it run in O(N^3logN) time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T02:01:43.587",
"Id": "29821",
"Score": "0",
"body": "I would not feel confident enough to assert if that would be the running time but it would seem so. (`2*N^3` to generate the lists, `N^3 log(N^3) = 3*N^3 logN` to sort them and `2*N^3` to iterate through them)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T02:06:24.557",
"Id": "29823",
"Score": "0",
"body": "Oh ok. As for iterating through the lists, wouldn't they both iterate through at the same time so the values of x and y will always be the same, until it reaches the end of list2 as the size of it may be smaller?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T00:55:10.893",
"Id": "18723",
"ParentId": "18720",
"Score": "1"
}
},
{
"body": "<p>When you compare sorted lists, you want to find identical values. It can be done in one pass, without nested loops. Take first values from both lists and compare. If values are equal, only then make additional checks, then take next values from both lists. If they are not equal, take next value from the list from which node with less value was taken.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T02:56:17.300",
"Id": "29827",
"Score": "0",
"body": "Ok so I implemented it that way, however it only finds one solution and then it stops searching. It doesn't terminate, but it just stops the search for more solutions for higher N values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T03:03:10.090",
"Id": "29828",
"Score": "0",
"body": "what does it mean \"stops but not terminate\"? Infinite loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T03:09:34.490",
"Id": "29829",
"Score": "0",
"body": "Like it will print out this: Enter a value of 72 or higher: \n94\nSolution: 19,43,46,47,67,72\nFrom what I know, there is a second solution it needs to find as well, but it just stops right there. However the code is still running, just not finding any more solutions. It could be a possible infinite loop."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T02:27:55.053",
"Id": "18725",
"ParentId": "18720",
"Score": "0"
}
},
{
"body": "<p>Several points to be said about this code:</p>\n\n<h2>Time Complexity</h2>\n\n<p>You have three nested loops each going to <code>n</code> and in the innermost body you add to the linked list, which makes that list roughly size <code>O(n^3)</code>. Same thing for the second list.\nAfterwards, you have loops over those lists nested, which gives you <code>O(n^6)</code>.</p>\n\n<p>Instead of even building the second list, I would suggest to switch to an entirely different data structure: You could store the initial list's result in a <code>HashMap</code> indexed by their sum. In the second round (where you previously created the second list) you would then just lookup the \"sum\" value of D,E, and F in that map. If a corresponding key exists, you have found a solution. While this does not really change the theoretical complexity, it does give you less required space, less object creations, and no need for even running any sorting algorithms. (If you care about multiple solutions, you may need to map the sum to a list of possible values.)</p>\n\n<h2>Data Structures</h2>\n\n<p>We have no information about your <code>DLList</code> class, but there is absolutely no reason to roll your own doubly-linked list instead of <code>java.util.LinkedList</code>. Similarly, why do you write your own quicksort implementation instead of relying to the proven and fast sorting implementations already available?</p>\n\n<h2>Code Structure / Style</h2>\n\n<p>Your <code>EquationSolver</code> looks like a mess. Around a dozen local variables and a huge block of code all in one method smells bad. You should refactor this with \"Extract to Method\" heavily.</p>\n\n<p>Your <code>Node</code> class is kind of off. Firstly, it does not need the reference to other nodes at all, if you relied on the existing list implementations. Then, it would not really be a node anymore anyways, and you'd have to think up a proper name for it. Secondly, storing three values and their sum is a huge source of errors, because the values may easily become inconsistent. Instead, you should just compute the sum from the given other values (on demand, or in the constructor). (Note that you could store D and E negatively to make this work.) Given all of this, your class <code>Node</code> rather resembles a <code>Tuple3</code> class, i.e. a class that represents a tuple of 3 values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T16:42:33.820",
"Id": "29978",
"Score": "0",
"body": "Actually, running an `O(n^3)` algorithm twice doesn't give you an `O(n^6)` algorithm, it gives you `O(2(n^3))`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T19:25:51.760",
"Id": "30069",
"Score": "0",
"body": "It's not running twice, but nested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T22:41:19.297",
"Id": "30081",
"Score": "0",
"body": "I can only first spot a regular \"for\" loop, then a nested \"for for for\" loop, then another \"for for for\" loop, and finally a \"for for\" loop. I still cannot see where there's a \"for for for for for for\" loop. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T06:17:41.003",
"Id": "30089",
"Score": "0",
"body": "The \"for for\" loop that loops over list1 outside and list2 inside with each list being roughly n^3-sized (after the sort calls)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T07:02:08.853",
"Id": "18787",
"ParentId": "18720",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T00:08:28.847",
"Id": "18720",
"Score": "2",
"Tags": [
"java",
"algorithm",
"mathematics"
],
"Title": "Solving Diophantine equations"
}
|
18720
|
<p>In <code>java.util.Random</code> the Oracle implementation of <code>nextInt(int)</code> is as follows:</p>
<pre><code>public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}
</code></pre>
<p>I have a need to do the same thing for <code>long</code>s, but this is not included as part of the class signature. So I extended the class to add this behavior. Here's my solution, and even though I'm pretty sure I have it right, bit-twiddling can subtly fluster even the best of devs!</p>
<pre><code>import java.util.Random;
public class LongRandom extends Random {
public long nextLong(long n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return nextLong() & (n - 1); // only take the bottom bits
long bits, val;
do {
bits = nextLong() & 0x7FFFFFFFL; // make nextLong non-negative
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}
}
</code></pre>
<p>Have I introduced a subtle bug? Are there improvements to make? What might I need to watch out for?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T05:20:21.287",
"Id": "29846",
"Score": "0",
"body": "You can find some alternatives on SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T13:24:30.297",
"Id": "29900",
"Score": "0",
"body": "Unlike Microsoft, Sun got that code right. Nice."
}
] |
[
{
"body": "<p>You just need to test, It's that simple.<br>\nI've tested your code on C#, minus the <code>& 0x7FFFFFFFL; // make nextLong non-negative</code> </p>\n\n<p>(I didn't need that, C# rands are positive)</p>\n\n<p>The results look well distributed on [0,N-1].\nSo I think code is fine, except for the part I did not test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:28:45.483",
"Id": "29904",
"Score": "0",
"body": "The problem with testing is that it’s categorically impossible to prove correctness through it. Your test in particular fails to find failing cases which another answer has found."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T21:58:32.013",
"Id": "29929",
"Score": "0",
"body": "That's nonsense. Did you *read* my post? You don't test to 'prove correctness', that's for the academics. You test to find faults."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T22:20:13.767",
"Id": "29930",
"Score": "0",
"body": "I actually think my previous comment was premature. But your “that’s for academics” dismissal is ridiculous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T04:04:10.787",
"Id": "29935",
"Score": "0",
"body": "So style and phrasing aside, we're on accord on the subject."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T07:49:19.590",
"Id": "18731",
"ParentId": "18727",
"Score": "0"
}
},
{
"body": "<p>Try it with n>2^32 and your code will fail. <code>0x7FFFFFFFL</code> reduces your code to <code>int</code>, breaking your extension to <code>long</code>. You need to use the maximal value of <code>long</code> not <code>int</code> in your mask. i.e. <code>7FFFFFFFFFFFFFFFL</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T13:28:20.037",
"Id": "18766",
"ParentId": "18727",
"Score": "3"
}
},
{
"body": "<p>There is a similar method in <a href=\"http://commons.apache.org/math/\" rel=\"nofollow\">Apache Commons Math</a>: <a href=\"http://commons.apache.org/math/apidocs/org/apache/commons/math3/random/RandomDataGenerator.html#nextLong%28long,%20long%29\" rel=\"nofollow\"><code>RandomDataGenerator.nextLong(long lower, long upper)</code></a>.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T13:56:16.563",
"Id": "18768",
"ParentId": "18727",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "18766",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T05:04:06.860",
"Id": "18727",
"Score": "4",
"Tags": [
"java",
"random"
],
"Title": "Extending java.util.Random.nextInt(int) into nextLong(long)"
}
|
18727
|
<p>I would love to hear feedback on my <a href="https://github.com/eranation/mixpanel-java" rel="nofollow">first open source project</a> (a very simple async API for Mixpanel).</p>
<p>It implements a REST client for <a href="https://mixpanel.com/docs/api-documentation/http-specification-insert-data" rel="nofollow">this REST HTTP API</a>.</p>
<p><strong>Review requested on the following aspects:</strong> </p>
<ul>
<li>Code style (formatting, naming etc...)</li>
<li>Code quality (best practices, performance etc)</li>
<li>Asynchronous aspects (usage of <code>Executors</code> etc)</li>
<li>JavaDoc quality</li>
</ul>
<p>Also I would love to hear feedback on the "non-code" aspects of it </p>
<ul>
<li>Github aspects (<a href="https://github.com/eranation/mixpanel-java/blob/master/README.md" rel="nofollow">readme</a>, license, folder structure)</li>
<li>Maven aspects (<a href="https://github.com/eranation/mixpanel-java/blob/master/pom.xml" rel="nofollow">pom.xml</a> structure and best practices)</li>
</ul>
<p><strong>Here is the core code:</strong></p>
<pre><code>package org.eranmedan.mixpanel;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.helpers.NOPLogger;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* A dead simple Mixpanel track API for Java
* <p>
* <b>Example Usage:</b>
* </p>
*
* <blockquote>
*
* <pre>
*
* String uniqueId = &quot;50479b24671bf&quot;;
* String nameTag = &quot;Test Name&quot;;
* String ip = &quot;123.123.123.123&quot;;
* Date time = new Date();
* String token = &quot;e3bc4100330c35722740fb8c6f5abddc&quot;;
* Map&lt;String, String&gt; props = new HashMap&lt;String, String&gt;();
* props.put(&quot;action&quot;, &quot;play&quot;);
* Logger logger = LoggerFactory.getLogger(&quot;MixpanelAPI Test Logger&quot;);
*
* MixpanelAPI mixpanelAPI = new MixpanelAPI(token, logger);
*
* mixpanelAPI.track(&quot;test1&quot;, uniqueId, props);
* mixpanelAPI.track(&quot;test2&quot;, uniqueId, nameTag, ip, time, props);
* mixpanelAPI.track(&quot;test3&quot;, uniqueId, nameTag, ip, time);
* mixpanelAPI.track(&quot;test4&quot;, uniqueId, nameTag, ip);
* mixpanelAPI.track(&quot;test5&quot;, uniqueId, nameTag);
* mixpanelAPI.track(&quot;test6&quot;, uniqueId);
*
*
*
* </pre>
*
* </blockquote>
*
* <b>For example, <code>test2</code> will send a message of this format:</b>
*
* <pre>
* { "event": "test2",
* "properties": {
* "distinct_id": "50479b24671bf",
* "ip": "123.123.123.123",
* "token": "e3bc4100330c35722740fb8c6f5abddc",
* "time": 1245613885,
* "mp_name_tag": "Test Name",
* "action": "play"
*
* }
* }
* </pre>
*
* <b>Note:</b> In most use cases you can ignore the return value of the
* <code>Future</code> returned for performance. The Future is mostly for
* testing purposes
*
* @version 0.1
* @author Eran Medan
* @see <a
* href="https://mixpanel.com/docs/api-documentation/http-specification-insert-data">https://mixpanel.com/docs/api-documentation/http-specification-insert-data</a>
*/
public class MixpanelAPI {
private static final String MIXPANEL_API_ENDPOINT = "http://api.mixpanel.com/track/?data=";
private final String token;
private final Logger logger;
private final ExecutorService threadPool;
/**
* @see #MixpanelAPI(String token, Logger logger, ExecutorService threadPool)
*
*/
public MixpanelAPI(String token) {
this(token, null);
}
/**
* @see #MixpanelAPI(String token, Logger logger, ExecutorService threadPool)
*
*/
public MixpanelAPI(String token, Logger logger) {
// TODO: isn't a fixed threadpool based on
// Runtime.getRuntime().availableProcessors() better?
this(token, logger, Executors.newCachedThreadPool());
}
/**
* Create a new MixpanelAPI object (usually, there is no need for more than
* one)
*
* @param token
* the MixPanel API token
* @param logger
* an optional Logger, if none provided a {@link NOPLogger} is
* provided
* @param threadPool
* an optional custom ExecutorService to queue the asynchronous HTTP
* calls to Mixpanel's API, if none provided a
* <code>Executors.newCachedThreadPool()</code> is used
*/
public MixpanelAPI(String token, Logger logger, ExecutorService threadPool) {
this.token = token;
this.logger = (logger == null) ? NOPLogger.NOP_LOGGER : logger;
this.threadPool = threadPool;
}
/**
* @see #track(String event, String nameTag, HttpServletRequest request,
* String cookieName, Map additionalProperties)
*/
public void track(String event, String nameTag, HttpServletRequest request, String cookieName) {
track(event, nameTag, request, cookieName, null);
}
/**
* Track an event
*
* @param request
* the request object, will be used to deduce the IP address and
* Mixpanel cookie for the unique ID
* @param cookieName
* the mixpanel cookie name, e.g. if this is your setup:
*
* <pre>
* mixpanel.init(token, {
* cookie_expiration: 365,
* cookie_name: "foobar"
* }
* </pre>
*
* then the cookie name is actually <code>mp_foobar</code>
*
* @see #track(String event, String distinctId, String nameTag, String ip,
* Date time, Map additionalProperties)
*/
public Future<Boolean> track(String event, String nameTag, HttpServletRequest request, String cookieName, Map<String, String> additionalProperties) {
Cookie mixpanelCookie = findCookieByName(request, cookieName);
String uniqueId = null;
String ip = getClientIpAddr(request);
if (mixpanelCookie != null) {
String cookieValue = mixpanelCookie.getValue();
String result;
try {
result = URLDecoder.decode(cookieValue, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
JsonParser jp = new JsonParser();
JsonElement mixJason = jp.parse(result);
uniqueId = mixJason.getAsJsonObject().get("distinct_id").getAsString();
} else {
logger.warn("Unique ID for mixpanel cookie name: " + cookieName + " was not found, using IP instead");
uniqueId = ip;
}
return track(event, uniqueId, nameTag, ip, null, null);
}
/**
* @see #track(String event, String distinctId, String nameTag, String ip,
* Date time, Map additionalProperties)
*/
public Future<Boolean> track(String event, String distinctId) {
return track(event, distinctId, null, null, null, null);
}
/**
* @return
* @see #track(String event, String distinctId, String nameTag, String ip,
* Date time, Map additionalProperties)
*/
public Future<Boolean> track(String event, String distinctId, Map<String, String> additionalProperties) {
return track(event, distinctId, null, null, null, additionalProperties);
}
/**
* @see #track(String event, String distinctId, String nameTag, String ip,
* Date time, Map additionalProperties)
*/
public Future<Boolean> track(String event, String distinctId, String nameTag) {
return track(event, distinctId, nameTag, null, null, null);
}
/**
* @see #track(String event, String distinctId, String nameTag, String ip,
* Date time, Map additionalProperties)
*/
public Future<Boolean> track(String event, String distinctId, String nameTag, String ip) {
return track(event, distinctId, nameTag, ip, null, null);
}
/**
* @see #track(String event, String distinctId, String nameTag, String ip,
* Date time, Map additionalProperties)
*/
public Future<Boolean> track(String event, String distinctId, String nameTag, String ip, Date time) {
return track(event, distinctId, nameTag, ip, time, null);
}
/**
* Tracks an event
*
* @param event
* the (required) event name
* @param distinctId
* (required) the user's distinct mixpanel ID (usually stored in a
* cookie) or any string that uniquely can identify a user. e.g. the
* user id.
* @param nameTag
* (optional) is the way to set a name for a given user for our
* streams feature. You can set this to any string value like an
* email, first and last name, or username.
* @param ip
* (optional) is a raw string IP Address (e.g. "127.0.0.1") that you
* pass to our API. This is largely useful if you're making requests
* from your backend and would like geolocation processing done on
* your requests otherwise it's safe to use the &ip=1 parameter
* described in the docs that is outside of the encoded data string.
* @param time
* is the time at which the event occured, it must be a unix
* timestamp, requests will be rejected that are 5 days older than
* codesent time - this is done for security reasons as your token is
* public generally. Format is seconds since 1970, GMT time zone. If
* you'd like to import data, you can through a special API for any
* event.
* @param additionalProperties
* additional custom properties in a name-value map
* @return a {@link Future} object returning a Boolean when calling it's
* <code>get()</code> method, true means a successful call (at the
* moment, true is the only possible return value, any error will
* cause an {@link ExecutionException} to be thrown when calling the
* future's get method). <b>Note:</b> In most use cases you can ignore
* the return value of the <code>Future</code> returned for
* performance. The Future is mostly for testing purposes
*/
public Future<Boolean> track(final String event, final String distinctId, final String nameTag, final String ip, final Date time, final Map<String, String> additionalProperties) {
return threadPool.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (event == null) {
throw new RuntimeException("event field is mandatory");
}
if (distinctId == null) {
throw new RuntimeException("distinctId field is mandatory");
}
JsonObject jo = new JsonObject();
jo.addProperty("event", event);
JsonObject properties = new JsonObject();
jo.add("properties", properties);
properties.addProperty("distinct_id", distinctId);
if (ip != null) {
properties.addProperty("ip", ip);
}
properties.addProperty("token", token);
if (time != null) {
properties.addProperty("time", time.getTime() / 1000L);
}
if (nameTag != null) {
properties.addProperty("mp_name_tag", nameTag);
}
if (additionalProperties != null) {
for (Entry<String, String> entry : additionalProperties.entrySet()) {
properties.addProperty(entry.getKey(), entry.getValue());
}
}
final String message = jo.toString();
byte[] bytes = message.getBytes();
String encode = DatatypeConverter.printBase64Binary(bytes);
logger.debug("Mixpanel message to be sent: " + message);
final String url = MIXPANEL_API_ENDPOINT + encode;
logger.debug("Mixpanel URL to call: " + url);
URL apiURL;
try {
apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int statusCode = connection.getResponseCode();
InputStream inputStream = connection.getInputStream();
String contentEncoding = connection.getContentEncoding();
String responseBody = IOUtils.toString(inputStream, contentEncoding);
if (statusCode == 200) {
if (responseBody.equals("1")) {
logger.debug("Mixpanel event reported successfully");
return true;
} else {
String warningMessage = "Mixpanel event not reported successfully. Response Body: " + responseBody + " message: \n" + message + ". url: " + url;
logger.warn(warningMessage);
throw new Exception(warningMessage);
}
} else {
String warningMessage = "Mixpanel response not 200: " + statusCode;
logger.warn(warningMessage);
throw new Exception(warningMessage);
}
} catch (MalformedURLException e) {
String warningMessage = "Mixpanel URL is malformed: " + e.getMessage();
logger.warn(warningMessage, e);
throw new Exception(warningMessage, e);
} catch (IOException e) {
String warningMessage = "Mixpanel IO Exception: " + e.getMessage();
logger.warn(warningMessage, e);
throw new Exception(warningMessage, e);
}
}
});
}
public void close() {
if (!threadPool.isShutdown()) {
threadPool.shutdown();
}
// no need to threadPool.awaitTermination, let it end when it ends, just
// stop accepting new tasks.
}
public void awaitTermiation(long timeout, TimeUnit unit) {
try {
threadPool.awaitTermination(timeout, unit);
} catch (InterruptedException e) {
logger.warn("Didn't terminate after " + timeout + " " + unit.toString());
}
}
@Override
protected void finalize() throws Throwable {
try {
close();
} finally {
super.finalize();
}
}
private static String getClientIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
private static Cookie findCookieByName(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
return cookie;
}
}
}
return null;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T10:27:35.447",
"Id": "29854",
"Score": "3",
"body": "Just 2 comments: (1) You could put `if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {return xxx;}` in its own method to avoid the code repetition in your `setClientIpAddr` method. (2) Your last `track` method is quite long and would probably benefit from being split in several smaller methods, at least from a readability perspective."
}
] |
[
{
"body": "<ol>\n<li><p>I'd implement <code>Closeable</code>, <code>AutoCloseable</code>:</p>\n\n<pre><code>public class MixpanelAPI implements Closeable, AutoCloseable {\n ...\n}\n</code></pre>\n\n<p>See: <a href=\"https://stackoverflow.com/a/13141382/843804\">implements Closeable or implements AutoCloseable</a> on Stack Overflow.</p></li>\n<li><blockquote>\n<pre><code>public MixpanelAPI(String token, Logger logger, ExecutorService threadPool) {\n this.token = token;\n this.logger = (logger == null) ? NOPLogger.NOP_LOGGER : logger;\n this.threadPool = threadPool;\n}\n</code></pre>\n</blockquote>\n\n<p>I'd check nulls here. Allowing to create an object with an invalid state (when <code>token</code> or <code>threadPool</code> is <code>null</code>) does not look a good idea. You'll get a <code>NullPointerException</code> later which would be harder to debug. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>; <em>Effective Java 2nd Edition</em>, <em>Item 38: Check parameters for validity</em>)</p>\n\n<p>Guava has a nice <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow noreferrer\"><code>Preconditions</code></a> API for that.</p></li>\n<li><blockquote>\n<pre><code>public void track(String event, String nameTag, HttpServletRequest request, String cookieName) {\n track(event, nameTag, request, cookieName, null);\n}\n</code></pre>\n</blockquote>\n\n<p>I'd create an explanatory variable for the <code>null</code> parameter. It would be easier to read, readers don't have to check the called method to figure out what is that <code>null</code>.</p>\n\n<pre><code>public void track(String event, String nameTag, HttpServletRequest request, String cookieName) {\n Map<String, String> additionalProperties = null;\n track(event, nameTag, request, cookieName, additionalProperties);\n}\n</code></pre>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>, p296; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><p>You have too many parameters here:</p>\n\n<blockquote>\n<pre><code>return track(event, distinctId, null, null, null, additionalProperties);\n</code></pre>\n</blockquote>\n\n<p>It's a code smell: Long Parameter List (See <em>Long Parameter List</em> in <em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>). You could introduce a parameter object.</p></li>\n<li><p>I'd be a little bit more defensive here and set a limit here:</p>\n\n<blockquote>\n<pre><code>String responseBody = IOUtils.toString(inputStream, contentEncoding);\n</code></pre>\n</blockquote>\n\n<p>If it accidentally returns a 10GB file you probably waste a lot of network bandwidth and get an <code>OutOufMemoryError</code> later.</p></li>\n<li><blockquote>\n<pre><code>JsonParser jp = new JsonParser();\n</code></pre>\n</blockquote>\n\n<p>It would deserve a longer variable name. Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p></li>\n<li><blockquote>\n<pre><code>logger.warn(\"Unique ID for mixpanel cookie name: \" + cookieName + \" was not found, using IP instead\");\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://en.wikipedia.org/wiki/SLF4J\" rel=\"nofollow noreferrer\">SLF4J supports <code>{}</code></a>, use that for easier reading and better performance:</p>\n\n<pre><code>logger.warn(\"Unique ID for mixpanel cookie name: {} was not found, using IP instead\", cookieName);\n</code></pre></li>\n<li><blockquote>\n<pre><code> * @return a {@link Future} object returning a Boolean when calling it's\n * <code>get()</code> method, true means a successful call (at the\n * moment, true is the only possible return value, any error will\n * cause an {@link ExecutionException} to be thrown when calling the\n * future's get method). <b>Note:</b> In most use cases you can ignore\n * the return value of the <code>Future</code> returned for\n * performance. The Future is mostly for testing purposes\n</code></pre>\n</blockquote>\n\n<p>In that case you could use <code>Future<Void></code> instead.</p></li>\n<li><p>I'd move the <code>Callable</code> to a separate class. I think you could extract out some smaller methods for better readability and fulfilling the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a>.</p></li>\n<li><blockquote>\n<pre><code>URL apiURL;\ntry {\n apiURL = new URL(url);\n</code></pre>\n</blockquote>\n\n<p>The variable declaration could be inside the try block:</p>\n\n<pre><code>try {\n URL apiURL = new URL(url);\n</code></pre></li>\n<li><blockquote>\n<pre><code>InputStream inputStream = connection.getInputStream();\n</code></pre>\n</blockquote>\n\n<p>You should close this stream in a <code>finally</code> block or use try-with-resources. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow noreferrer\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><blockquote>\n<pre><code>if (statusCode == 200) {\n if (responseBody.equals(\"1\")) {\n logger.debug(\"Mixpanel event reported successfully\");\n return true;\n } else {\n String warningMessage = \"Mixpanel event not reported successfully. Response Body: \"\n + responseBody + \" message: \\n\" + message + \". url: \" + url;\n logger.warn(warningMessage);\n throw new Exception(warningMessage);\n }\n} else {\n String warningMessage = \"Mixpanel response not 200: \" + statusCode;\n logger.warn(warningMessage);\n throw new Exception(warningMessage);\n}\n</code></pre>\n</blockquote>\n\n<p>I think it would be easier to follow with <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clauses</a>:</p>\n\n<pre><code>if (statusCode != 200) {\n ...\n throw new Exception(warningMessage);\n}\nif (!responseBody.equals(\"1\")) {\n ...\n throw new Exception(warningMessage);\n}\nlogger.debug(\"Mixpanel event reported successfully\");\nreturn true;\n</code></pre></li>\n<li><blockquote>\n<pre><code>if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"Proxy-Client-IP\");\n}\n</code></pre>\n</blockquote>\n\n<p><code>ip.length()</code> could be changed to <code>ip.isEmpty()</code>. It's more readable. Furthermore, the first two conditions could be changed to <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isEmpty%28java.lang.CharSequence%29\" rel=\"nofollow noreferrer\"><code>StringUtils.isEmpty(ip)</code></a> (which is null-safe, from <a href=\"http://commons.apache.org/proper/commons-lang/\" rel=\"nofollow noreferrer\">Apache Commons Lang</a>).</p></li>\n<li><p>You have five identical if statements here. I'd remove the duplication and changed it into a loop:</p>\n\n<pre><code>private static String getClientIpAddr(HttpServletRequest request) {\n List<String> ipHeaders = newArrayList();\n ipHeaders.add(\"X-Forwarded-For\");\n ipHeaders.add(\"Proxy-Client-IP\");\n ipHeaders.add(\"WL-Proxy-Client-IP\");\n ipHeaders.add(\"HTTP_CLIENT_IP\");\n ipHeaders.add(\"HTTP_X_FORWARDED_FOR\");\n\n for (String ipHeader: ipHeaders) {\n String ip = request.getHeader(ipHeader);\n boolean validIp = StringUtils.isNotEmpty(ip) && !\"unknown\".equalsIgnoreCase(ip);\n if (validIp) {\n return ip;\n }\n }\n return request.getRemoteAddr();\n}\n</code></pre>\n\n<p>(<code>newArrayList</code> from <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\">Google Guava</a>.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T08:31:46.020",
"Id": "43842",
"ParentId": "18732",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43842",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T07:52:55.743",
"Id": "18732",
"Score": "3",
"Tags": [
"java",
"multithreading",
"api",
"asynchronous"
],
"Title": "Very simple async MixpanelAPI"
}
|
18732
|
<p>In C#, passing a parameter by reference can't be ignored:</p>
<pre><code>// C#
void foo(ref int p_value) ; // passing an int by reference
void bar()
{
int i = 0 ;
foo(ref i) ;
}
</code></pre>
<p>In C++ (and as far as I am concerned, it is a good thing), the passing by reference is only marked in the function prototype, so the code above becomes:</p>
<pre><code>// C++
void foo(int & p_value) ; // passing an int by reference
void bar()
{
int i = 0 ;
foo(i) ; // at call site, there is no "ref" marker.
}
</code></pre>
<p>The thing is, for a few special functions, to ease code reviewing, we would want to use a C#-like solution to read at call site if a variable is expected to be modified or not.</p>
<p>I devised a solution wrapping the value with a struct, something like:</p>
<pre><code>template<typename T>
struct Ref
{
T & m_value ;
explicit Ref(T & p_value) : m_value(p_value) {}
operator T & () { return this->m_value ; }
operator const T & () const { return this->m_value ; }
} ;
template <typename T> // wrapping T with Ref
Ref<T> byRef(T & p_value)
{
return Ref<T>(p_value) ;
}
template <typename T> // idempotent-enabling overload (no need for Ref<Ref<T>>)
Ref<T> & byRef(Ref<T> & p_value)
{
return p_value ;
}
</code></pre>
<p>I expect this trivial code to be inlined away in optimized code.</p>
<p>This enables me to write the code:</p>
<pre><code>void foo(Ref<int> p_int)
{
p_int *= 10 ;
}
void bar()
{
int i = 0 ;
foo(byRef(i)) ;
}
</code></pre>
<p>Which is exactly what I want:</p>
<ul>
<li>no use of <code>foo(& i)</code> C-style notation, with pointers, needing to handle NULL, etc.</li>
<li>in the cases we care, we can see in the code what is passed by non-const reference</li>
</ul>
<p><b>Did I miss some unexpected problem/hidden cost that will come back to bite me in a few weeks/months/years?</p>
<p>Could this code be written better?</p>
<p>Will the code be confusing when seen through some un*x debuggers?</b></p>
<p>P.S.: Of course, <code>Ref</code> and <code>byRef</code> will be properly namespaced. I'm still not sure about making <code>Ref::m_value</code> public or private.</p>
|
[] |
[
{
"body": "<p>I can't see anything I would do majorly different.</p>\n\n<ul>\n<li>I would make the member <code>T & m_value</code> private. </li>\n<li>I would change the name of the method <code>byRef()</code> to just <code>ref()</code>\n<ul>\n<li>Note you still have a difference in identifiers.<br>\nThe class is <code>Ref</code> while the function is <code>ref()</code></li>\n</ul></li>\n</ul>\n\n<p>The only problem I see is that at inside the function, the object is not automatically usable in its native type you need to cast it back before you can use it:</p>\n\n<pre><code>struct X { void print();};\n\nvoid print(Ref<X> x)\n{\n x.print(); // This fails to compile\n\n // To use the x object I need to cast it back to an X\n static_cast<X&>(x).print();\n\n // If we are going to use it multiple times then we could set up\n // a local reference to the object as this will generate an implicit cast\n X& x1 = x;\n x1.print();\n}\n</code></pre>\n\n<p>Thus getting at methods in the object becomes slightly on the messy side.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T17:41:22.440",
"Id": "29868",
"Score": "0",
"body": "I get your point about the method calls. I didn't think about that. . . o.O . . . The good thing is that the aim is to wrap built-ins. . . And of course, you're right about the names: `byRef` should become `ref`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T17:45:49.670",
"Id": "29869",
"Score": "0",
"body": "Note that keeping m_value public (and giving it a short name) would enable direct manipulation of the variable, including the method calls. As the `Ref` is used only as a simple wrapper, there's no concern about encapsulation, there. Am I wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:36:04.403",
"Id": "29871",
"Score": "0",
"body": "@paercebal: It was only a minor thing (personally I would make it private). **BUT** I have no strong argument for my perspective; in a code review at work if another engineer really wanted it public I would be fine with that as well. Direct manipulation (via member or casting) boils down to the same thing. There is some extra messing around you need to do. I am sure we can take this one step further (if we use some template/macro hijinks)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:39:38.150",
"Id": "29872",
"Score": "0",
"body": "If the design goal is only to support built-in types then you should make that explicit by makeing sure it does not compile for other types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T12:05:24.277",
"Id": "29899",
"Score": "0",
"body": "`makeing sure it does not compile for other types` : You're right. On my computer, my own proof-of-concept had additional basic constraints, but I'm unsure about the exact level of conformance/efficiency of all the compilers at my new job (started since two weeks ago... ^_^...), so I'm not sure I'll apply that \"patch\" until I'm more familiar about those (I already broke the build once for a dumb warning, not sure I want to try it again soon)... ^_^"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T16:57:19.333",
"Id": "18744",
"ParentId": "18736",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T11:42:28.907",
"Id": "18736",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Explicitely passing a parameter by reference in C++03"
}
|
18736
|
<p>I'm new to Zend Framework. Can you help me optimize this function, which gets a list of <code>Manufactures</code> with some conditions from a database?</p>
<pre><code>private function Manufactures(
$Condition = array(),
$Order = array('name' => 'ASC'),
$Strict = TRUE,
$Limit = NULL)
{
$Request = $this->_DbTable->select();
$Clause = $Strict ? '=' : 'LIKE';
foreach ($Condition as $index => $value) {
if (!is_array($value)) {
$Request->where($this->_DbTable->info('name') . '.' . $index . ' '. $Clause .' ?', $value);
} else {
foreach ($value as $key => $val) {
if (is_array($val)) {
foreach ($val as $valIndex) {
if (isset($valIndex['modifier']) && isset($valIndex['value'])) {
$Request->where($this->_DbTable->info('name') . '.' . $key . ' ' . $valIndex['modifier']. ' ?', $valIndex['value']);
}
}
}
}
}
}
foreach ($Order as $index => $value) {
$Request->order($index . ' ' . $value);
}
if($Limit) $Request->limit($Limit);
$Data = $this->_DbTable->fetchAll($Request)
->toArray();
return isset($Data) ? $Data : NULL;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T12:38:34.397",
"Id": "18738",
"Score": "3",
"Tags": [
"php",
"performance",
"mysql",
"zend-framework"
],
"Title": "Getting a list of manufacturers from a database"
}
|
18738
|
<p>I rarely write multithreaded code, and am on shaky ground when doing so. I make mistakes. I would like a sanity check of something I am going to introduce in one of my apps.</p>
<p>There will be exactly one running instance of the <code>Thread</code> class below in my application. (It will be stored in a servlet context attribute.) "Clients" will call one of three methods on the instance, <code>getRunList()</code> to get data from it, <code>signalFreshRunListCreation()</code> to tell the thread to generate new data, and <code>stopThread()</code> to signal the thread to exit. On its own, the thread creates new data every 30 seconds.</p>
<p>Have I made any errors? </p>
<pre><code>
public class ThreadRunListDefault extends Thread {
// This set to true signals that the thread should exit.
private boolean _boStop = false;
// The thread sets this to true just before it sleeps.
private boolean _boIsSleeping = false;
// An external client sets this to true to signal that a new run list should be created.
private boolean _boFreshRunListRequested = false;
// This is a mutex to lock the run list while a fresh one is being created.
private Object _lockRunList = new Object();
// This is the actual data that will be returned.
private List<BeanRunOutput> _runList;
// This is the time the thread will sleep between refreshing the data on its own
private long _iSleepMilliseconds = 30000;
@Override
public void run() {
// Loop as long as no client has indicated the thread should stop.
while (!_boStop) {
// Create the data.
this.createFreshRunList();
// Only sleep if a refresh of the data wasn't requested while we were
// creating a fresh run list.
if (!_boFreshRunListRequested) {
try {
// We set the sleeping flag to true so that signalFreshRunListCreation() will
// know whether or not to call interrupt() on the thread and wake it up.
_boIsSleeping = true;
Thread.sleep(_iSleepMilliseconds);
} catch (InterruptedException e) { }
_boIsSleeping = false;
}
}
}
/*
* This is the method that will be called by run() to create new data in the _runList member variable.
*/
private void createFreshRunList() {
synchronized(this._lockRunList) {
// Here we put the code that creates the run list.
// Typically it will take 5 to 10 seconds.
_runList = new ArrayList<BeanRunOutput>();
}
}
/*
* This is the method a client will call to get the data in _runList.
*/
public List<BeanRunOutput> getRunList() {
synchronized(this._lockRunList) {
return _runList;
}
}
/*
* This is the method a client will call to signal the thread that a new run list should be created.
* If run() is currently gathering data (_boIsSleeping is false), a flag will be set to tell run()
* to run again immediately after it is finished, without sleeping first. If the thread is currently
* sleeping, it will be interrupted.
*/
public void signalFreshRunListCreation() {
if (_boIsSleeping) {
// Thread is sleeping so interrupt it.
this.interrupt();
} else {
// The thread is running so signal it should just run again when
// complete (in other words not sleep).
_boFreshRunListRequested = true;
}
}
/*
* This method allows a client to signal the thread to exit.
*/
public void stopThread() {
_boStop = true;
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>The <code>_boStop</code> and the <code>_boIsSleeping</code> fields are accessed by multiple threads, so you should synchronize them. You could use <code>volatile</code> fields or <code>AtomicBoolean</code>s too.</p>\n\n<p>Make sure that you do read operations in <code>synchronized</code> blocks too, not just writes:</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em>.</p></li>\n<li><p>A possible bug: <code>_boFreshRunListRequested</code> is never set to <code>false</code>.</p></li>\n<li><p>Using <code>_</code> prefixes (and sometimes <code>this.</code>) to access fields it's not really necessary and it's just noise. Modern IDEs use highlighting to separate local variables from instance variables.</p></li>\n<li><p>You could eliminate some comments, for example:</p>\n\n<pre><code>// Loop as long as no client has indicated the thread should stop.\nwhile (!boStop) {\n</code></pre>\n\n<p>This could be</p>\n\n<pre><code>while (!threadStop) {\n</code></pre>\n\n<p>Another example:</p>\n\n<pre><code> // Create the data.\n this.createFreshRunList();\n</code></pre>\n\n<p>Here you could rename the method to <code>createData</code> or <code>createFreshData</code>.</p>\n\n<p>A good reading in this topic is <em>Clean Code</em> by <em>Robert C. Martin</em> and <em>Code Complete</em>, 2nd Edition by <em>Steve McConnell</em>.</p></li>\n<li><p>It mainly depends on your requirements, but I'd consider renaming the class to <code>DataRefresherImpl</code> and implementing two interfaces: <code>DataRefresherService</code> and <code>DataRefresher</code>. The first would be used only in the servlet/container initializer. The second is for the clients to get their data and to request new data creation. It would prevent clients to call the <code>stopThread</code> method accidentally.</p></li>\n<li><p><em>OldCurmudgeon</em> has already mentioned the <code>getRunList</code> method is dangerous. You could use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#unmodifiableList%28java.util.List%29\"><code>Collections.unmodifiableList</code></a> here. Furthermore, make sure that the <code>BeanRunOutput</code> objects are also immutable or handle the modifications. See also: <em>Effective Java, 2nd Edition</em>, <em>Item 39: Make defensive copies when needed</em></p></li>\n</ol>\n\n<p>Finally, here is an refactored version with the queue which was suggested by <em>OldCurmudgeon</em>.</p>\n\n<pre><code>public interface DataRefresherService {\n void shutdown();\n}\n</code></pre>\n\n\n\n<pre><code>public interface DataRefresher {\n List<BeanRunOutput> getRunList();\n void signalFreshRunListCreation();\n}\n</code></pre>\n\n\n\n<pre><code>public class DataRefresherImpl implements Runnable, \n DataRefresherService, DataRefresher {\n\n private final AtomicBoolean threadStop = new AtomicBoolean(false);\n\n private final ReentrantReadWriteLock listLock = new ReentrantReadWriteLock();\n\n private static final long REFRESH_INTERVAL_IN_MILLIS = 3000;\n\n private final ArrayBlockingQueue<String> refreshQueue = \n new ArrayBlockingQueue<String>(1);\n\n private List<BeanRunOutput> runList;\n\n public DataRefresherImpl() {\n }\n\n @Override\n public void run() {\n while (!threadStop.get()) {\n createFreshRunList();\n sleepAndWakeOnRequest();\n }\n }\n\n private void createFreshRunList() {\n listLock.writeLock().lock();\n try {\n runList = new ArrayList<BeanRunOutput>();\n } finally {\n listLock.writeLock().unlock();\n }\n }\n\n private void sleepAndWakeOnRequest() {\n try {\n refreshQueue.poll(REFRESH_INTERVAL_IN_MILLIS, TimeUnit.MILLISECONDS);\n } catch (InterruptedException ignored) {\n }\n }\n\n @Override\n public List<BeanRunOutput> getRunList() {\n listLock.readLock().lock();\n try {\n return runList;\n } finally {\n listLock.readLock().unlock();\n }\n }\n\n @Override\n public void signalFreshRunListCreation() {\n refreshQueue.offer(\"refresh\");\n }\n\n @Override\n public void shutdown() {\n threadStop.set(true);\n refreshQueue.offer(\"shutdown\");\n }\n}\n</code></pre>\n\n<p>(I've not tested this too much.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T23:43:34.827",
"Id": "29887",
"Score": "0",
"body": "I agree with all of your points apart from 4 but let's not argue about that one here. Nice work on the queue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T23:46:14.807",
"Id": "29888",
"Score": "0",
"body": "I don't think `threadStop` needs to be atomic, `volatile` would do surely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T06:57:09.620",
"Id": "29941",
"Score": "0",
"body": "I hope you don't mind if I use your refactored version. I'll put a comment in it with both your names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:28:04.140",
"Id": "29948",
"Score": "1",
"body": "@JohnFitzpatrick: Feel free to use it, the whole site is under creative commons licence :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:07:41.940",
"Id": "29984",
"Score": "0",
"body": "One more question: I would like a client who has called `signalFreshRunListCreation()` while the data is currently being gathered by `createFreshRunList()` to block at least until the next `createFreshRunList()` has begun. In other words he/she should get data from the next gathering after they call `getRunList()`. I think all I need to do is add `listlock.readLock().lock()` and then `unlock()` immediately after `refreshQueue.offer(\"refresh\");` to achieve this effect. Is that true? (OK, I know I'm going outside the scope of reviewing code. Don't hesitate to say \"we don't do that here\".)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T21:42:43.437",
"Id": "30151",
"Score": "1",
"body": "@JohnFitzpatrick: One idea: you might be able to do it with an `Executor` and submit a `Callable` which calls the `createFreshRunList` method. Then you could wait for the `Future.get` in the signal method."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T16:14:52.637",
"Id": "18741",
"ParentId": "18740",
"Score": "6"
}
},
{
"body": "<p>Comments in no particular order but mostly from top to bottom:</p>\n\n<ol>\n<li><p>It is generally considered better to implement <code>Runnable</code> rather than extend <code>Thread</code>.</p></li>\n<li><p>Consequently from 1, calling <code>this.interrupt()</code> is no longer valid and changing it to <code>Thread.currentThread().interrupt()</code> in <code>signalFreshRunListCreation</code> highlights a problem. You will actually then be interrupting the calling thread, not the RunList thread.</p>\n\n<p>The trick to this is to store a copy of your current thread as one of the first things in your <code>run</code> method. You can then call its <code>interrupt()</code> to interrupt the RunList.</p></li>\n<li><p>I am being reminded by my IDE to only <code>synchronize</code> on <code>final</code> objects. This is good advice so make <code>_lockRunList</code> <code>final</code>.</p></li>\n<li><p>Just returning the list from <code>getRunList</code> is dangerous. You should probably either copy it or do something else to protect yourself from the other thread hacking it around.</p></li>\n<li><p>It's probably not the best idea to use <code>interrupt</code> to control your flow. There are other mechanisms that would be better, I'd probably create a single-item <code>BlockingQueue</code> and use <code>poll(time)</code> on it to implement your pause. You can then prematurely interrupt the pause by posting to the queue.</p>\n\n<p>This would also eliminate the use of <code>Thread.sleep()</code> which is generally considered worth trying to avoid as it is rarely what you really want to do.</p></li>\n<li><p><code>stopThread</code> propably should also interrupt it. Once you are not using <code>interrupt</code> to control your flow this will become easy.</p></li>\n<li><p><code>boFreshRunListRequested</code> should be made <code>volatile</code> because it is accessed from several threads.</p></li>\n</ol>\n\n<p>Just because I felt like making one, here's a <code>Dozer</code> that will pause for a certain amount of time or a special event. It uses the same mechanism we are suggesting.</p>\n\n<pre><code>/**\n * Use one of these to doze for a certain time.\n *\n * The dozing is fully interruptable.\n *\n * Another thread can stop the caller's doze with either a wakeup call or an abort call.\n *\n * These can be interpreted in any way you like but it is intended that a Wakeup is\n * interpreted as a normal awakening and should probably be treated in exactly the\n * same way as an Alarm. An Abort should probably be interpreted as a suggestion\n * to abandon the proces.\n */\npublic class Doze {\n // Special alarm messages.\n public enum Alarm {\n // Standard timeout.\n Alarm,\n // Just wake from your doze.\n Wakeup,\n // Abort the whole Doze process.\n Abort;\n }\n // My queue to wait on.\n private final ArrayBlockingQueue<Alarm> doze = new ArrayBlockingQueue<Alarm>(1);\n // How long to wait by default.\n private final long wait;\n\n public Doze(long wait) {\n this.wait = wait;\n }\n\n public Doze() {\n this(0);\n }\n\n public Alarm doze() throws InterruptedException {\n // Wait that long.\n return doze(wait);\n }\n\n public Alarm doze(long wait) throws InterruptedException {\n // Wait that long.\n Alarm poll = doze.poll(wait, TimeUnit.MILLISECONDS);\n // If we got nothing then it must be a normal wakeup.\n return poll == null ? Alarm.Alarm : poll;\n }\n\n public void wakeup() {\n // Just post a Wakeup.\n doze.add(Alarm.Wakeup);\n }\n\n public void abort() {\n // Signal the system to abort.\n doze.add(Alarm.Abort);\n }\n\n public static void main(String[] args) throws InterruptedException {\n // Doze for 10 seconds.\n final Doze d = new Doze(1 * 1000);\n\n // Start a dozing thread.\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Alarm a = d.doze();\n // Wait forever until we are aborted.\n while (a != Alarm.Abort) {\n System.out.println(\"Doze returned \" + a);\n a = d.doze();\n }\n System.out.println(\"Doze returned \" + a);\n } catch (InterruptedException ex) {\n // Just exit on interrupt.\n }\n }\n }).start();\n\n // Wait for a few seconds.\n Thread.sleep(3000);\n\n // Wake it up.\n d.wakeup();\n\n // Wait for a few seconds.\n Thread.sleep(3000);\n\n // Abort it.\n d.abort();\n\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T06:44:10.527",
"Id": "29940",
"Score": "0",
"body": "All your points are crystal clear thanks. There's just one, point 2, that I'd like to make sure I understood correctly. Point 2 is that in its current state (even before I switch to implementing `Runnable` rather than extending `Thread`), my `signalFreshRunListCreation()` method will not have the desired effect. The call to `this.interrupt()` does not interrupt the (possibly) sleeping thread that is executing the `run()` method, but rather it wakes the (non-sleeping) calling thread?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T09:16:15.273",
"Id": "29958",
"Score": "0",
"body": "Not quite - if you extend `Thread` then `this.interrupt()` is a perfectly acceptable mechanism (I think). However, once you move away from extending `Thread` and merely implement `Runnable` (the \"correct\" mechanism) you have to take and hold a reference to the thread to access it. However, see 5 and @palacsint's example of how to avoid using `interrupt` completely."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:49:38.260",
"Id": "18747",
"ParentId": "18740",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T13:26:56.913",
"Id": "18740",
"Score": "5",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Multithreading correctly done?"
}
|
18740
|
<p>Is there a way to improve this SQL query? It involves multiple cross join and joins.</p>
<p>I have 3 tables, and I want to compute the cardinal product:</p>
<pre><code>table N:
N
-
4
table sums:
i S
-----------
1 22
2 26
3 22
table mults:
i j M
-------------------
1 1 122
1 2 144
1 3 119
2 1 144
2 2 170
2 3 141
3 1 119
3 2 141
3 3 126
</code></pre>
<p>Here is a <a href="http://sqlfiddle.com/#!2/c35c4/1" rel="nofollow">fiddle</a>.</p>
<pre><code>SELECT ((N.n*M1.m)-(S1.s*S2.s)) / (SQRT((N.n*M2.m)-(pow(S1.s,2))) * SQRT((N.n*M3.m)-(pow(S2.s,2))))
FROM N
CROSS JOIN sums as S1
CROSS JOIN sums as S2
JOIN mults as M1
ON M1.i = S1.i
AND M1.j = S2.i
JOIN mults as M2
ON M2.i = S1.i
AND M2.j = S1.i
JOIN mults as M3
ON M3.i = S2.i
AND M3.j = S2.i;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T17:33:01.303",
"Id": "29865",
"Score": "0",
"body": "Does it have to be done in SQL? I would suck the data out and do it in memory instead. There are some powerful matrix and numeric libraries out there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T17:33:56.770",
"Id": "29866",
"Score": "0",
"body": "yeah, I know LAPACK for example but with sql queries?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T21:24:26.137",
"Id": "29927",
"Score": "3",
"body": "I agreed with @Leonid. Using a database like this is likely to fall apart if you try to apply this approach on a little larger data sets, but another issue is that it looks so much like a math problem that you really should use a math tool just to make it easier to maintain and debug later."
}
] |
[
{
"body": "<p>This SQL, for what it does, is neat, and concise. There is no obvious place where any optimizations can be made. With the data size as small as it is, there is no reason to recommend indexes, or other improvements.</p>\n\n<p>The only glaring issue has been pointed out already: There are tools other than SQL that are designed to do these types of heavy computation with performance that your database just won't beat.</p>\n\n<p>Apart from anything else, the log functions are notoriously hard to get right, and there are multiple 'standards' for implementation.</p>\n\n<p>Consider math libraries designed for data and computations such as this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T05:31:31.083",
"Id": "36945",
"ParentId": "18742",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T16:37:42.460",
"Id": "18742",
"Score": "5",
"Tags": [
"sql",
"join"
],
"Title": "SQL cross join and multiple joins"
}
|
18742
|
<p>I'm doing <a href="http://projecteuler.net/problem=5" rel="nofollow noreferrer">Project Euler problem 5</a> as a kata, focussing on TDD and code readability. The challenge is:</p>
<blockquote>
<p>What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</p>
</blockquote>
<p>For reference, a "less-readable" solution that reeks of goto was something along these lines: </p>
<pre><code>public int Solution_GotoVersion()
{
int solution = 1;
outer: while (solution++ < int.MaxValue)
{
for (int j = 1; j <= 20; j++)
{
if (solution % j != 0)
goto outer;
}
return solution;
}
throw new Exception("Solution not found");
}
</code></pre>
<p>This takes <strong>about 4 seconds</strong> to run, relative to the other solutions.</p>
<p>Of course I was trying to avoid such code (in light of readability, for one), I wrote it specifically to compare it to my first solution, that uses an alternative along the lines of <a href="https://stackoverflow.com/a/1133520/419956">this SO answer</a>. So, focussing on readability, here's something a little nicer:</p>
<pre><code>public int Solution_LinqVersion()
{
var dividers = Enumerable.Range(1, 20);
int solution = Enumerable
.Range(1, int.MaxValue)
.FirstOrDefault(candidate
=> dividers.All(divider => candidate.IsDivisibleBy(divider)));
return solution;
}
</code></pre>
<p>This performs much worse, taking <strong>about 25 seconds</strong>, relatively. I don't mind loosing <em>some</em> performance when traded for readability, but a factor 8 is a bit much.</p>
<p>I've tried an intermediate solution, like this:</p>
<pre><code>public int Solution_LittleOfBothWorlds()
{
var dividers = Enumerable.Range(1, 20).ToArray();
int solution = 1;
while (solution++ < int.MaxValue)
{
if (dividers.All(divider => solution % divider == 0))
return solution;
}
throw new Exception("Solution not found");
}
</code></pre>
<p>This is in the middle, performance-wise, taking <strong>about 14 seconds</strong>, relatively.</p>
<p>What can I do to keep relative performance close to the first example, with code that utilizes Linq's readability?</p>
<p>Note: I'm aware there are of many other optimizations possible, amongst others in the algorithm itself. In this case however, I'm specifically interested in the performance of Linq queries relative to more "oldskool" constructs, and how to keep Linq's nice syntax without giving up too much performance (if possible).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T22:45:14.377",
"Id": "29882",
"Score": "0",
"body": "In what world is a LINQ query more readable than a for loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T00:46:35.367",
"Id": "29890",
"Score": "4",
"body": "In the world of functional programming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T10:32:52.377",
"Id": "29894",
"Score": "0",
"body": "You're losing far more performance by using an inefficient algorithm. I'd expect sub millisecond runtime by simply calculating the least common multiple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T10:39:33.470",
"Id": "29897",
"Score": "0",
"body": "@CodesInChaos Aye, agreed, but as I already mention in my question I'm aware of that, and I'm trying to focus on investigating the difference between loops and linq."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T09:13:31.793",
"Id": "29957",
"Score": "0",
"body": "Btw, you can do `dividers.All(candidate.IsDivisibleBy)`. And I think your \"newskool\" vs \"oldskool\" concept is a wrong frame of mind - each tool has its uses, and none replaces the other."
}
] |
[
{
"body": "<p>How about breaking it across two functions:</p>\n\n<pre><code>private boolean IsDivisibleBy1to20(int solution)\n{\n for (int j = 1; j <= 20; j++)\n {\n if (solution % j != 0)\n return false;\n }\n return true;\n}\n\npublic int Solution_GotoVersion()\n{\n int solution = 1;\n while (solution++ < int.MaxValue)\n {\n if( IsDivisibleBy1to20(solution)\n {\n return solution;\n }\n }\n throw new Exception(\"Solution not found\");\n}\n</code></pre>\n\n<p>I think it would help with testability because you could test the divisibility thing seperately.</p>\n\n<p>Then there is this bit:</p>\n\n<pre><code> while (solution++ < int.MaxValue)\n</code></pre>\n\n<p>I think this actually works, although its a bit tricky due to post-increment and overflow concerns. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T10:34:02.610",
"Id": "29895",
"Score": "1",
"body": "You inverted the logic of `IsDivisibleBy1to20`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T15:32:20.273",
"Id": "29918",
"Score": "0",
"body": "@CodesInChaos, yet more reason to test one's code :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T17:23:43.867",
"Id": "18745",
"ParentId": "18743",
"Score": "5"
}
},
{
"body": "<p>Focus on optimizing the innermost loop. That's where the performance is lost. In particular try to minimize the number of indirect calls (<code>virtual</code> method, interface and delegate calls).</p>\n\n<p>Your LINQ code has ~60 of those. My variant 1 reduces them to ~20, and my variant 2 to only a handful.</p>\n\n<h2>Variant 1:</h2>\n\n<p>Very close to linq, but using <code>Array.TrueForAll</code>. About twice as fast are pure linq:</p>\n\n<pre><code>public int Solution_ArrayLinqVersion()\n{\n var dividers = Enumerable.Range(1, 20).ToArray();\n\n int solution = Enumerable\n .Range(1, int.MaxValue)\n .First(candidate\n => Array.TrueForAll(dividers, divider => candidate%divider==0));\n\n return solution;\n}\n</code></pre>\n\n<h2>Variant 2:</h2>\n\n<p>Use a loop for the division testing(inner loop) and linq for the outer loop. Almost as fast as no LINQ:</p>\n\n<pre><code>int LinqOutLoopInner()\n{\n return Enumerable\n .Range(1, int.MaxValue)\n .First(IsDivisibleBy1to20);\n}\n\nstatic bool IsDivisibleBy1to20(int candidate)\n{\n for (int j = 1; j <= 20; j++)\n {\n if (candidate % j != 0)\n return false;\n }\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T19:34:41.937",
"Id": "30140",
"Score": "0",
"body": "I upvoted (and learned from) the competing answers, but this one was closest to the question as I asked/phrased it. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T10:58:06.327",
"Id": "18763",
"ParentId": "18743",
"Score": "7"
}
},
{
"body": "<p>You can have both performance and readability using the newly-introduced (.NET 4.0) method <a href=\"http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.greatestcommondivisor%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>BigInteger.GreatestCommonDivisor</code></a> (a reference to <code>System.Numerics</code> is required).</p>\n\n<p>With the <code>BigInteger</code> stuct, you gain an additional advantage: your code will work for arbitrarily large numbers (assuming sufficient memory).</p>\n\n<pre><code>var result = ClosedInterval(1, 20).LeastCommonMultiple();\n</code></pre>\n\n<p>What we are looking for is the <em>least common multiple</em> of all natural numbers in the interval <code>[1, 20]</code>, so we'll need a method to generate them (closed means including both bounds and the numbers between):</p>\n\n<pre><code>static IEnumerable<BigInteger> ClosedInterval(BigInteger first, BigInteger last)\n{\n for (var i = first; i <= last; i++)\n {\n yield return i;\n }\n}\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Least_common_multiple#Reduction_by_the_greatest_common_divisor\" rel=\"nofollow\">From Wikipedia</a>, we know how to calculate the least common multiple of <em>two</em> numbers:</p>\n\n<pre><code>static BigInteger LeastCommonMultiple(BigInteger a, BigInteger b)\n{\n return (a * b) / BigInteger.GreatestCommonDivisor(a, b);\n}\n</code></pre>\n\n<p>For an <em>arbitrary number</em> of least common multiples, we simply aggregate them using LINQ and package the logic in an extension method:</p>\n\n<pre><code>static BigInteger LeastCommonMultiple(this IEnumerable<BigInteger> divisors)\n{\n return divisors.Aggregate(LeastCommonMultiple);\n}\n</code></pre>\n\n<hr>\n\n<p>The implementation calculates the correct result (232792560) in <strong>less than ten milliseconds</strong>. </p>\n\n<p>In less than half a second, you can find out the answer for an input of <code>[1, 20000]</code>; The solution is over eight thousand digits long and therefore somewhat outside the scope of this answer.</p>\n\n<hr>\n\n<p>What's really awesome:</p>\n\n<ul>\n<li><p>There is an implicit cast from <code>int</code> to <code>BigInteger</code>, so you can pass integer literals as arguments to <code>ClosedInterval</code></p></li>\n<li><p>The arithmetic operators are overloaded, so you can use the same syntax for dividing, multiplying, etc. as you would with the integral numeric types</p></li>\n<li><p><code>BigInteger</code> is <em>extremely optimized</em> for speed (the only thing to wary of is that it is a <code>struct</code>, and therefore exhibits different memory behaviour than reference types do). </p></li>\n<li><p>It turns out that the <strong>aggregation is <em>highly</em> parallelizable!</strong> Just using PLINQ like this:</p>\n\n<pre><code>static BigInteger LeastCommonMultiple(this IEnumerable<BigInteger> divisors)\n{\n return divisors.AsParallel().Aggregate(LeastCommonMultiple);\n}\n</code></pre>\n\n<p>leads to a performance improvement proportional to the number of cores in your machine. In my case, finding the least common multiple of all natural numbers between one and two hundred thousand completed in around six seconds (the sequential version took over 45). </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T18:49:33.153",
"Id": "29923",
"Score": "0",
"body": "If you want to optimize performance, implementing LCM like `if(a<b){return (a/GCD)*b);}else{return (b/GCD)*a;}` is probably a bit faster since it keeps the intermediate numbers smaller. But I didn't actually test it, so I might be wrong. Probably doesn't matter much in this case, since `b` is very small, but if both are large, I'd expect a gain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T18:58:10.463",
"Id": "29925",
"Score": "0",
"body": "@CodesInChaos yes, but this would be a lot more relevant for size-constrained types like `int` or `long` where you can prevent overflow using that technique."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T16:21:52.643",
"Id": "18773",
"ParentId": "18743",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18763",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T16:39:32.137",
"Id": "18743",
"Score": "7",
"Tags": [
"c#",
"performance",
"linq",
"programming-challenge"
],
"Title": "Keeping Linq's readability (e.g. over goto statements) without sacrificing performance"
}
|
18743
|
<p>I've recently had to print some national symbols in windows console using <code>Mingw</code> and found, that I got nothing in the output, if I use wide strings.</p>
<p>So, I studied the problem and found out that it is locale problem. I was unable to find somewhere complete solution, so I had to write something, that seems to work. </p>
<p>So, I decided to publish it here for review, or may be I should publish it somewhere it it worth.</p>
<ul>
<li>I've tested in Mingw 4.7.0 using Russian locale.</li>
<li>It should probably correctly convert wide strings to national OEM encoded strings.</li>
</ul>
<p><em>Code:</em></p>
<pre><code>#ifndef CUSTOM_LOCALE_H
#define CUSTOM_LOCALE_H
#if (__cplusplus >= 201103L)
#define CUSTOM_LOCALE_OVERRIDE override
#else
#define CUSTOM_LOCALE_OVERRIDE
#endif
#include <locale>
#include <iostream>
#include <windows.h>
namespace custom_locale
{
class CustomLocale : public std::codecvt <wchar_t, char, std::mbstate_t> {
public:
explicit CustomLocale ( size_t r = 0 ) : std::codecvt <wchar_t, char, std::mbstate_t> (r) {}
protected:
result do_in (state_type&, const char* from, const char* from_end,
const char*& from_next, wchar_t* to, wchar_t* to_end, wchar_t*& to_next ) const CUSTOM_LOCALE_OVERRIDE
{
std::size_t size = from_end - from;
std::size_t buffer_size = to_end - to;
std::size_t written = MultiByteToWideChar(CP_OEMCP, 0, from, size, to, buffer_size);
to_next = to + written;
if (written == 0) {
return error;
}
else if (written != buffer_size) {
return partial;
}
else {
return ok;
}
}
result do_out (state_type&, const wchar_t* from, const wchar_t* from_end,
const wchar_t*& from_next, char* to, char* to_end, char*& to_next ) const CUSTOM_LOCALE_OVERRIDE
{
std::size_t size = from_end - from;
std::size_t buffer_size = to_end - to;
std::size_t written = WideCharToMultiByte(CP_OEMCP, 0, from, size, to, buffer_size, 0, 0);
to_next = to + written;
if (written == 0) {
return error;
}
else if (written != buffer_size) {
return partial;
}
else {
return ok;
}
}
result do_unshift ( state_type&, char*, char*, char*& ) const CUSTOM_LOCALE_OVERRIDE { return ok; }
int do_encoding () const throw () CUSTOM_LOCALE_OVERRIDE { return 1; }
bool do_always_noconv () const throw () CUSTOM_LOCALE_OVERRIDE { return false; }
int do_length ( state_type& state, const char* from, const char* from_end, size_t max ) const CUSTOM_LOCALE_OVERRIDE
{
return std::codecvt <wchar_t, char, std::mbstate_t>::do_length ( state, from, from_end, max );
}
int do_max_length () const throw () CUSTOM_LOCALE_OVERRIDE
{
return std::codecvt <wchar_t, char, std::mbstate_t>::do_max_length ();
}
};
inline void init()
{
std::locale loc ( std::locale(), new CustomLocale() );
std::ios_base::sync_with_stdio (false);
std::wcout.imbue(loc);
std::wcin.imbue(loc);
}
}
#endif
</code></pre>
<p><em>Example:</em></p>
<pre><code>#include "custom_locale.h"
int main ()
{
custom_locale::init();
std::wstring s(L"привет");
std::wcout << s << '\n';
std::wstring u;
std::wcin >> u;
s += L' ' + u;
std::wcout << s << '\n';
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>This is a somewhat old question, but I have an alternative that may work for this. Related to <a href=\"https://stackoverflow.com/questions/26387054/how-can-i-use-stdimbue-to-set-the-locale-for-stdwcout\">this question</a>, if you turn off the synchronization with the underlying <code>stdio</code>, you can use <code>imbue</code> to set the locale for both <code>wcout</code> and <code>wcin</code>:</p>\n\n<pre><code>#include <locale>\n#include <string>\n#include <iostream>\n\nint main ()\n{\n // this code turns off the sync with stdio\n std::ios_base::sync_with_stdio(false);\n // now create the appropriate locale without setting the global one\n std::locale ru(\"ru_RU.utf8\");\n // use imbue to allow the Russian words to be properly displayed\n std::wcout.imbue(ru);\n // ... and input\n std::wcin.imbue(ru);\n\n // the rest of the code is essentially unchanged from the original\n std::wstring s(L\"привет\");\n std::wcout << s << '\\n';\n std::wstring u; \n std::wcin >> u;\n s += L' ' + u;\n std::wcout << s << '\\n';\n }\n</code></pre>\n\n<p>Using it in this way means that no custom class is required. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-21T13:25:31.803",
"Id": "212594",
"Score": "0",
"body": "Does it work with default windows console settings (code page 866 for ru)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-23T13:00:04.180",
"Id": "213097",
"Score": "0",
"body": "After doing some thorough testing, no, it does not work with that. I'll work on this further to see if I can at least simplify what you've already done (which I can also verify works)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T00:14:43.130",
"Id": "392942",
"Score": "0",
"body": "this does not work with `mingw64-x86_64-gcc-g++`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-20T16:17:56.313",
"Id": "114547",
"ParentId": "18746",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:38:22.110",
"Id": "18746",
"Score": "7",
"Tags": [
"c++",
"windows",
"io",
"i18n"
],
"Title": "Mingw, wcout and locales"
}
|
18746
|
<p>I am writing a simple-ish c# CLI app to improve our telephony reporting system. </p>
<p>At present, I have a nightly DTS package which dumps a couple of tables from the Cisco telephony box into a database on our corporate cluster. An hour later, I have a SQL Server Agent job that runs a variety of messy stored procedures to generate queue level statistics. </p>
<p>I was advised by a telephony consultant to do it this way, but have never been 100% happy with it, due to the lack or error handling.</p>
<p>I have found 6 stored procedures on the uccx Cisco telephony box, which are used by the Historical Cisco Reporting application. These contain a lot more statistics than I can currently provide.</p>
<p>So... my plan is as follows:</p>
<ol>
<li><p>Get a list of current queue names, including their open and close times from a SQL Server table</p></li>
<li><p>Run a stored procedure x amount of times, once for each queue, passing in the parameters from step 1</p></li>
<li><p>For each row generated from the stored procedure in step 2, write a row in a table on the SQL Server cluster</p></li>
<li><p>Do this for each stored procedure.</p></li>
</ol>
<p>My code, which works for one of the stored procedures <a href="https://gist.github.com/4081331" rel="nofollow">is here</a>. </p>
<p>It is very very basic, with poor errrmmm everything ha. I want to make this a bit more OO, remove duplicate code, and make it a bit better but I am not too great at that. </p>
<p>I can code, but not at a very advanced standard.</p>
<p>Any advice on how to tackle this beast? I am willing to learn new techniques, and am willing to chuck out what I've done thus far and start again. I really need to skill up, as I'll be getting more projects in a similar vein</p>
<p>Thanks guys and gals!</p>
<p>I have two classes, the main class and the logFile class:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
namespace UCCXtoSQL
{
public static class LogFile
{
public static void write(string logMessage)
{
string message = string.Empty;
string logFileLocation = @"C:\debug\UCCXtoSQL.log";
StreamWriter logWriter;
message = string.Format("{0}: {1}", DateTime.Now, logMessage);
if (!File.Exists(logFileLocation))
{
logWriter = new StreamWriter(logFileLocation);
}
else
{
logWriter = File.AppendText(logFileLocation);
}
logWriter.WriteLine(message);
logWriter.Close();
}
}
}
</code></pre>
<p>Main:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace UCCXtoSQL
{
class Program
{
static void Main(string[] args)
{
getData();
}
static void getData()
{
string connString = @"Data Source=uccx-pri\crssql;Initial Catalog=db_cra;Integrated Security=SSPI;";
string sql2k5ConnString = @"Data Source=sql2k5;Initial Catalog=db_cra;User Id=sqlsupport;Password=blahblahblah;";
string procedure = @"sp_csq_activity";
int id = 0;
//string queueName = @"|CSQ-SHG01";
SqlConnection conn = new SqlConnection(connString);
SqlConnection sql2k5conn = new SqlConnection(sql2k5ConnString);
DataTable csq = getCSQTable(sql2k5conn);
foreach (DataRow row in csq.Rows)
{
id++;
string name = row["CSQName"].ToString();
string open = row["CSQOpen"].ToString();
string close = row["CSQClose"].ToString();
string format = "yyyy-MM-dd ";
DateTime today = DateTime.Now.Date.AddDays(-1);
Console.WriteLine(id + " " + name);
LogFile.write(id + " " + name);
string paramstart = (today.ToString(format) + open);
string paramend = (today.ToString(format) + close);
Console.WriteLine("Queue open: " + paramstart);
Console.WriteLine("Queue close: " + paramend);
//var Open = TimeSpan.Parse(row["CSQOpen"].ToString());
//string statsDate = DateTime.Now.ToShortDateString();
//string newDateTime = statsDate + Open;
//Console.WriteLine("Converted " + newDateTime);
csqActivity(paramstart, paramend, procedure, name, conn, sql2k5conn);
}
}
private static void csqActivity(string pstart, string pend, string procedure, string queueName, SqlConnection conn, SqlConnection sql2k5conn)
{
try
{
queueName = @"|" + queueName;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(procedure, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
//da.SelectCommand.Parameters.Add(new SqlParameter("@starttime", "2012-11-08 08:30:00"));
//da.SelectCommand.Parameters.Add(new SqlParameter("@endtime", "2012-11-08 17:15:00"));
da.SelectCommand.Parameters.Add(new SqlParameter("@starttime", pstart));
da.SelectCommand.Parameters.Add(new SqlParameter("@endtime", pend));
da.SelectCommand.Parameters.Add(new SqlParameter("@csqlist", queueName));
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows)
{
//Console.WriteLine(row["CSQ_Name"]);
Console.WriteLine("Queue: {0} - Presented: {1}", row["CSQ_Name"], row["Calls_Presented"]);
LogFile.write("Queue: " + row["CSQ_Name"]);
LogFile.write("Presented: " + row["Calls_Presented"]);
InsertRecord(sql2k5conn, row, pstart, pend, queueName);
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
LogFile.write("Error: " + e);
}
finally
{
Console.WriteLine("Done");
conn.Close();
}
}
private static void InsertRecord(SqlConnection sql2k5conn, DataRow row, string start, string end, string queue)
{
try
{
DateTime startdate = Convert.ToDateTime(start);
DateTime endDate = Convert.ToDateTime(end);
sql2k5conn.Open();
SqlCommand sql2k5comm = new SqlCommand("insert_csq_activity", sql2k5conn);
sql2k5comm.CommandTimeout = 0;
sql2k5comm.CommandType = CommandType.StoredProcedure;
//sql2k5comm.Parameters.Add(new SqlParameter(/*PARAMNAME*/,/*PARAM*/);
sql2k5comm.Parameters.Add(new SqlParameter("@CSQ_Name", row["CSQ_Name"]));
//sql2k5comm.Parameters.Add(new SqlParameter("@CSQ_Name", queue));
sql2k5comm.Parameters.Add(new SqlParameter("@Call_Skills", row["Call_Skills"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Calls_Presented", row["Calls_Presented"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Avg_Queue_Time", row["Avg_Queue_Time"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Max_Queue_Time", row["Max_Queue_Time"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Calls_Handled", row["Calls_Handled"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Avg_Speed_Answer", row["Avg_Speed_Answer"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Avg_Handle_Time", row["Avg_Handle_Time"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Max_Handle_Time", row["Max_Handle_Time"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Calls_Abandoned", row["Calls_Abandoned"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Avg_Time_Abandon", row["Avg_Time_Abandon"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Max_Time_Abandon", row["Max_Time_Abandon"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Avg_Calls_Abandoned", row["Avg_Calls_Abandoned"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Max_Calls_Abandoned", row["Max_Calls_Abandoned"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Calls_Dequeued", row["Calls_Dequeued"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Avg_Time_Dequeue", row["Avg_Time_Dequeue"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Max_Time_Dequeue", row["Max_Time_Dequeue"]));
sql2k5comm.Parameters.Add(new SqlParameter("@Calls_Handled_by_Other", row["Calls_Handled_by_Other"]));
sql2k5comm.Parameters.Add(new SqlParameter("@CSQ_StartDateTime", startdate));
sql2k5comm.Parameters.Add(new SqlParameter("@CSQ_EndDateTime", endDate));
sql2k5comm.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
LogFile.write("Error: " + e);
}
finally
{
sql2k5conn.Close();
}
}
static DataTable getCSQTable(SqlConnection connection)
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("get_csqnames", connection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "csqTable");
DataTable dt = ds.Tables["csqTable"];
return dt;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T23:23:25.623",
"Id": "29886",
"Score": "1",
"body": "I've added the code from the URL. Don't want to seem as if I'm going off-topic :("
}
] |
[
{
"body": "<p>Your task falls into ETL (Extract-Tranform-Load) category, and SQL Server Integration Services (SSIS) is the service dedicated to ETL. You can actually implement all the processing described here using the SSIS package (next version of DTS), at it might result in faster and more reliable solution because SSIS uses stream-based processing and optimised interaction with SQL Server.</p>\n\n<p>If you still want to use .NET app to do the transfer then suggestion will vary depending on how much data do you need to transfer, and how likely you would need to maintain this solution in the future.</p>\n\n<ul>\n<li>If data volume is not large (i.e. less than a couple of thousands records) then you can keep using DataTables, otherwise it would be better to switch to streaming techniques (process the data while you load it)</li>\n<li>If it's a one-time implementation then usually it's not worth investing lots of efforts into clean design as long as program does the job.</li>\n</ul>\n\n<p>Since you've asked for suggestions to clean up the code, here is my list of what I would do with it:</p>\n\n<ol>\n<li>Apply <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms229045%28v=vs.100%29.aspx\" rel=\"nofollow\">.NET naming conventions</a> (don't use Hungarian notation in particular).</li>\n<li><p><code>write</code> method: use the <code>using</code> keyword for all disposable objects (<code>StreamWriter</code>) + you can initialise logWriter with a single line:</p>\n\n<pre><code>public static void Write(string logMessage)\n{\n const string logFileLocation = @\"C:\\debug\\UCCXtoSQL.log\";\n using (var logWriter = new StreamWriter(logFileLocation, true))\n {\n logWriter.WriteLine(string.Format(\"{0}: {1}\", DateTime.Now, logMessage));\n }\n}\n</code></pre></li>\n<li>Replace <code>DataSet</code>/<code>DataTable</code> with Entity Framework - that's the biggest change since it will remove all the manual <code>SqlCommand</code>/<code>SqlConnection</code>/<code>DataTable</code>/<code>DataSet</code>/<code>DataAdapter</code> processing in favor of typed data objects. <a href=\"http://msdn.microsoft.com/en-us/data/ee712907\" rel=\"nofollow\">Read more on Entity Framework</a> </li>\n<li>Replace your custom <code>LogFile</code> logging class with logging framework (log4net, NLog).</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T22:40:11.067",
"Id": "18819",
"ParentId": "18748",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18819",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:51:03.100",
"Id": "18748",
"Score": "1",
"Tags": [
"c#",
"sql",
"sql-server"
],
"Title": "How to dump UCCX stored procedure results via c# to SQL Server"
}
|
18748
|
<p>The following is code from a university practical I am doing. It reads in a txt file of twenty clients, whose information is stored in the txt file like this:</p>
<pre><code>Sophia Candappa F 23 00011
</code></pre>
<p>As per my lecturer's instructions, I have stored this information in a class called Client (although I know an ArrayList would be better I can't use it).<br>
The code below is a method that is used to compare all the clients to one another and determine if they are a match. They are a match if they are all of the following: </p>
<ol>
<li>Opposite sex </li>
<li>Age within five years of one another </li>
<li>They have three interests in common </li>
</ol>
<p>The latter is determined by the string "00011" in the example above. If the clients share the number "1" at the same place in the string on three or more occasions, then the third condition is satisfied.</p>
<p>My code works perfectly and outputs the desired result. However, I want to ask two questions.</p>
<ul>
<li><p>Is it as efficient as it could be (without ArrayLists)? I had considered separating out all the if/else statements into separate methods, but decided against it as I thought it wouldn't reduce any of the actual loops. </p></li>
<li><p>How can I change the output slightly. Currently, if a client is matched it displays "[Client Name] is compatible with" then it takes a new line and outputs all the clients who are matched. I would like to change it so that if the client has just one match, it says "Client Name is compatible with"..., but if the client has two or more clients it says "Client Name is compatible with the following [two/three/four] clients...</p></li>
</ul>
<p>I have tried doing the latter, but I always mess up the formatting. Thanks in advance for any help that can be offered.</p>
<pre><code>public static void matchClients(Client[] clientDetails)
{
boolean anyMatch;
int count;
for (int b = 0; b < numberOfClients; b++)
{
anyMatch = false;
count = 0;
for (int c = 0; c < numberOfClients; c++)
{
if (clientDetails[b].getClientGender()!=clientDetails[c].getClientGender())
{
if (Math.abs(clientDetails[b].getClientAge() - clientDetails[c].getClientAge()) <= 5)
{
int interests = 0;
String clientOneInterests = clientDetails[b].getClientInterests();
String clientTwoInterests = clientDetails[c].getClientInterests();
int interestNumber = 0;
while (interestNumber < clientOneInterests.length())
{
if ((clientOneInterests.charAt(interestNumber) == clientTwoInterests.charAt(interestNumber))
&& (clientOneInterests.charAt(interestNumber) == '1' ))
interests++;
interestNumber++;
}
if (interests >= 3)
{
anyMatch = true;
if (count == 0)
{
System.out.println(clientDetails[b].getClientName() + "is compatible with the following client(s)");
System.out.println("\t" + clientDetails[c].getClientName());
}
else
{
System.out.println("\t" + clientDetails[c].getClientName());
}
count++;
}
interests = 0;
}
}
}
if (anyMatch == false)
System.out.println(clientDetails[b].getClientName() + "is not compatible with any client.");
System.out.println("");
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>You should extract out at least two methods:</p>\n\n<pre><code>boolean isMatchingClients(final Client client, final Client otherClient) { ... }\nint calculateCommonInterests(final String clientInterests, \n final String otherClientInterests) { ... }\n</code></pre>\n\n<p>It would improve readabilily a lot and make the code <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">more flatten</a>.</p>\n\n<p>I usually prefer <code>final</code> variables. Making a variable <code>final</code> relieves the programmer of excess mental juggling - he/she doesn't have to scan through the code to see if the variable has changed. (From <a href=\"https://softwareengineering.stackexchange.com/a/98796/36726\">@nerdytenor's answers.</a>)</p></li>\n<li><p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. </p>\n\n<p>For example, the <code>count</code> variable could be right before the second <code>for</code> loop:</p>\n\n<pre><code>int count = 0;\nfor (int c = 0; c < numberOfClients; c++)\n</code></pre>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>If it's possible I'd consider storing the interest data in <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/BitSet.html\" rel=\"nofollow noreferrer\"><code>BitSet</code></a>s. Then it would be possible to <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/BitSet.html#and%28java.util.BitSet%29\" rel=\"nofollow noreferrer\"><code>and</code></a> two of them and get the number of common bits with the <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/BitSet.html#cardinality%28%29\" rel=\"nofollow noreferrer\"><code>cardinality</code></a> method. Here is some test code:</p>\n\n<pre><code>@Test\npublic void testBitSet() {\n final BitSet interestBitSet = createBitSetFromString(\"11100111\");\n final BitSet otherInterestBitSet = createBitSetFromString(\"11001001\");\n\n final BitSet clone = (BitSet) interestBitSet.clone();\n clone.and(otherInterestBitSet);\n\n assertEquals(3, clone.cardinality());\n}\n\nprivate BitSet createBitSetFromString(final String input) {\n final BitSet result = new BitSet();\n\n final char[] inputArray = input.toCharArray();\n for (int index = 0; index < inputArray.length; index++) {\n if (inputArray[index] == '1') {\n result.set(index);\n }\n }\n return result;\n}\n</code></pre>\n\n<p>The <code>and</code> method modifies the bitset which is a disadvantage here. Cloning helps, although it's not the most beautiful solution.</p></li>\n<li><p>Instead of </p>\n\n<pre><code>System.out.println(\"\");\n</code></pre>\n\n<p>you could use</p>\n\n<pre><code>System.out.println();\n</code></pre></li>\n<li><p>You could remove some duplication:</p>\n\n<pre><code>if (count == 0) {\n System.out.println(clientDetails[b].getClientName() + \"is compatible with the following client(s)\");\n System.out.println(\"\\t\" + clientDetails[c].getClientName());\n} else {\n System.out.println(\"\\t\" + clientDetails[c].getClientName());\n}\n</code></pre>\n\n<p>The following is the same:</p>\n\n<pre><code>if (count == 0) {\n System.out.println(clientDetails[b].getClientName() + \"is compatible with the following client(s)\");\n}\nSystem.out.println(\"\\t\" + clientDetails[c].getClientName());\n</code></pre></li>\n<li><p>I'd create local variables for <code>clientDetails[b]</code> and <code>clientDetails[c]</code>. They are used a lot.</p></li>\n<li><p>About the output: if you want to show the number of compatible clients in the header you have to count them (and maybe store them in an <code>ArrayList</code> to avoid running the loop twice) before printing the header. If you are not allowed to use <code>ArrayList</code>s I don't think that it's worth it.</p></li>\n<li><p>I don't know what's the type of the <code>clientGender</code> field. If it's <code>String</code>, you should not compare it with <code>!=</code> or <code>==</code>. See: <a href=\"https://stackoverflow.com/questions/767372/java-string-equals-versus\">Java String.equals versus ==</a></p></li>\n<li><p>The <code>anyMatch</code> variable is duplicated, it could be eliminated. It only stores the state whether <code>count == 0</code> or not.</p>\n\n<pre><code>final boolean anyMatch = (count > 0);\nif (anyMatch) { \n ... \n}\n</code></pre></li>\n</ol>\n\n<p>Some optimization ideas:</p>\n\n<ol>\n<li><p>Use two arrays: one for males, one for females, so you don't have to compare clients with the same sex.</p></li>\n<li><p>Order the arrays by age and skip the definitely non-matching clients. You could use binary search here.</p></li>\n<li><p>Use a two-dimensional array with the first dimension as the age. The second dimension contains the clients with the corresponding age.</p></li>\n<li><p>You could use one array which is sorted by gender then age. You could use <code>Arrays.sort</code> and a custom <code>compareTo</code> method in the <code>Client</code> class:</p>\n\n<pre><code>@Override\npublic int compareTo(final Client o) {\n final int nameResult = name.compareTo(o.name);\n if (nameResult != 0) {\n return nameResult;\n }\n return age - o.age;\n}\n</code></pre></li>\n</ol>\n\n<p>Finally, here is my two methods after the refactorings mentioned above:</p>\n\n<pre><code>public static void matchClients(final Client[] allClients) {\n for (final Client client: allClients) {\n checkClient(client, allClients);\n }\n}\n\nprivate static void checkClient(final Client client, final Client[] allClients) {\n int matchCount = 0;\n for (final Client otherClient: allClients) {\n if (!isMatchingClients(client, otherClient)) {\n continue;\n }\n if (matchCount == 0) {\n System.out.println(client.getClientName() + \n \"is compatible with the following client(s)\");\n }\n System.out.println(\"\\t\" + otherClient.getClientName());\n matchCount++;\n }\n final boolean anyMatch = (matchCount > 0);\n if (!anyMatch) {\n System.out.println(client.getClientName() + \n \"is not compatible with any client.\");\n }\n System.out.println();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T20:55:23.063",
"Id": "29874",
"Score": "0",
"body": "Thanks for all your advice. I did originally use methods. Was this the correct way to do it: If client[a].gender != client[b].gender then call method compareAge, passing as parameters the actual array and the two client elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T20:56:47.350",
"Id": "29875",
"Score": "0",
"body": "Also, where would you declare the local variables? I declared them at the very start because they are used after every iteration of the first second for loop (meaning if I declared them after first for loop they would be re-declared everytime, thus generating an error)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T21:01:25.840",
"Id": "29876",
"Score": "0",
"body": "And forgive me, but I have to ask a third question! In your first comment, you mention creating different methods. Why have you passed the objects as 'final'? Why not just pass them as Client clientone?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T21:08:44.607",
"Id": "29877",
"Score": "0",
"body": "With regards to your three optimization ideas, from my understanding of our lecturer's instructions, we have to use just one array (an array of objects - our first time doing this). Also, the array is currently arranged by gender, so I don't know if it is worth sorting it by age, as although it will speed up age comparison, it would slow down gender comparison?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T22:49:48.670",
"Id": "29883",
"Score": "0",
"body": "@AndrewMartin: See the edit, please. Feel free to ask if you have further questions or miss one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T23:09:10.263",
"Id": "29884",
"Score": "0",
"body": "Thanks for all your help. I'll read through it all now and try and implement as much as I can. One final note however - as all the client interests are held in a String like this \"10010\", when I try and use BitSet (which I have no prior experience of), I only get an output of two (zero and one) for every client. How can I fix that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T00:18:46.913",
"Id": "29889",
"Score": "0",
"body": "@AndrewMartin: You might want to post that part of the code to Stack Overflow. Anyway, I've added some sample code to the answer."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T20:47:28.497",
"Id": "18752",
"ParentId": "18750",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18752",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T19:17:49.413",
"Id": "18750",
"Score": "2",
"Tags": [
"java"
],
"Title": "Rewriting nested for loops to give better formatted output"
}
|
18750
|
<p>I recently started game development, but one of the things that I never put much thought to was the loading of images. I'm curious as to advice for improving my current code on loading images. I'm using cocos2d in iOS code, but if you know of optimization techniques in other languages I'd like to hear that as well.</p>
<pre><code>//above the @implementation
#define kZLayerBase -1
#define kOffsetImg1 (-50)
#define kOffsetImg2 (50)
#define kPositionXImg1 (screenSize.width/2)
#define kPositionYImg1 (screenSize.height/2)
#define kPositionXImg2 kPositionXImg1
#define kPositionYImg2 kPositionYImg1
#define kWidthImg1 100
#define kHeightImg1 100
#define kWidhtImg2 100
#define kHeightImg2 100
//...
//individually
-(void)loadImages1{
CGSize screenSize = [[CCDirector sharedDirector] winSize];
CCSprite *img1 = [CCSprite spriteWithFile:@"img1.png"];
[img1 setPosition:ccp(kPositionXImg1, kPositionImg1)];
[self addChild:img1 z:kTagLayerBase];
CCSprite *img2 = [CCSprite spriteWithFile:@"img2.png"];
[img2 setPosition:ccp(kPositionXImg2, kPositionImg2)];
[self addChild:img2 z:kTagLayerBase];
}
//using a sprite sheet
-(void)loadImages2{
CCSprite *img1 = [CCSprite spriteWithFile:@"img.png" rect:CGRectMake(kWidthBean*0, kHeightBean*0, kWidthBean, kHeightBean)];
[img1 setPosition:ccp(kPositionXImg1, kPositionImg1)];
[self addChild:img1 z:kTagLayerBase];
CCSprite *img2 = [CCSprite spriteWithFile:@"img.png" rect:CGRectMake(kWidthBean*1, kHeightBean*0, kWidthBean, kHeightBean)];
[img2 setPosition:ccp(kPositionXImg2, kPositionImg2)];
[self addChild:img2 z:kTagLayerBase];
}
</code></pre>
<p>As you can see in <code>loadImages1</code>, I've basically just made 2 images, and loaded them separately.</p>
<p>I'm curious on your input on this:</p>
<ul>
<li>Is this slow or a bad way to load images? </li>
<li>Is there some sort of sprite cache in cocos2d?</li>
<li>If this wasn't using ARC, does this ever pose a memory problem?</li>
</ul>
<p>As you can see in <code>loadImages2</code>, I tried having a sprite sheet and loading from there.</p>
<p>I'm curious:</p>
<ul>
<li>Is this better way to load images than the first?</li>
<li>Is there a way to load the picture at once and then just pick out segments of it? The code seems to keep reloading the same image.</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n <p>is this slow or a bad way to load images?</p>\n</blockquote>\n\n<p>Actually, yes and no. Cocos-2d goes the smart route and caches your sprite image internally, which makes the sprite's image not only re-useable, but it drastically speeds up the next time the method is called during program execution (it doesn't have to read an image off the disk into memory).</p>\n\n<p>At the same time, you have access to sprite-sheet optimizations, so why not use them? It's much cheaper to load a large sprite sheet of 10-20 sprites, than to query the disk and load 10-20 images.</p>\n\n<blockquote>\n <p>is there some sort of sprite cache in cocos2d?</p>\n</blockquote>\n\n<p>See above. The class is called <a href=\"https://github.com/insurgentgames/teh-internets/blob/master/cocos2d/CCTextureCache.m\" rel=\"nofollow\">CCTextureCache</a>, and it actually does some very low-level caching of the image (depending on your version of Cocos, it should even drop into OGL territory).</p>\n\n<blockquote>\n <p>if this wasn't using ARC, does this ever pose a memory problem?</p>\n</blockquote>\n\n<p>Actually, no. Convenience constructors (<code>+[CCSprite spriteWithFile:]</code>) are supposed to return autoreleased objects under MRC. Your local variables would be owned by you (0 -> 1), then autoreleased and crushed when they fell out of scope (1 -> 0).</p>\n\n<blockquote>\n <p>is this better way to load images than the first?\n is there a way to load the picture at once and then just pick out segments of it? the code seems to keep reloading the same image</p>\n</blockquote>\n\n<p>No, and Yes (respectively). I will direct you to one <a href=\"http://www.raywenderlich.com/2361/how-to-create-and-optimize-sprite-sheets-in-cocos2d-with-texture-packer-and-pixel-formats\" rel=\"nofollow\">Ray Wenderlich</a>, who has written more thoroughly on the subject than I.</p>\n\n<p><strong>A note on <code>#defines</code></strong></p>\n\n<p>Defines are ultimately abstractions away from text. They are not magic, they are not intrinsic, and they are not smart. If you want truly good constants (which is really what you are using), define them as</p>\n\n<p><code>static CGFloat const myVarName = someConstValue;</code></p>\n\n<p>Although, <code>kPositionXImg1</code> and <code>kPositionYImg1</code> cannot be made into compile-time constants by definition, those can stay defined, however it would be quite a bit more readable to just eliminate the macro altogether and inline it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T20:57:45.207",
"Id": "30149",
"Score": "0",
"body": "Wow. thanks so much for your answer, this explains a lot!! the only reason i haven't accepted is to wait a little while to see if anyone else is going to give it a shot, but this is pretty darn awesome, thanks!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T07:40:18.233",
"Id": "18875",
"ParentId": "18757",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T05:42:18.417",
"Id": "18757",
"Score": "1",
"Tags": [
"performance",
"image",
"objective-c",
"ios"
],
"Title": "Loading of images"
}
|
18757
|
<p>First off, I will try to explain the problem and then I will show you the code I have come up with so far.</p>
<p>I've got a list of properties. Each property has a tag of type int and a value of one of the following types: (bool, string, int, long).
some sample properties:</p>
<blockquote>
<p>tag: 1, value: "some string"<br>
tag: 14, value: true<br>
tag: 20, value: 123</p>
</blockquote>
<p>There is also a list of rules. Each rule is like a property, plus one of the following operators: (<, >, <=, >=, ==, !=, startsWith). The <em>startsWith</em> operator is used to check whether one string starts with another one.</p>
<p>Some sample rules:</p>
<blockquote>
<p>tag: 1, value: "hello", operator: ==<br>
tag: 14, value: true, operator: == </p>
</blockquote>
<p>Each list of rules is called a <code>Criteria</code> and is used to validate a list of properties. A criteria validates a list of properties if only all the rules of the criteria are met. For example, the two rules above make up a criteria. This criteria does not validate the aforementioned list of properties because the 1st rule forces the value of tag (1) to be equal (==) to "hello" which is not. </p>
<p>The following criteria:</p>
<blockquote>
<p>tag: 1, value: "some string", operator: ==<br>
tag: 20, value: 100, operator: ><br>
tag: 20, value: 120, operator: <</p>
</blockquote>
<p>does not validate the above properties too, because although the first two rules are met, the last rule, which forces the value of tag (20) to be less than 120 is not true. Therefore the whole criteria does not validate the properties.<br>
And here is a criteria that validates to true:</p>
<blockquote>
<p>tag: 1, value: "some", operator: startsWith<br>
tag: 14, value: false, operator: !=<br>
tag: 20, value: 123, operator: >=<br>
tag: 20, value: 100, operator: ></p>
</blockquote>
<p>So the final code will look like something like this:</p>
<pre><code>Param* properties = new Param[MAX_PARAMS];
properties[1] = Param("something"); // tag 1 => value: "something"
properties[2] = Param(12); // tag 2 => value: 12
properties[3] = Param(20); // tag 3 => value: 20
properties[4] = Param(string("bye")); // tag 4 => value: "bye"
multimap<int, Rule> rules;
rules.insert(RulePair(1, Rule("some", SW))); // the value of tag 1 should start with "some"
rules.insert(RulePair(3, Rule(20, LTE))); // the value of tag 3 should be <= 20
rules.insert(RulePair(3, Rule(10, SW))); // the value of tag 3 should be start with 10 (which is a meaningless rule)
rules.insert(RulePair(2, Rule(10, GT))); // the value of tag 2 should be > 10
rules.insert(RulePair(4, Rule("bye1", EQ))); // the value of tag 4 should be equal to "bye1"
if(CheckRules(rules, properties))
{
cout << "everything is fine!" << endl;
}
</code></pre>
<p>And this is the whole code that I have come up with. I have used <code>boost::variant</code> to be able to store and compare different types in a single map. In the following code I have supposed I only need properties of type either <code>string</code> or <code>int</code>, but new types can be easily added. Any advice on improving the readability, performance or efficiency of this code is appreciated!</p>
<pre><code>#include <map>
#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"
#define MAX_PARAMS 1000
using namespace std;
using namespace boost;
typedef variant<string, int> MyVariant;
struct IsEqual
{
MyVariant mValue;
bool operator()( MyVariant &other ) const
{
return mValue == other;
}
IsEqual( MyVariant const& value ):mValue(value) {}
};
struct IsLessThan
{
MyVariant mValue;
bool operator()( MyVariant &other ) const
{
return other < mValue;
}
IsLessThan( MyVariant const& value ):mValue(value) {}
};
struct IsLessThanEqual
{
MyVariant mValue;
bool operator()( MyVariant &other ) const
{
return other < mValue || other == mValue;
}
IsLessThanEqual( MyVariant const& value ):mValue(value) {}
};
struct IsGreaterThan
{
MyVariant mValue;
bool operator()( MyVariant &other ) const
{
return !(other < mValue) && !(other == mValue);
}
IsGreaterThan( MyVariant const& value ):mValue(value) {}
};
struct IsGreaterThanEqual
{
MyVariant mValue;
bool operator()( MyVariant &other ) const
{
return !(other < mValue);
}
IsGreaterThanEqual( MyVariant const& value ):mValue(value) {}
};
class StartsWith
: public boost::static_visitor<bool>
{
public:
string mPrefix;
bool operator()(string &other) const
{
return other.compare(0, mPrefix.length(), mPrefix) == 0;
}
template<typename U>
bool operator()(U &other)const
{
return false;
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
enum Operator
{
EQ, // ==
NEQ, // !=
GT, // >
GTE, // >=
LT, // <
LTE, // <=
SW, // Starts With
};
string GetOperatorString(Operator op)
{
switch (op)
{
case EQ:
return "=";
case NEQ:
return "!=";
case GT:
return ">";
case GTE:
return ">=";
case LT:
return "<";
case LTE:
return "<=";
case SW:
return "should start with";
}
return "";
}
class Rule : public boost::static_visitor<bool>
{
public:
MyVariant v;
string mPrefix;
Operator mOperator;
bool operator()(MyVariant &other) const
{
if (mOperator == EQ)
{
return IsEqual(v)(other);
}
else if (mOperator == NEQ)
{
return !IsEqual(v)(other);
}
else if (mOperator == LT)
{
return IsLessThan(v)(other);
}
else if (mOperator == LTE)
{
return IsLessThanEqual(v)(other);
}
else if (mOperator == GT)
{
return IsGreaterThan(v)(other);
}
else if (mOperator == GTE)
{
return IsGreaterThanEqual(v)(other);
}
else if (mOperator == SW)
{
return apply_visitor(StartsWith(mPrefix), other);
}
}
Rule(MyVariant &v_, Operator op):v(v_),mOperator(op){}
Rule(string &prefix, Operator op):v(prefix), mPrefix(prefix),mOperator(op){}
Rule(const char* prefix, Operator op):v(prefix), mPrefix(prefix),mOperator(op){}
Rule(int _v, Operator op):v(_v), mOperator(op){}
Rule(){}
};
typedef multimap<int, Rule>::iterator RulesItr;
class Param
{
public:
Param():mAvailable(false){}
Param(MyVariant v):mAvailable(true), mValue(v){}
bool IsAvailable(){return mAvailable;}
MyVariant GetValue(){return mValue;}
private:
bool mAvailable;
MyVariant mValue;
};
bool CheckRules(multimap<int, Rule> rules, Param* properties)
{
if (rules.empty()) return true;
RulesItr nextRule = rules.begin();
int nextPropTag = 0;
Param* property;
while (nextRule != rules.end())
{
nextPropTag = nextRule->first;
if (nextPropTag >= MAX_PARAMS) return false;
property = &properties[nextPropTag];
if (!property->IsAvailable()) return false;
MyVariant propertyValue = property->GetValue();
while (nextRule != rules.end() && nextRule->first == nextPropTag)
{
Rule &tester = nextRule++->second; // read and go forward
cout << "rule: " << propertyValue << " " << GetOperatorString(tester.mOperator) << " " << tester.v;
if (!tester(propertyValue))
{
cout << ": Failed!" << endl;
return false;
}
cout << ": OK!" << endl;
}
} // while
return true;
}
typedef pair<int, Rule> RulePair;
int main(int argc, char **argv)
{
Param* properties = new Param[MAX_PARAMS];
properties[1] = Param("something"); // tag 1 => value: "something"
properties[2] = Param(12); // tag 2 => value: 12
properties[3] = Param(20); // tag 3 => value: 20
properties[4] = Param(string("bye")); // tag 4 => value: "bye"
multimap<int, Rule> rules;
rules.insert(RulePair(1, Rule("some", SW))); // the value of tag 1 should start with "some"
rules.insert(RulePair(3, Rule(20, LTE))); // the value of tag 3 should be <= 20
rules.insert(RulePair(3, Rule(10, SW))); // the value of tag 3 should be start with 10 (which is a meaningless rule)
rules.insert(RulePair(2, Rule(10, GT))); // the value of tag 2 should be > 10
rules.insert(RulePair(4, Rule("bye1", EQ))); // the value of tag 4 should be equal to "bye1"
if (CheckRules(rules, properties))
{
cout << "everything is fine!" << endl;
}
else
{
cout << "rule mismatch!" << endl;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>I would get rid of the if-else statement in operator() of Rule, and replace it with a stored <code>apply_visitor</code> functor, or move the <code>apply_vistor</code> from operator() of Rule into StartsWith and make all of your checkers have the same signature.</p>\n\n<p>Suppose we go with moving <code>apply_visitor</code> into StartsWith.</p>\n\n<p>Then <code>Rule</code> stores a <code>std::function< bool( MyVariant const& other ) > check;</code>, which you produce once at <code>Rule</code> construction (possibly through a big if-else block, but you only run that block once). Then operator() on <code>Rule</code> just calls that check on the input parameter.</p>\n\n<p>If I was to go further, I'd work on rule-factories. A rule-factory is a function that takes a MyVariant and produces a <code>std::function< bool( MyVariant const& other ) ></code>. Then register a rule factory for each enum entry. And now your <code>Rule</code> class itself goes away -- a <code>Rule</code> is just any <code>std::function</code> that takes a <code>MyVariant</code> and returns true or false.</p>\n\n<p>The end syntax looks like:</p>\n\n<pre><code>typedef std::function< bool(MyVariant const&) > Rule;\ntypedef std::function< Rule(MyVariant) > RuleFactory;\n\nclass MetaFactory\n{\npublic:\n std::map<Operator, RuleFactory> m_factories;\n MetaFactory()\n {\n m_factories[EQ] = [](MyVariant left){return [left](MyVariant right){return left == right;};};\n m_factories[NEQ] = [](MyVariant left){return [left](MyVariant right){return left != right;};};\n m_factories[GT] = [](MyVariant left){return [left](MyVariant right){return left>right;};};\n m_factories[GTE] = [](MyVariant left){return [left](MyVariant right){return left>=right;};};\n m_factories[LT] = [](MyVariant left){return [left](MyVariant right){return left<right;};};\n m_factories[LTE] = [](MyVariant left){return [left](MyVariant right){return left<=right;};};\n m_factories[LTE] = [](MyVariant left){return [left](MyVariant right){return apply_visitor(StartsWith(left), right);};};\n }\n static std::function<bool(MyVariant const&)> AlwaysFalseFactory(MyVariant var)\n {\n return [](MyVariant const&){return false;};\n }\n RuleFactory GetFactory( Operator op )\n {\n auto it = m_factories.find(op);\n Assert(it != m_factories.end());\n if (it == m_factories.end())\n return RuleFactory::AlwaysFalseFactory;\n return *it;\n }\n};\n\ntypedef std::vector<std::pair<int,MyVariant>> Params;\n\nbool CheckRules(std::multimap<int,Rule> const& rules, Params const& params)\n{\n for (auto it = params.begin(); it != params.end(); ++it)\n {\n auto rules = rules.equal_range( it->first );\n for (auto rule = rules.first; rule != rules.second; ++rule)\n {\n if(!(*rule)(it->second))\n return false;\n }\n }\n return true;\n}\n\nint main()\n{\n Params params;\n params.push_back( std::make_pair(1, \"something\") );\n params.push_back( std::make_pair(2, 12 ) );\n params.push_back( std::make_pair(3, 20 ) );\n params.push_back( std::make_pair(4, \"bye\" ) );\n\n MetaFactory meta;\n std::multimap<int, Rule> rules;\n rules.insert( std::make_pair( 1, meta.GetFactory(SW)(\"some\") ) );\n rules.insert( std::make_pair( 3, meta.GetFactory(LTE)(20) ) );\n rules.insert( std::make_pair( 3, meta.GetFactory(SW)(10) ) );\n rules.insert( std::make_pair( 2, meta.GetFactory(GT)(10) ) );\n rules.insert( std::make_pair( 4, meta.GetFactory(EQ)(\"bye1\") ) );\n\n if (CheckRules( rules, params ) )\n {\n cout << \"everything is fine!\\n\";\n }\n else\n {\n cout << \"rule failed!\\n\";\n }\n}\n</code></pre>\n\n<p>now, the above doesn't have diagnostics in it. But I hope you get the idea -- don't use a class when a function will do.</p>\n\n<p>I might make a <code>Rule</code> a pair of tests and error message <code>std::function<std::string(MyVariant const&)</code>s even, with the error message optional. This would give you diagnostics as well. Or the return value could be a pair of <code>bool,std::string</code>, where a true bool means \"passed with a possible warning\", and false means \"failed with a descriptive error\".</p>\n\n<p>But you might not want to go this far. :)</p>\n\n<p>...</p>\n\n<p>If you lack C++11, this is a patch on the above:</p>\n\n<pre><code>template<typename Test>\nstruct RuleInstance\n{\n Test test;\n MyVariant left;\n RuleInstance( MyVariant v, Test t ):test(t),left(v) {}\n bool operator()(MyVariant const& right) const\n {\n return test(left, right);\n }\n};\n\ntemplate<typename Test>\nstruct FactoryInstance\n{\n Test test;\n FactoryInstance(Test t):test(t) {}\n Rule operator()(MyVariant var) const\n {\n return RuleInstance<Test>(var, test);\n };\n};\n\ntemplate<typename Test>\nFactoryInstance<Test> make_factory( Test t ) { return t; };\n\n// replace m_factories[EQ] = [](MyVariant left){return [left](MyVariant right){return left == right;};}; with:\n // make this somewhere (a binary test function):\n bool LessMyVariant( MyVariant const& left, MyVariant const& right ) { return left < right; }\n\n // create the factory of rules like this:\n m_factories[EQ] = make_factory( LessMyVariant );\n</code></pre>\n\n<p>but the as you can see, this gets rid of lots of brevity.</p>\n\n<p>On the other hand, this continues to be data-driven: having uniform code behavior, controlled by data, is often a boon to debugging. You can validate data easier than you can validate code!</p>\n\n<p>Less effort was put into optimizing the C++03 version than the C++11 version, but the hit may be minimal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T06:31:51.380",
"Id": "29937",
"Score": "0",
"body": "Thank you! I will give your solution a try. The only point that you probably missed is that `boost::variant` only supports the `==` and `<` operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T06:37:02.880",
"Id": "29938",
"Score": "0",
"body": "I think you have used lambda expressions in `MetaFactory`. Could you replace them with something else since I am afraid I may not be able to use C++0x features. (maybe if you could replace them with the equivalent boost syntax)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T07:45:21.777",
"Id": "29943",
"Score": "0",
"body": "About storing the params, I have used an array, which is still sorted like a map, given that the key to access each param is its index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-19T12:49:32.680",
"Id": "31612",
"Score": "0",
"body": "Please correct the return value of `make_factory`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T21:44:44.410",
"Id": "18782",
"ParentId": "18762",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18782",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T10:55:14.963",
"Id": "18762",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Comparing sets of different types using variants"
}
|
18762
|
<p>I need some guidance on making the following code more idiomatic:</p>
<pre><code>(ns cheaterpress.algorithm
(:use [clojure.string :only [split lower-case]])
(:use [clojure.test]))
(def words (split (slurp "words") #"\s"))
(defn string-to-letter-hash [string]
(loop [letters (seq string) letter-hash {}]
(if (empty? letters)
letter-hash
(let [letter (first letters) letter-freq (get letter-hash letter 0)]
(recur (rest letters) (assoc letter-hash letter (inc letter-freq)))))))
(defn can-play [word letters index]
(loop [letters letters index index]
(if (and (= (inc index) (count word)) (not (= 1 (count word))))
true
(let [letter (get word index) frequency (get letters letter 0)]
(when (not (= 0 frequency))
(recur (assoc letters letter (dec frequency)) (inc index)))))))
(println
(time
(count (doall (filter #(can-play % (string-to-letter-hash "abcdefghijklmnopqrstuvxyz") 0) (map lower-case words))))))
</code></pre>
<p><code>string-to-letter-hash</code> takes a string and returns a map with the letter frequencies, e.g.:</p>
<pre><code>(string-to-letter-hash "hello")
;=> {\h 1 \e 1 \l 2 \o 1}
</code></pre>
<p><code>can-play</code> takes a letter frequency hash and a word, and then it finds out if it can make the word from the letters in the hash map. If it can, it returns true, otherwise, nil.</p>
<pre><code>(can-play "hello" {\h 1 \e 1 \l 2 \o 1} 0)
;=> true
(can-play "lol" {\h 1 \e 1 \l 2 \o 1} 0)
;=> true
(can-play "hello world" {\h 1 \e 1 \l 2 \o 1} 0)
;=> nil
</code></pre>
<p>The last bit of code in my script basically gets all the words in a file and finds which of them can be played according to the <code>can-play</code> function.</p>
|
[] |
[
{
"body": "<p>Well there is a standard library function: frequences :)</p>\n\n<pre><code>user> (doc frequencies)\n-------------------------\nclojure.core/frequencies\n([coll])\n Returns a map from distinct items in coll to the number of times\n they appear.\n</code></pre>\n\n<p>Since in Clojure many many types can be converted to sequences, frequencies will work on many types, including strings. In Clojure you can get an amazing amount of work done simply by using the sequence library. So your <code>string-to-letter-hash</code> is actually just an example of <code>frequences</code>.</p>\n\n<p>For your <code>can-play</code>: the same type of thinking applies. Try to resist your first impulse of writing a loop. The Clojure library functions will almost always do the job - the thing that requires training is knowing the library well enough to find a good way to compose the functions.</p>\n\n<pre><code>(defn can-play? [word freqs]\n (every? #(>= % 0) (vals (merge-with - freqs (frequencies word)))))\n</code></pre>\n\n<p>(updated to comment version: <a href=\"https://gist.github.com/4105644\" rel=\"nofollow\">https://gist.github.com/4105644</a>) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:30:12.933",
"Id": "29906",
"Score": "0",
"body": "What about the case `(every? (complement nil?) (map (frequencies \"helloworld\") \"hellohellohello\"))`? This will return true, but the word cannot be formed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:38:04.190",
"Id": "29908",
"Score": "0",
"body": "Also the behavior of: `(every? freqs word)` is equivalent to what you described, yeah? http://clojuredocs.org/clojure_core/clojure.core/every_q"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:48:41.453",
"Id": "29909",
"Score": "0",
"body": "I figured it out with multiple letters and frequencies I believe! https://gist.github.com/4105644"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T14:14:03.437",
"Id": "18769",
"ParentId": "18767",
"Score": "3"
}
},
{
"body": "<p>Here is an implementation with recursion over the remaining letters and letter set:</p>\n\n<pre><code>(defn can-play [word available]\n (loop [[s & stem] (clojure.string/replace word #\"\\W\" \"\") available available]\n (or (nil? s) ;; no more letters to check\n (and (pos? (available s 0)) ;; first letter must be in letterbox...\n ;; ...and the rest of the word must be playable after removing one\n ;; first instance of the first letter from the box\n (recur stem (update-in available [s] dec))))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-10T11:06:58.307",
"Id": "31047",
"ParentId": "18767",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "18769",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T13:33:49.137",
"Id": "18767",
"Score": "1",
"Tags": [
"clojure"
],
"Title": "Idiomatic letterpress cheater"
}
|
18767
|
<p>Please help me check the correctness of this c# iterative implementation of <a href="http://chessprogramming.wikispaces.com/Negamax" rel="nofollow">negamax</a>! Thank you! Your help highly appreciated! Also, please help me out how to add <a href="http://chessprogramming.wikispaces.com/Alpha-Beta" rel="nofollow">alpha beta pruning</a> to this(it was supposed to be alpha beta with negamax, but i forgot the alpha beta part... :<)! Thanks in advance!</p>
<p>EDIT: I DO think that the implementaqtion works. I only want it to be checked. Also, i simply want SUGGESTIONS and GUIDANCE on how to add alpha beta to the algorithm, not someone write the code for me. Please do not be mistaken. Thank you.</p>
<pre><code>Random r = new Random();
Stack<int> maxs = new Stack<int>();
Stack<int> levels = new Stack<int>();
Stack<string> todo = new Stack<string>();
Stack<string> undo = new Stack<string>();
maxs.Push(int.MinValue);
var le = legals(bd);
while (le.Any())
{
var mv = le[r.Next(le.Count)];
le.Remove(mv);
todo.Push(mv);
levels.Push(1);
}
while (todo.Any())
{
//init
string mv = todo.Pop();
int level = levels.Pop();
undo.Push(mv);
if (level != depthleft) maxs.Push(int.MinValue);
move(mv, level % 2 == 0 ? "b" : "w");
//expand children/do operations,cleanup
if (level == depthleft)
{
int score = -eval(bd, level % 2 == 0);
if (score > maxs.Last())
{
maxs.Pop();
maxs.Push(score);
}
unmove(undo.Pop());
int diff = level - levels.Last();
if (diff != 0)
{
for (; diff > 0; diff--)
{
score = -maxs.Pop();
if (score > maxs.Last())
{
maxs.Pop();
maxs.Push(score);
}
unmove(undo.Pop());
}
}
}
else
{
var ls = legals(bd);
while (ls.Any())
{
var child = ls[r.Next(ls.Count)];
ls.Remove(child);
todo.Push(child);
levels.Push(level + 1);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T15:29:25.613",
"Id": "29917",
"Score": "2",
"body": "I think your question does not fit well on this site. This site is for requests to improve code that you think works, not to check whether it works at all and certainly not to write code for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T00:56:28.200",
"Id": "29931",
"Score": "0",
"body": "yes, i think my code should work. i just want someone to check its correctness on behalf of puny me. also, i only wanted SUGGESTIONS on howto incooperate alpha beta into the algorithm, certainly not necessarily writing code for me either. maybe it was my unclear question. ill edit it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:54:59.620",
"Id": "29954",
"Score": "0",
"body": "@idiotretard (such an odd name): your question seems to fit on StackOverflow. HTH"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T10:28:38.833",
"Id": "29963",
"Score": "1",
"body": "... i initially posted this on stack overflow, got told to move it here, and got closed there... wth should i do then!?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T10:32:00.663",
"Id": "29964",
"Score": "0",
"body": "\"What kind of questions can I ask here?\n\nCode Review - Stack Exchange is for sharing code from projects you are working on for peer review. If you are looking for feedback on a specific working piece of code from your project in the following areas…\n\nBest practices and design pattern usage\nSecurity issues\nPerformance\nCorrectness in unanticipated cases\nthen you are in the right place!\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T10:32:34.513",
"Id": "29965",
"Score": "0",
"body": "\"I'm confused! What questions are on-topic for this site?\nSimply ask yourself the following questions. To be on-topic the answer must be yes to all questions:\n\nDoes my question contain code? (Please include the code in the question, not a link to it)\nDid I write that code?\nIs it actual code from a project rather than pseudo-code or example code?\nTo the best of my knowledge, does the code work?\nDo I want feedback about any or all facets of the code?\nIf you answered yes to all the above questions, your question is on-topic for Code Review.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T10:33:00.830",
"Id": "29966",
"Score": "0",
"body": "i can tell you i DO believe that my question was on topic AND i would definitely answer yes to all the five questions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:00:02.083",
"Id": "30049",
"Score": "0",
"body": "This question is on-topic, as the current community consensus sees it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:58:15.487",
"Id": "30055",
"Score": "0",
"body": "`... i initially posted this on stack overflow, got told to move it here, and got closed there... wth should i do then!?` Oh man, sorry that we trapped you in a vicious bureaucratic circle - it was definitely not intentional. :("
}
] |
[
{
"body": "<p>Some quick suggestions:</p>\n\n<ul>\n<li>Split the code into smaller methods, with understandable names - it will become simpler!</li>\n<li>Use clear variable names (even if they are longer) and try to avoid \"shortenings\";</li>\n<li><strong>Never</strong> use less than 3 characters for variable names... <code>le</code>? <code>r</code>? <code>mv</code>?!? (<code>int i</code> in for cycles is an exception because it is idiomatic);</li>\n<li>Use PascalCase (not camelCase) for methods and properties;</li>\n<li>Use camelCase (not lowercase) for local variables;</li>\n<li>Don't repeat code (<code>var le = legals(bd); while (le.Any()) { ... }</code>), extract it to a method.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T16:20:25.043",
"Id": "18847",
"ParentId": "18770",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18847",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T15:05:52.767",
"Id": "18770",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Iterative Implementation of Negamax Alpha-Beta"
}
|
18770
|
<p>I have a list of images that are used as links and at the bottom of each image there is another image to show/hide. So far all the images show at the same time because they have the same class.</p>
<p>Is there any way to get around that? I don't know how to give them all the unique ID.</p>
<pre><code> <div id="nav">
<ul>
<li id="one" ><a href="#"><img src="mikesfamilyborder.png" class="first" /><p><img src="mikesfamilybordername.png" class="name"/></p></a></li>
<li id="two"><a href="#" ><img src="bradsfamilyborder.png" class="first" /><p><img src="bradsfamilyname.png" class="name"/></a></p></li>
<li id="three"><a href="#" ><img src="brennerfamilyborder.png" class="first" /><p><img src="ryanbfamilyname.png" class="name"/></a></p></li>
<li id="four"><a href="#" ><img src="ryanfamilyborder.png" class="first" /><p><img src="ryanlfamilyname.png" class="name"/></a></p></li>
<li id="five"><a href="#" ><img src="missydadfamilyborder.png" class="first" /><p><img src="lackeysname.png" class="name"/></a></p></li>
<li id="six"><a href="#" ><img src="libbyfamilyborder.png" class="first" /><p><img src="libbysname.png" class="name"/></a></p></li>
</ul>
<p> Click Picture for Family page</p>
</div>
</code></pre>
<p>JavaScript:</p>
<pre><code>$('.name').hide();
$(".first").hover(function() {
$(".name").stop().show();
}, function() {
$(".name").stop().hide();
});
</code></pre>
|
[] |
[
{
"body": "<p>You need to find the <code>.name</code> item that is in the same block of HTML as the one being hovered. One way to do that is to go up the parent chain from the one begin hovered to get the <code>li</code> tag and then use <code>.find()</code> from thereto find that <code>.name</code> item in that block. You can use this code to do that:</p>\n\n<pre><code>$('.name').hide();\n\n$(\".first\").hover(function() {\n $(this).closest(\"li\").find(\".name\").stop(true).show();\n}, function() {\n $(this).closest(\"li\").find(\".name\").stop(true).hide();\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T16:21:14.600",
"Id": "29919",
"Score": "0",
"body": "I got it working but it took the .next() instead of .find(). thanks it atleast put me in the right direction!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T16:36:32.017",
"Id": "29920",
"Score": "0",
"body": "@RyanLackey - I changed my code to a more robust way than `.next()` (it won't break if the HTML is modified slightly)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T15:54:46.967",
"Id": "18772",
"ParentId": "18771",
"Score": "2"
}
},
{
"body": "<h2>Miskate</h2>\n\n<p>I'll point a miskate in the HTML.</p>\n\n<p>The second <code>li</code> and onwards, the <code>p</code> element should be closed first and then. But, in your markup <code>a</code> is first closed and then <code>p</code> which is semantically wrong.</p>\n\n<p>Here's the formatted HTML for second <code>li</code>.</p>\n\n<pre><code><li id=\"two\">\n <a href=\"#\">\n <img src=\"bradsfamilyborder.png\" class=\"first\" />\n <p>\n <img src=\"bradsfamilyname.png\" class=\"name\"/>\n </a>\n</p> <!--- Did I closed this right? --->\n</li>\n</code></pre>\n\n<p>It should be</p>\n\n<pre><code><li id=\"two\">\n <a href=\"#\"><img src=\"bradsfamilyborder.png\" class=\"first\" />\n <p><img src=\"bradsfamilyname.png\" class=\"name\" /></a>\n </p>\n</li>\n</code></pre>\n\n<hr>\n\n<h2>Review</h2>\n\n<p>The IDs an class names are very generic. Chances are that they will clash with other page/developers styles and will not work as expected. When working with jQuery and CSS, it's very important to name the <em>things</em> properly. You can namespace them with some prefix - <code>nav-</code> in this case.</p>\n\n<p>The class names <code>name</code> and <code>first</code> doesn't tell anything about what it contains or direct wrong message. <code>family-name</code> and <code>family-border-name</code> is much better.</p>\n\n<p><code>$('.name').hide()</code> will hide the elements on page load causing flicker. I'll suggest...(see <strong>Improvements</strong> section below)</p>\n\n<p><code>stop()</code> is used to stop ongoing animation. As no animation is used(or the code is not shown?), it can be removed.</p>\n\n<hr>\n\n<h2>Improvement</h2>\n\n<p>Here is the <a href=\"https://jsfiddle.net/tusharj/5966kpn6/\" rel=\"nofollow noreferrer\">Demo</a> of jfriend00's answer. Although, this is correct, this can be done without jQuery at all.</p>\n\n<p><strong>Note:</strong> Here, I'll use old markup provided in the question.</p>\n\n<p><code>$('.name').hide();</code> can be written in CSS as</p>\n\n<pre><code>.name {\n display: none;\n}\n</code></pre>\n\n<p>This has better effect as compared to jQuery counterpart as it will not show flicker when CSS is included in <code><head></code>.</p>\n\n<p>And the <code>hover()</code> can be written as below using <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/:hover\" rel=\"nofollow noreferrer\"><code>:hover</code></a> pseudo-class and <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/Adjacent_sibling_selectors\" rel=\"nofollow noreferrer\">Adjacent Sibling Selector</a></p>\n\n<pre><code>.first:hover + p > .name {\n display: block;\n}\n</code></pre>\n\n<p>which basically says, when hover on <code>.first</code>, select next sibling <code>p</code> and it's direct children <code>></code>, having <code>name</code> class.</p>\n\n<p><strong>Demo:</strong><sup>Although, you cannot see images, you can see it works as expected when hover over an image.</sup></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#nav .family-border-name {\n display: none;\n}\n#nav .family-name:hover + p > .family-border-name {\n display: block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"nav\">\n <ul>\n <li>\n <a href=\"#\"><img src=\"mikesfamilyborder.png\" class=\"family-name\" />\n <p><img src=\"mikesfamilybordername.png\" class=\"family-border-name\" /></p>\n </a>\n </li>\n <li>\n <a href=\"#\"><img src=\"bradsfamilyborder.png\" class=\"family-name\" />\n <p><img src=\"bradsfamilyname.png\" class=\"family-border-name\" /></p>\n </a>\n </li>\n <li>\n <a href=\"#\"><img src=\"brennerfamilyborder.png\" class=\"family-name\" />\n <p><img src=\"ryanbfamilyname.png\" class=\"family-border-name\" /></p>\n </a>\n </li>\n <li>\n <a href=\"#\"><img src=\"ryanfamilyborder.png\" class=\"family-name\" />\n <p><img src=\"ryanlfamilyname.png\" class=\"family-border-name\" />\n </p>\n </a>\n\n </li>\n <li>\n <a href=\"#\"><img src=\"missydadfamilyborder.png\" class=\"family-name\" />\n <p><img src=\"lackeysname.png\" class=\"family-border-name\" />\n </p>\n </a>\n </li>\n <li>\n <a href=\"#\"><img src=\"libbyfamilyborder.png\" class=\"family-name\" />\n <p><img src=\"libbysname.png\" class=\"family-border-name\" />\n </p>\n </a>\n </li>\n </ul>\n <p> Click Picture for Family page</p>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-01T06:14:29.550",
"Id": "285211",
"Score": "0",
"body": "Note that there is one intentional miskate in the answer, don't edit it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-01T06:14:01.463",
"Id": "151378",
"ParentId": "18771",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18772",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T15:23:13.240",
"Id": "18771",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Show/hide image in each list individually with same class"
}
|
18771
|
<p>In my C# program, I have a class defined as follows:</p>
<pre><code>public class DbResult
{
public bool bSuccess { get; private set; }
public String Message { get; private set; }
private DbResult(bool success, string message)
{
this.bSuccess = success;
this.Message = message;
}
public static DbResult Failed(string message)
{
return new DbResult(false, message);
}
public static DbResult Success(string message)
{
return new DbResult(true, message);
}
}
</code></pre>
<p>This is used in my DataAccess class, which has several methods whose return type is DbResult. They use LINQ and the Entity Framework. <strong>UPDATE</strong> Here is the entire DataAccess as of right now:</p>
<pre><code>public class DataAccess
{
private readonly TestDatabaseEntities _MyDBEntities;
public DataAccess(TestDatabaseEntities entities)
{
_MyDBEntities = entities;
}
public DbResult DatabaseExists()
{
DbResult MyResult;
if (_MyDBEntities.Database.Exists())
MyResult = DbResult.Success("Database Found");
else
MyResult = DbResult.Failed("Database Not Found");
return MyResult;
}
// ============================
// CRUD FUNCTIONS for MAN TABLE
// ============================
public DbResult Create(Man M)
{
DbResult DbRes;
try
{
_MyDBEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name });
DbRes = DbResult.Success("Record created");
}
catch (Exception e)
{
DbRes = DbResult.Failed(e.ToString());
}
return DbRes;
}
public DbResult Update(IQueryable<Man> myQuery, Man man)
{
DbResult DbRes;
try
{
foreach (Man M in myQuery)
{
M.Name = man.Name;
}
DbRes = DbResult.Success("Record updated");
}
catch (Exception e)
{
DbRes = DbResult.Failed(e.ToString());
}
return DbRes;
}
public DbResult Delete(IQueryable myQuery)
{
DbResult DbRes;
try
{
foreach (Man M in myQuery)
{
_MyDBEntities.Men.Remove(M);
}
DbRes = DbResult.Success("Record deleted");
}
catch (Exception e)
{
DbRes = DbResult.Failed(e.ToString());
}
return DbRes;
}
public DbResult Read(IQueryable myQuery, out string[,] Records)
{
DbResult DbRes;
Records = null;
try
{
List<Man> men = myQuery.OfType<Man>().ToList();
Records = new string[men.Count, 2];
for (int i = 0; i < men.Count; i++)
{
Records[i, 0] = men[i].ManID.ToString();
Records[i, 1] = men[i].Name;
}
DbRes = DbResult.Success("Read Success");
}
catch (Exception e)
{
DbRes = DbResult.Failed(e.ToString());
}
return DbRes;
}
// ============================
// SAVECHANGES FUNCTION
// ============================
public DbResult SaveChanges()
{
DbResult DbRes;
try
{
_MyDBEntities.SaveChanges();
DbRes = DbResult.Success("Saved successfully");
}
catch (Exception e)
{
DbRes = DbResult.Failed(e.ToString());
}
return DbRes;
}
}
</code></pre>
<p>I also have a class called ServiceManager, which checks to see if the SQL Server (SQLEXPRESS) service is running on the local machine.</p>
<pre><code>public class ServiceManager
{
public DbResult SQLRunning()
{
DbResult MyResult;
ServiceController sc = new ServiceController("SQL Server (SQLEXPRESS)");
if (sc.Status == ServiceControllerStatus.Running)
MyResult = DbResult.Success("SQL Server is running");
else
MyResult = DbResult.Failed("SQL Server is NOT running.");
return MyResult;
}
}
</code></pre>
<p>As you may have noticed in the code directly above, I use the DbResult class as a return type to carry the status message and bool back to the main program. I think this does not make sense since DbResult is a class created for returning results from trying to perform operations on the Database, not the SQL Server checkup. I could create a new class called ServiceResult, which does the exact same thing as DbResult, but that would be duplicating code. see example below:</p>
<pre><code>public class ServiceResult
{
public bool bRunning { get; private set; }
public String Message { get; private set; }
private ServiceResult(bool bRunning, string message)
{
this.bRunning = success;
this.Message = message;
}
public static ServiceResult Running(string message)
{
return new ServiceResult(false, message);
}
public static ServiceResult Stopped(string message)
{
return new ServiceResult(true, message);
}
}
</code></pre>
<p>You see how the above class is very similar to the DbResult class and works relatively the same way? This is how I might make a class for Services, but is there any way I can make a class that does both DbResults and ServiceResults without becoming more ambiguous like the following class example below? or, is it ok to be ambiguous like the result I put below?</p>
<pre><code>public class Result
{
public bool bYesNo { get; private set; }
public String Message { get; private set; }
private Result(bool YesNo, string message)
{
this.bYesNo = YesNo;
this.Message = message;
}
public static Result No(string message)
{
return new Result(false, message);
}
public static Result Yes(string message)
{
return new Result(true, message);
}
}
</code></pre>
<h2>UPDATED</h2>
<p>The methods that use my <code>DataAccess</code> class looks like this</p>
<pre><code> static private void DoCreate()
{
int myID;
bool bIsValidID;
var dbEntities = new TestDatabaseEntities();
string sNewName;
DataAccess MyDA = new DataAccess(dbEntities);
DbResult CreationResult, SaveResult;
do
{
bIsValidID = _MyUI.GetValidInput<int>("Enter ID: ", int.TryParse, out myID);
}
while (!bIsValidID);
sNewName = _MyUI.GetInput<string>("Enter Name:", x => x.Trim());
CreationResult = MyDA.Create(new Man() {ManID = myID, Name = sNewName });
_MyUI.DisplayMessage(CreationResult.Message);
if (!CreationResult.bSuccess)
return;
SaveResult = MyDA.SaveChanges();
_MyUI.DisplayMessage(SaveResult.Message);
}
static private void DoRead()
{
var dbEntities = new TestDatabaseEntities();
DataAccess MyDA = new DataAccess(dbEntities);
string [,] Records;
DbResult ReadResult;
var query = from person in dbEntities.Men
where true
select person;
ReadResult = MyDA.Read(query, out Records);
if (ReadResult.bSuccess)
{
_MyUI.DisplayRecords(Records);
}
if (!ReadResult.bSuccess)
_MyUI.DisplayMessage(ReadResult.Message);
}
static private void DoUpdate()
{
int myID;
var dbEntities = new TestDatabaseEntities();
string sNewName = "";
DataAccess MyDA = new DataAccess(dbEntities);
DbResult UpdateResult, SaveResult;
myID = _MyUI.GetInput<int>("Enter ID to update: ", int.Parse);
sNewName = _MyUI.GetInput<string>("Enter new name: ", x => x.Trim());
var query =
from person in dbEntities.Men
where person.ManID == myID
select person;
UpdateResult = MyDA.Update(query, new Man() { ManID = myID, Name = sNewName });
_MyUI.DisplayMessage(UpdateResult.Message);
if (!UpdateResult.bSuccess)
return;
SaveResult = MyDA.SaveChanges();
_MyUI.DisplayMessage(SaveResult.Message);
}
static private void DoDelete()
{
int myID;
bool bValidInput;
var dbEntities = new TestDatabaseEntities();
DataAccess MyDA = new DataAccess(dbEntities);
DbResult DeleteResult, SaveResult;
do
{
bValidInput = _MyUI.GetValidInput<int>("Enter ID to delete: ", int.TryParse, out myID);
} while (!bValidInput);
var Query =
from person in dbEntities.Men
where person.ManID == myID
select person;
DeleteResult = MyDA.Delete(Query);
_MyUI.DisplayMessage(DeleteResult.Message);
if (!DeleteResult.bSuccess)
return;
SaveResult = MyDA.SaveChanges();
_MyUI.DisplayMessage(SaveResult.Message);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T17:35:23.897",
"Id": "29980",
"Score": "3",
"body": "Just a comment on your code, using Hungarian Notation is not a standard naming convenction, especially on public properties. http://stackoverflow.com/questions/309205/are-variable-prefixes-hungarian-notation-really-necessary-anymore"
}
] |
[
{
"body": "<p>Can I try to convince you that you don't actually need such a <code>Result</code> class at first place?</p>\n\n<p>How do you actually use the string <code>Message</code> value of this class? Do you show it to user? If yes, then what would you do when you need to make it multilingual? What I'm trying to say is that verbal interpretation of \"success\" or \"failure\" should actually be done on UI level, and <code>Result</code> class is not a UI. Also there is usually a single \"success\" case. You may say that you might want to differentiate several failure cases, but those are best described by a nice technology called exceptions.</p>\n\n<p>So, what do we have beside <code>Message</code>? A boolean flag. That's what we probably want to return in case if we're interested whether something was successful or not... but wait. What usually happens when something goes wrong? Exception. And it would probably be more useful to let the business code process this exception, as the same exception may be treated differently in different situations.</p>\n\n<p>Now let's go back to your code. You <code>ServiceManager</code> class doesn't have a state, so let's make it static:</p>\n\n<pre><code>public static class ServiceManager\n{\n public static bool IsSqlServerRunning()\n {\n //TODO: What if service is not installed?\n ServiceController sc = new ServiceController(\"SQL Server (SQLEXPRESS)\");\n return (sc.Status == ServiceControllerStatus.Running);\n }\n}\n</code></pre>\n\n<p>Now it's much cleaner, and the caller of this method can decide what to output in case when SQL Server is not running...</p>\n\n<p>About DB wrappers - I would suggest to avoid them at all. They represent abstractions over abstraction (Entity framework). By wrapping adds/deletes/selects in separate methods you loose lots of benefits provided by ORM frameworks like transactional nature of the DB interaction, without getting pretty much any benefit. It's actually much easier and cleaner to explicitly define context boundaries (in case of Web processing boundaries are already defined) and directly use the ORM to manipulate with the data.</p>\n\n<p><strong>Update based on updated question</strong>. There are several issues in the code that uses <code>DataAccess</code> class:</p>\n\n<ul>\n<li>All methods are static. It's not an issue for a small codebase and console app like yours, but don't overuse them.</li>\n<li><p>The following code is actually exactly the same as just <code>dbEntities.Men</code></p>\n\n<pre><code>from person in dbEntities.Men\nwhere true\nselect person\n</code></pre></li>\n<li>naming conventions (local variables should start with lower case</li>\n<li>don't convert Man objects into 2-dimensional array... </li>\n</ul>\n\n<p>I'll show you how to simplify the code based on DoUpdate method, it includes most of the tasks done in other methods. No DataAccess class usage, cleaner code, better exception management.</p>\n\n<pre><code>static private void DoUpdate()\n{\n int myID = _MyUI.GetInput<int>(\"Enter ID to update: \", int.Parse);\n string sNewName = _MyUI.GetInput<string>(\"Enter new name: \", x => x.Trim());\n\n try\n { \n using (var dbEntities = new TestDatabaseEntities())\n {\n //TODO: If ManID is unique then we can use FirstOrDefault here.\n var allMatchingMen =\n from person in dbEntities.Men\n where person.ManID == myID\n select person;\n\n foreach(var man in allMatchingMen)\n man.Name = sNewName;\n\n dbEntities.SaveChanges();\n _MyUI.DisplayMessage(\"Record(s) updated\");\n }\n }\n catch (OptimisticConcurrencyException ex)\n {\n //TODO: add auto-retry logic\n _MyUI.DisplayMessage(\"Someone updated the record, let's retry\");\n }\n catch (Exception ex)\n {\n _MyUI.DisplayMessage(\"Something went wrong, could not update\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T17:29:42.623",
"Id": "29979",
"Score": "0",
"body": "I disagree on the avoiding DB wrappers. What happens when it is decided that the data storage should be changed from SQL to, say Mongo, or Solr. You have tightly bound your application to SQL. By having a properly designed data access layer using interfaces, you just have to create the class that performs the needed actions on the data store and plug it into the application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:09:58.233",
"Id": "29985",
"Score": "0",
"body": "The business code would still \"know\" about the underlying ORM, at least in order to optimize the DB usage, otherwise you'll quickly get a system that doesn't use the benefits of the specific DB platform. Also, switching from SQL to Mongo won't be that easy anyway, e.g. because of lack of ACID. There is a good article why you shouldn't wrap ORM into repository from one of the core contributors of NHibernate: http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:55:47.843",
"Id": "29989",
"Score": "0",
"body": "I understand why I shouldn't use the wrapper class now, however, I don't understand how what I was doing with the wrapper classes is considered \"wrapping ORM\" into a class. I just see a boolean, and a message, with some methods to regulate how they are assigned values. On a note of lesser importance, the exception gets passed to the DbResult.Failure method from the data Access layer, where the exception occurs. and then the message gets displayed in the UI class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T20:50:54.157",
"Id": "29994",
"Score": "0",
"body": "By \"wrapping ORM\" I meant your `DataAccess` class that hides the work with ORM classes. \n\nConcerning \"exception gets passed to the DbResult.Failure method\" - that's exactly what I wouldn't suggest to do... By passing a string (probably `exception.ToString()`) instead of rich exception object you loose a lot of information. For certain exceptions later you may want to implement automatic retries, for others you may want to show a customised notification rather than stack trace ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T04:03:41.293",
"Id": "30022",
"Score": "0",
"body": "@almaz I've updated my question to include the methods in my main class(which runs the menu to display to user) which use my DataAccess Class. After what you've told me, I sense there must be something wrong with creating `dbEntities` in those methods and passing it to the dataAccess class. Would i be correct in guessing that a lot of that code should be transferred to the DataAccess Class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T13:38:45.027",
"Id": "30040",
"Score": "0",
"body": "Updated my response"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T16:15:34.053",
"Id": "30059",
"Score": "0",
"body": "The only problem i forsee with using the code that you posted in your update is if I wanted to add update functionality for more dbEntities classes. Such as one that I have called `Location`, which has 2 fields, \"ID\", and \"Place Name\". It seems like code reuse would be more difficult to implement. I would end up copying the entire update function and changing only the part where it takes in the new ID and name from user, the place where the query is defined, and the foreach loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T10:50:03.953",
"Id": "30097",
"Score": "0",
"body": "Well, your current code looks like a console app, because a single method talks to user, requires input and performs the action. In real world of desktop/web apps these stages are separated into different methods and/or classes. In that cases it's better to separate common functionality, e.g. in web you would have a common context handling per request, and most likely exception handling for common scenarios as well. In your code you can extract a base class and share the functionality between Man and Location."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T14:25:12.503",
"Id": "18793",
"ParentId": "18775",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18793",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T16:26:12.507",
"Id": "18775",
"Score": "0",
"Tags": [
"c#",
"optimization",
"classes",
"entity-framework"
],
"Title": "Making a Custom class less specialized but just as understandable?"
}
|
18775
|
<blockquote>
<p>Given an array of words, print all anagrams together. For example, if
the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output
may be “cat tac act dog god”.</p>
</blockquote>
<p>The following is my c++ code. I use raw pointer to implement varying number of children
for practice. Actually, I guess maybe it's better to adopt STL containers. </p>
<pre><code>#include <iostream>
#include <cstring>
using namespace std;
struct Index_node_base
{
Index_node_base* next;
Index_node_base():next(NULL){}
};
struct Index_node : public Index_node_base
{
int index;
Index_node(int i):index(i), Index_node_base(){}
};
void insert_index_node(Index_node** head, int i)
{
Index_node* node = new Index_node(i);
node->next = (*head);
*head = node;
}
struct Trie_node_base
{
typedef Trie_node_base* Base_ptr;
Base_ptr* child;
int num_of_child;
Trie_node_base(int n)
{
child = new Base_ptr[n];
for(int i=0; i < n; ++i)
child[i] = NULL;
num_of_child = n;
}
~Trie_node_base()
{
delete [] child;
}
};
struct Trie_node : public Trie_node_base
{
bool is_end;
Index_node* head;
Trie_node(int n):Trie_node_base(n), is_end(false), head(NULL){}
};
class Trie
{
public:
Trie(int n=26)
{
root = new Trie_node(n);
}
~Trie()
{
destroy(root);
}
void insert_trie_node(const char* w, int ind);
Trie_node* get_root_node();
private:
Trie_node* root;
void destroy(Trie_node* root);
};
Trie_node* Trie::get_root_node()
{
return root;
}
void Trie::insert_trie_node(const char* w, int ind)
{
Trie_node* r = root;
while(*w)
{
int i = *w - 'a';
if(r->child[i] == NULL)
{
r->child[i] = new Trie_node(r->num_of_child);
}
r = (Trie_node*)r->child[i];
++w;
}
if(r->is_end)
{
insert_index_node(&(r->head), ind);
}
else
{
r->is_end = true;
r->head = new Index_node(ind);
}
}
void traversal_trie(const char* word_arr[], Trie_node* r)
{
size_t i;
if(r->is_end)
{
Index_node* h = r->head;
while(h != NULL)
{
printf("%s\n", word_arr[h->index]);
h = (Index_node*)h->next;
}
}
for(i = 0; i < r->num_of_child; ++i)
{
if(r->child[i] != NULL)
traversal_trie(word_arr, (Trie_node*)r->child[i]);
}
}
void Trie::destroy(Trie_node* root)
{
size_t i;
for(i = 0; i < root->num_of_child; ++i)
{
if(root->child[i] != NULL)
destroy((Trie_node*)root->child[i]);
}
if(root->is_end)
{
Index_node* h = root->head;
Index_node* tmp = NULL;
while(h != NULL)
{
tmp = (Index_node*)h->next;
delete h;
h = tmp;
}
}
delete root;
}
static int comp_char(const void* x, const void* y)
{
const char* c1 = (const char*)x;
const char* c2 = (const char*)y;
return *(c1) - *(c2);
}
static void cluster_anagrams(const char* word_arr[], size_t size)
{
Trie* trie = new Trie(26);
size_t i;
char* buffer;
for(i = 0; i < size; ++i)
{
int len = strlen(word_arr[i]);
buffer = new char [len+1];
memcpy(buffer, word_arr[i], len+1);
qsort(buffer, strlen(buffer), 1, comp_char);
trie->insert_trie_node(buffer, i);
delete buffer;
}
cout << "Debug!" << endl;
traversal_trie(word_arr, trie->get_root_node());
}
int main()
{
const char* word_arr[] = {"cat", "dog", "tac", "god", "act", "gdo"};
size_t size = sizeof(word_arr) / sizeof(word_arr[0]);
cluster_anagrams(word_arr, size);
system("pause");
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>#include <cstring>\n</code></pre>\n\n<p>Avoid including C headers when programming C++.</p>\n\n<pre><code>struct Index_node_base\n{\n Index_node_base* next;\n Index_node_base():next(NULL){} \n};\n\nstruct Index_node : public Index_node_base\n{\n int index;\n Index_node(int i):index(i), Index_node_base(){}\n};\n\nvoid insert_index_node(Index_node** head, int i)\n{\n Index_node* node = new Index_node(i);\n node->next = (*head);\n *head = node;\n}\n</code></pre>\n\n<p>This is overkill as you are just re-implementing a list of numbers / characters.</p>\n\n<pre><code>const char*\n</code></pre>\n\n<p>This is C code, consider using the C++ <code>std::string</code> instead.</p>\n\n<pre><code>const char* word_arr[]\n</code></pre>\n\n<p>For example, this one should be a <code>std::list<std::string></code> (a.k.a. <code>list<string></code>)</p>\n\n<pre><code> printf(\"%s\\n\", word_arr[h->index]);\n</code></pre>\n\n<p>Again C, use the C++ iostreams instead. This should be like <code>cout << ... << endl;</code></p>\n\n<pre><code>while(*w)\n{\n int i = *w - 'a';\n if(r->child[i] == NULL)\n {\n r->child[i] = new Trie_node(r->num_of_child);\n }\n r = (Trie_node*)r->child[i];\n ++w;\n}\n</code></pre>\n\n<p>You can use iterators and STL algorithms to do this in one line.</p>\n\n<pre><code>for(i = 0; i < r->num_of_child; ++i)\n{\n if(r->child[i] != NULL)\n traversal_trie(word_arr, (Trie_node*)r->child[i]);\n}\n</code></pre>\n\n<p>This would also be one line using <code>for_each</code> on iterators and passing <code>traversal_trie</code>.</p>\n\n<pre><code>void Trie::destroy(Trie_node* root)\n</code></pre>\n\n<p>You won't need destory anymore as a result; also, there's a chance you might not need pointers.</p>\n\n<pre><code>static int comp_char(const void* x, const void* y)\n{\n const char* c1 = (const char*)x;\n const char* c2 = (const char*)y;\n\n return *(c1) - *(c2);\n}\n</code></pre>\n\n<p>This is messsy, you are doing useless C style voids and casts and not using C++ overloading. This body would have been something along the line of just the line <code>return c1 < c2;</code></p>\n\n<pre><code>for(i = 0; i < size; ++i)\n{\n int len = strlen(word_arr[i]);\n buffer = new char [len+1];\n memcpy(buffer, word_arr[i], len+1); \n qsort(buffer, strlen(buffer), 1, comp_char); \n trie->insert_trie_node(buffer, i); \n delete buffer;\n}\n</code></pre>\n\n<p><code>memcpy</code>? Not necessary, <code>std::string</code> allows you to copy the string and not mess with memory.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T17:31:31.227",
"Id": "18778",
"ParentId": "18776",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18778",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T16:39:58.533",
"Id": "18776",
"Score": "1",
"Tags": [
"c++",
"trie"
],
"Title": "use trie data structure to solve the problem of clustering anagrams"
}
|
18776
|
<p>This is my code that works:</p>
<pre><code>foreach (var r in rlist)
{
if (r.IndexOf("_") != -1)
{
int id = int.Parse(r.Split('_')[1]);
var x_tmp = (from x in db.tblX where x.x_id == my_id && x.x_id == id select x).First();
x_tmp.order = someNumber;
}
}
db.SaveChanges();
</code></pre>
<p>Is there a way to refactor this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:59:20.937",
"Id": "29955",
"Score": "0",
"body": "Is it supposed to set the same order for all the items? Shouldn't you be incrementing the order?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T09:03:16.433",
"Id": "29956",
"Score": "1",
"body": "-1: also, why are you comparing `x.x_id` to both `my_id` and `id`? **Does this code compile? Does it work as intended?** Did you try to improve it by yourself before putting it on our collective table?"
}
] |
[
{
"body": "<p>Seems you are calling the query a few times with <code>id</code>, so let's just call it only once with all of them.</p>\n\n<pre><code>(from x in db.tblX where x.x_id == my_id && ids.Contains(x.x_id) select x)\n</code></pre>\n\n<p>There you go, now <code>IEnumerable</code>'s <code>Contains</code> function allows you to look up the id in a list of <code>ids</code> you have made in advance. I usually prefer to use LINQ methods, as simple LINQ expressions tend to be more complex than they should be:</p>\n\n<pre><code>db.tblX.Where(x => x.x_id == my_id && ids.Contains(x.x_id))\n</code></pre>\n\n<p>We can now use a plain <code>foreach</code> as suggested in comments, such that we don't have side effects:</p>\n\n<pre><code>var ids = rlist.Where(x => x.IndexOf(\"_\") != -1).Select(x => int.Parse(x.Split('_')[1]));\n\nvar items = db.tblX.Where(x => x.x_id == my_id && ids.Contains(x.x_id));\n\nforeach (var item in items)\n item.order = someNumber;\n\ndb.SaveChanges();\n</code></pre>\n\n<p>Done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T18:33:22.767",
"Id": "29921",
"Score": "2",
"body": "Why are you suggesting `ForEach()`? I think `foreach` is more idiomatic and readable. [And `ForEach()` also clashes with the idea of side-effects-free lambdas, that's behind LINQ.](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx) Also, your first `ForEach()` doesn't work, you want to use `Select()` there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T18:53:15.473",
"Id": "29924",
"Score": "0",
"body": "Adapted answer to your feedback, thanks! Seems I need to think some more about avoiding side effects..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T17:48:40.803",
"Id": "18779",
"ParentId": "18777",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18779",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T17:10:57.980",
"Id": "18777",
"Score": "-3",
"Tags": [
"c#",
"linq"
],
"Title": "How to refactor sql query in a foreach"
}
|
18777
|
<p>I've created a logging system with one-use passwords (sent via SMS API). What I would like to know is if it's "safe". I know it is hard to estimate safety but I am curious if it is safer than regular password. I would appreciate any advice to improve following code.</p>
<p>Scheme is:</p>
<p>Logging:</p>
<p>Loggin at a webpage -> Ask external server for password -> Store the password in session var and when form is sent compare it with the sent one</p>
<p>External script:</p>
<p>When asked with proper apikey -> give random password and send it via SMS API</p>
<p>The code is below:</p>
<p>External script:</p>
<pre><code> <?php
$apiKey='foobar123';
if ($_GET['api']!=$apiKey) {
header('HTTP/1.0 404 Not Found');
die();
}
$ile=12; //char number
$onepass='';
for($i=0;$i<$ile;$i++)
{
$k=rand(1,10);
$onepass.=$letter[$k];
}
if (!isset($_POST['ip'],$_POST['ip'])) {echo 'error'; die();}
$ip=$_POST['ip'];
$www=$_POST['www'];
echo $onepass;
include('sender.php'); //sending API
?>
</code></pre>
<p>Logging script (at page foo.com)</p>
<pre><code> <?php
session_start();
$sessi='1231dsahsda8';
$www="foo.com";
$ip=$_SERVER['REMOTE_ADDR'];
if(isset($_GET['destroyer'])){
if($_GET['destroyer']=='yes'){
session_destroy(); echo 'Logged out - <a href="?relog">Log in again</a>'; die();
}
if($_GET['destroyer']=='no'){
session_destroy(); echo 'New pass has been sent!'; session_start();
}
}
if (isset($_POST['password'])){
if($_POST['password']==$_SESSION['pass']) $_SESSION[$sessi]="log";
else echo'Wrong Password <a href="?destroyer=no">Send again</a>';
}
if ($_SESSION[$sessi]!="log") {
if(!isset($_SESSION['pass'])){
$adres='http://www.foobar.com/index.php?api=foobar123';
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $adres);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, "ip=$ip&www=$www");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); /
$dane=curl_exec($c);
curl_close($c);
$_SESSION['pass']=$dane;
echo 'Password has been sent';
}
echo'<p>Log in</p><form action="?a" method="post"><input type="password" name="password" value=""/><input type="submit" value="Login" /></form>';
}
else{//authorised
echo 'Logged <p><a href="?destroyer=yes">Logout</a></p';
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T21:33:58.593",
"Id": "29928",
"Score": "0",
"body": "Why have you decided to split this up into two scripts? It seems that everything taking place in the \"api\" script could replace the curl stuff in the log in script (not \"logging\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T18:00:33.380",
"Id": "30065",
"Score": "0",
"body": "in the future i would like to store in one place phone number for each user and have one account for few sites - that's why I would like to store it in another place"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T12:09:01.603",
"Id": "64552",
"Score": "1",
"body": "Somethnig just doesnt seem right to me about storing a password in a session..."
}
] |
[
{
"body": "<ol>\n<li><p>This probably makes integration and debugging harder:</p>\n\n<blockquote>\n<pre><code>if ($_GET['api']!=$apiKey) {\n header('HTTP/1.0 404 Not Found');\n die();\n}\n</code></pre>\n</blockquote>\n\n<p>The error message is misleading, if someone use an older or wrong API key they probably will spend some time searching the error in a wrong place since it indicates that the URL is wrong, not the key. <a href=\"https://en.wikipedia.org/wiki/HTTP_403\"><em>403 Forbidden</em></a> would be more convenient here.</p></li>\n<li><p>This should be in a configuration file, it might change more often than the code itself:</p>\n\n<blockquote>\n<pre><code>$apiKey='foobar123';\n</code></pre>\n</blockquote></li>\n<li><p>This generates a random number:</p>\n\n<blockquote>\n<pre><code>$k=rand(1,10);\n</code></pre>\n</blockquote>\n\n<p>Documentation of <a href=\"http://hu1.php.net/mt_rand\"><code>mt_rand</code></a> says the following:</p>\n\n<blockquote>\n <p>mt_rand — Generate a better random value</p>\n</blockquote>\n\n<p>So I guess using <code>mt_rand</code> would we better. Furthermore, the linked page contains another interesting thing:</p>\n\n<blockquote>\n <p>[...]</p>\n \n <p><strong>Caution</strong></p>\n \n <p>This function does not generate cryptographically secure values, \n and should not be used for cryptographic purposes. If you need a \n cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.</p>\n</blockquote>\n\n<p>It really depends on the application and the sensitivity of your data which is more appropriate.</p></li>\n<li><p>This usually referred as <a href=\"https://en.wikipedia.org/wiki/One-time_password\">one-time password</a>:</p>\n\n<blockquote>\n <p>one-use passwords</p>\n</blockquote></li>\n<li><p>This check could be at the beginning of the script:</p>\n\n<blockquote>\n<pre><code>if (!isset($_POST['ip'],$_POST['ip'])) {echo 'error'; die();}\n</code></pre>\n</blockquote>\n\n<p>It's unnecessary to create an one-time password if the <code>ip</code> is empty.</p>\n\n<p>Additionally, I guess the following is the same:</p>\n\n<pre><code>if (!isset($_POST['ip'])) {echo 'error'; die();}\n</code></pre></li>\n<li><p>You could eliminate the comment here with better variable naming:</p>\n\n<blockquote>\n<pre><code>$ile=12; //char number\n</code></pre>\n</blockquote>\n\n<p>Just rename it to <code>$passwordLength</code>.</p>\n\n<p>See also: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Bad Comments</em>, p67: <em>Don’t Use a Comment When You Can Use a Function or a Variable</em></p></li>\n<li><p>Two typos:</p>\n\n<ul>\n<li><code>$adres</code> should be <code>$address</code></li>\n<li><code>$dane</code> to <code>$done</code></li>\n</ul></li>\n<li><p>I'd rename <code>$sessi</code> to a descriptive name. What does this variable store, what's its purpose? Put that into the name.</p></li>\n<li><p>I'd change <code>log</code> to something more descriptive here:</p>\n\n<blockquote>\n<pre><code>$_SESSION[$sessi]=\"log\";\n</code></pre>\n</blockquote>\n\n<p><code>logged_in</code> would be easier to understand since it describes a state not an action (like <code>log</code>).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T12:04:38.457",
"Id": "45204",
"ParentId": "18781",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T21:26:27.907",
"Id": "18781",
"Score": "3",
"Tags": [
"php",
"logging"
],
"Title": "Logging system safety"
}
|
18781
|
<p>I have some experience with PHP but I have never even try to do this wit pure PHP, but now a friend of mine asked me to help him with this task so I sat down and write some code. What I'm asking is for opinion if this is the right way to do this when you want to use only PHP and is there anything I can change to make the code better. Besides that I think the code is working at least with the few test I made with it.</p>
<p>Here it is:</p>
<pre><code><?php
session_start();
// define variables and initialize with empty values
$name = $address = $email = "";
$nameErr = $addrErr = $emailErr = "";
$_SESSION["name"] = $_SESSION["address"] = $_SESSION["email"] = "";
$_SESSION["first_page"] = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Missing";
}
else {
$_SESSION["name"] = $_POST["name"];
$name = $_POST["name"];
}
if (empty($_POST["address"])) {
$addrErr = "Missing";
}
else {
$_SESSION["address"] = $_POST["address"];
$address = $_POST["address"];
}
if (empty($_POST["email"])) {
$emailErr = "Missing";
}
else {
$_SESSION["email"] = $_POST["email"];
$email = $_POST["email"];
}
}
if ($_SESSION["name"] != "" && $_SESSION["address"] != "" && $_SESSION["email"] != "") {
$_SESSION["first_page"] = true;
header('Location: http://localhost/formProcessing2.php');
//echo $_SESSION["name"]. " " .$_SESSION["address"]. " " .$_SESSION["email"];
}
?>
<DCTYPE! html>
<head>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type="text" name="name" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span>
<br />
Address <input type="text" name="address" value="<?php echo htmlspecialchars($address);?>">
<span class="error"><?php echo $addrErr;?></span>
<br />
Email <input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span>
<br />
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Just two small notes:</p>\n\n<ol>\n<li><p>I think </p>\n\n<pre><code><DCTYPE! html>\n</code></pre>\n\n<p>should be</p>\n\n<pre><code><!DOCTYPE html>\n</code></pre></li>\n<li><p>From <em>Code Complete, 2nd Edition</em>, p761:</p>\n\n<blockquote>\n <p><strong>Use only one data declaration per line</strong></p>\n \n <p>[...] \n It’s easier to modify declarations because each declaration is self-contained.</p>\n \n <p>[...]</p>\n \n <p>It’s easier to find specific variables because you can scan a single\n column rather than reading each line. It’s easier to find and fix\n syntax errors because the line number the compiler gives you has \n only one declaration on it.</p>\n</blockquote></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T00:30:30.020",
"Id": "18784",
"ParentId": "18783",
"Score": "1"
}
},
{
"body": "<p>It's incredibly repetitive. Repetitive code is hard to maintain because you have to apply the same change in many places. It's also hard to see at a glance where the similarities and differences lie.</p>\n\n<p>Here is how it could be rewritten:</p>\n\n<pre><code><?php\n $params = array('name', 'address', 'email');\n\n session_start();\n $_SESSION['first_page'] = true;\n\n foreach ($params as $p) {\n $$p = $_SESSION[$p] = '';\n if ($_SERVER['REQUEST_METHOD'] == 'POST') {\n if (empty($_POST[$p])) {\n $errorVarName = \"${p}Error\";\n $$errorVarName = 'Missing';\n } else {\n $$p = $_SESSION[$p] = $_POST[$p];\n }\n }\n if ($_SESSION[$p] == '') {\n $_SESSION['first_page'] = false;\n }\n }\n if ($_SESSION['first_page'])) {\n # None of the expected params is an empty string\n header('Location: http://localhost/formProcessing2.php');\n }\n?>\n</code></pre>\n\n<p>To go one step further, I would suggest using <code>$val[$p]</code> and <code>$err[$p]</code> instead of <code>$$p</code> and <code>$$errorVarName</code>, respectively. That's because variably named variable names are icky, and smell vaguely of the stink associated with <a href=\"http://www.php.net/manual/en/ini.core.php#ini.register-globals\" rel=\"nofollow\"><code>register_globals</code></a>. An additional benefit of using an associative array is that you can pass all of the processed parameter values as a single argument to a function, which you can't do if they are individual variables. The template would need to be modified to say</p>\n\n<pre><code>Name <input type=\"text\" name=\"name\" value=\"<?php echo htmlspecialchars($val['name']);?>\">\n<span class=\"error\"><?php echo $err['name'];?></span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:11:18.217",
"Id": "29946",
"Score": "0",
"body": "Nice. And just for my information cause I haven't followed PHP for some time, is it possible now to use `session_start()` anywhere in the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T08:30:20.430",
"Id": "29949",
"Score": "0",
"body": "http://php.net/manual/en/intro.session.php seems to say that you can call session_start() anytime before you access $_SESSION, and that the call to session_start() can be omitted if session.auto_start is enabled."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T07:52:51.787",
"Id": "18788",
"ParentId": "18783",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18784",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-18T21:44:28.147",
"Id": "18783",
"Score": "1",
"Tags": [
"php",
"form"
],
"Title": "Checking form input data on submit with pure PHP"
}
|
18783
|
<p>I've used the Trie data structure to solve the following problem:</p>
<blockquote>
<p>Given an array of words, print all anagrams together. For example, if the given array is {"cat", "dog", "tac", "god", "act"}, then output may be "cat tac act dog god".</p>
</blockquote>
<p>The following is my C++ implementation which can accommodate varying number of children. </p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
struct Trie_node_base
{
vector<Trie_node_base*> child;
int num_of_child;
Trie_node_base(int n)
{
num_of_child = n;
for(int i = 0; i < n; ++i)
child.push_back(NULL);
}
};
struct Trie_node : public Trie_node_base
{
bool is_word;
vector<vector<string>::const_iterator> head;
Trie_node(int num):Trie_node_base(num), is_word(false){}
};
class Trie
{
public:
Trie(int n=26)
{
root = new Trie_node(n);
}
~Trie()
{
destroy(root);
}
void insert_trie_node(const string& w, vector<string>::const_iterator ind);
Trie_node* get_root_node()
{
return root;
}
private:
Trie_node* root;
void destroy(Trie_node* root);
};
void Trie::insert_trie_node(const string& w, vector<string>::const_iterator ind)
{
Trie_node* r = root;
string::const_iterator runner = w.begin();
for(; runner!=w.end(); ++runner)
{
char cur_char = *runner;
int i = cur_char - 'a';
if(r->child[i] == NULL)
{
r->child[i] = new Trie_node(r->num_of_child);
}
r = (Trie_node*)r->child[i];
}
if(!r->is_word)
r->is_word = true;
r->head.push_back(ind);
}
void Trie::destroy(Trie_node* root)
{
vector<Trie_node_base*>::iterator it = (root->child).begin();
for(; it != (root->child).end(); ++it)
{
if(*it != NULL)
destroy((Trie_node*)(*it));
}
delete root;
}
void traversal_trie(const vector<string>& word_arr, Trie_node* r)
{
size_t i;
if(r->is_word)
{
vector<vector<string>::const_iterator>::iterator it = (r->head).begin();
for(; it != (r->head).end(); ++it)
{
cout << *(*it) << endl;
}
}
for(i = 0; i < r->num_of_child; ++i)
{
if(r->child[i] != NULL)
traversal_trie(word_arr, (Trie_node*)r->child[i]);
}
}
void cluster_anagrams(const vector<string>& word_arr, size_t size)
{
Trie* trie = new Trie(26);
vector<string>::const_iterator it = word_arr.begin();
for(; it != word_arr.end(); ++it)
{
string cur_str = *it;
sort(cur_str.begin(), cur_str.end());
trie->insert_trie_node(cur_str, it);
}
traversal_trie(word_arr, trie->get_root_node());
}
int main()
{
const char* word_arr[] = {"cat", "dog", "tac", "god", "act", "gdo"};
size_t size = sizeof(word_arr) / sizeof(word_arr[0]);
vector<string> word_arr1(word_arr, word_arr+size);
cluster_anagrams(word_arr1, size);
system("pause");
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code does several things more complex than required. In no particular order:</p>\n\n<ul>\n<li>What purpose does <code>Trie_node_base</code> serve? You don’t need a base class here since you only inherit from it once.</li>\n<li>Worse, your base class doesn’t have a virtual destructor.</li>\n<li><p>To create an array of size <code>n</code>, you use a loop and <code>push_back</code>. Much easier would be to use the proper initialiser:</p>\n\n<pre><code>Trie_node_base(int n) :\n num_of_child(n) ,\n child(n)\n { }\n</code></pre></li>\n<li><p>In fact, you generally fail to use initialisers, and instead re-assign values inside the constructor.</p></li>\n<li>Consider <em>proper naming</em>. In the above code snippet, it should really be <code>number_of_children</code> and <code>children</code> (plural!).</li>\n<li>The <code>num_of_child</code> member is redundant – the same information is stored in the vector.</li>\n<li>The tree node <code>root</code> doesn’t need to, and shouldn’t be, a pointer.</li>\n<li>In general, your use of pointers and manual memory management makes the code vastly more complex and brittle (and requires the existence of the <code>destroy</code> method). If you need to use pointers, use smart pointers (<code>std::unique_ptr</code> in this case).</li>\n<li><p>Better yet, omit pointers entirely. They are utterly unnecessary here. Unfortunately though, you cannot use <code>std::vector</code> with an incomplete class (the standard screwed up here). But you <em>can</em> (and should!) use <code>boost::container::vector</code>. Thus your tree node implementation becomes:</p>\n\n<pre><code>struct Trie_node\n{\n boost::container::vector<Trie_node> children;\n bool is_word;\n\n Trie_node(int n)\n : children(n)\n , is_word(false)\n { }\n};\n</code></pre></li>\n</ul>\n\n<p>… There’s more but these are the essential points that will help reduce code complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T12:32:36.200",
"Id": "29970",
"Score": "0",
"body": "Some of my suggestions from http://codereview.stackexchange.com/questions/18776/use-trie-data-structure-to-solve-the-problem-of-clustering-anagrams are still missing in his revision, like the use of `for_each` and similar algorithms; I suppose he could take a look at those if he's done with yours and still wants to improve it further. Seems I missed a few as well reading your suggestions... :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T12:46:56.227",
"Id": "29971",
"Score": "0",
"body": "@Tom Oops, I hadn’t noticed the previous thread at all. Good job there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T09:52:38.983",
"Id": "18789",
"ParentId": "18785",
"Score": "10"
}
},
{
"body": "<p>It seems you used wrong data structure for the task. All what you need is a simple dictionary (the c++ map class). The idea to find all anagrams for a specific word is the following:</p>\n\n<p>step 1: building map structure based on the dictionary - the key is a sorted by symbols word, the value is the list of anagrams.</p>\n\n<p>Example.</p>\n\n<p>dictionary : tac god act</p>\n\n<p>the map structure will be:</p>\n\n<p>act: [tac, act]\ndgo: [god]</p>\n\n<p>step 2: search - we take the checked words one by one, sort their chars and use the result string as a key.</p>\n\n<p>checked words: cat dog</p>\n\n<p>cat -> <strong>act</strong> (letters are sorted) -> get anagrams from the dictionary for the key <strong>act</strong> -> [tac, act]\ndog -> <strong>dgo</strong> (lettes are sorted) -> get ananagrams from the dictionary for the key <strong>dgo</strong> -> [god]</p>\n\n<p>Here is the complete python solution for the similar <a href=\"http://codercharts.com/puzzle/its-raining-anagrams\" rel=\"nofollow\">puzzle</a> (it could be like a pseudocode for the solution), the first parameter is a dictionary file, the second is the list of the checked words:</p>\n\n<pre><code>import sys\ncheckwords = open(sys.argv[2]).read().split()\nlens = set(len(word) for word in checkwords)\nindex = {}\nfor word in open(sys.argv[1]).read().split(): \n if len(word) in lens:\n index.setdefault(''.join(sorted(word)), []).append(word)\nfor word in checkwords: \n anagrams = index[''.join(sorted(word))]\n print str(len(anagrams)) + '\\n' + '\\n'.join(anagrams)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T21:38:36.170",
"Id": "30642",
"Score": "0",
"body": "I don’t think the trie is the wrong data structure here. In fact, a trie *is* a lookup structure for string keys, and potentially more efficient than other general-purpose dictionaries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T09:50:55.763",
"Id": "30654",
"Score": "0",
"body": "1. Dictionaries are built-in and high optimized classes that exist in every modern language. If you want to port code to python or ruby or java - you need to rewrite the Trie class.\n\n2. Trie class is not memory efficient class - try to put the big dictionary into the trie."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T09:52:28.123",
"Id": "30656",
"Score": "0",
"body": "So what? I’m assuming that the question was asked in a CS course in the context of tries. And in fact tries are a *very* common data structure because they are indispensable in many fields, and implementations exist for all relevant programming languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T10:12:30.810",
"Id": "30657",
"Score": "0",
"body": "That trie structure doesn't support unicode strings - so it's just a show stopper for a real use and a good chance to fail the interview."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T10:39:19.927",
"Id": "30658",
"Score": "0",
"body": "Superficial knowledge can be a dangerous thing so maybe you should just accept that I know what I’m talking about. Like I said, the trie in OP’s question is probably from the context of a CS course where this is irrelevant (forget Unicode! It only accepts lower-case letters). Likewise in interviews: just be able to *explain* the limitations. If that’s a show-stopper then the interviewer is an idiot. In general, a trie *can* be written with Unicode in mind but a restricted alphabet implementation is often sufficient / superior because of the special use-cases it’s employed to solve."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T10:44:08.357",
"Id": "30659",
"Score": "0",
"body": "And to answer your other point: a well-written trie is more memory-efficient than other implementations; it only stores each common prefix once and has very limited overhead because the areas where tries are commonly applied ensure that many strings will have common prefixes and are short."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:00:03.477",
"Id": "30667",
"Score": "0",
"body": "Ok. I've tested trie vs Set classes in java using 178 691 words dictionary. Here is the results: trie building time is about 5 times slower, trie search time is about 7 times slower. Memory consumption is about 7 times bigger. Enjoy. Here is the code: http://www.dropbox.com/sh/m8ocl4jycot9w5t/EMm8-DPTOl?lst"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T13:05:05.013",
"Id": "30681",
"Score": "0",
"body": "Added the python tests: the python trie is even worse - about 30 times slower and memory consumption is 70 times bigger."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T13:07:28.487",
"Id": "30682",
"Score": "0",
"body": "Kudos for testing this. However, I keep telling people not to do microbenchmarks because they are hellishly hard to get right and even seasoned CS researchers routinely do them wrong. In your case for instance you were benchmarking the reading from file, which distorts the result due to several factors. Furthermore, the Java trie implementation can me made more efficient. The Python implementation is totally irrelevant since the built-in set is highly optimised C code – which trie implementation did you use? Was it also highly optimised C code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T13:30:25.403",
"Id": "30684",
"Score": "0",
"body": "But in fairness, even with a corrected trie Java implementation and an improved benchmark code my trie is about twice as slow as the set for insertion, and more than four times as slow for retrieval. I blame cache locality. In special fields tries are used with special string (not general purpose ones) such as DNA and this may change the numbers significantly. However, I cannot reproduce this at the moment: in each scenario the trie is slower. Maybe Java’s reference indirection simply prevents an efficient implementation in principle."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T15:41:22.173",
"Id": "19067",
"ParentId": "18785",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T00:30:35.187",
"Id": "18785",
"Score": "11",
"Tags": [
"c++",
"algorithm",
"interview-questions",
"trie"
],
"Title": "Implementation of Trie data structure accommodating varying number of children"
}
|
18785
|
<p>How can I combine these <code>if</code> statements to make this a little cleaner and be less repetitive?</p>
<pre><code>$(document).keydown(function(e){
if (e.keyCode == 38) {
if($html.hasClass('client-loading') || canAnim === false) {
return false;
}
var $prevProj = $('.project-current').prev('.project');
$prevProj.click();
}
if (e.keyCode == 40) {
if($html.hasClass('client-loading') || canAnim === false) {
return false;
}
var $nextProj = $('.project-current').next('.project');
$nextProj.click();
}
// Prevent rapid clicking
if ( e.keyCode == 38 || e.keycode == 40 ) {
canAnim = false;
setTimeout(function(){
canAnim = true;
},2000);
}
});
</code></pre>
|
[] |
[
{
"body": "<p>This is about as concise as i think it will reasonably get. There might be a better way to handle double presses then a global variable timeout.</p>\n\n<pre><code>if ( e.keyCode == 38 || e.keycode == 40 ) \n{\n if( $html.hasClass('client-loading') || canAnim === false ) return false;\n\n if (e.keyCode == 38) var $prevProj = $('.project-current').prev('.project').click();\n if (e.keyCode == 40) var $nextProj = $('.project-current').next('.project').click(); \n canAnim = false;\n setTimeout(function() { canAnim = true;},2000); }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T14:35:21.123",
"Id": "18794",
"ParentId": "18792",
"Score": "0"
}
},
{
"body": "<p>The <code>switch</code> statement is made exactly for this kind of case.</p>\n\n<pre><code>$(document).keydown(function(e){\n var $proj;\n switch (e.keyCode) {\n case 38:\n if($html.hasClass('client-loading') || canAnim === false) {\n return false;\n }\n $proj = $('.project-current').prev('.project');\n break;\n\n case 40:\n if($html.hasClass('client-loading') || canAnim === false) {\n return false;\n }\n $proj = $('.project-current').next('.project');\n break;\n\n // Prevent rapid clicking\n case 38:\n case 40:\n canAnim = false;\n\n setTimeout(function(){\n canAnim = true;\n },2000);\n break;\n }\n\n $proj.click();\n});\n</code></pre>\n\n<p>You can also notice the small refactoring I applied. Keeps some common stuff out of the switch, so that less code is in each case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:29:28.563",
"Id": "29987",
"Score": "1",
"body": "Won't work. Once you `break`, the rest of the cases are skipped. I.e. the timeout code will never be executed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T15:04:53.143",
"Id": "18795",
"ParentId": "18792",
"Score": "-4"
}
},
{
"body": "<p>Here's another one, just for the heck of it</p>\n\n<pre><code>$(document).keydown(function (e) {\n var current;\n\n // return early\n if( e.keyCode !== 38 && e.keyCode !== 40 ) {\n return false;\n }\n\n // again, return early\n if( $html.hasClass('client-loading') || canAnim === false ) {\n return false;\n }\n\n current = $('.project-current');\n\n if( e.keyCode === 38 ) {\n current.prev('.project').click();\n }\n\n if( e.keyCode === 40 ) {\n current.next('.project').click();\n }\n\n canAnim = false;\n setTimeout(function () { canAnim = true; }, 2000);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:22:54.220",
"Id": "65962",
"Score": "0",
"body": "I believe `canAnim` and `setTimeout` should be done before the second return early."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:38:50.293",
"Id": "65993",
"Score": "0",
"body": "@SimonAndréForsberg Heh, took me a while to decipher this old code again. Anyway, I'm not so sure about your suggestion. As far as I can tell, the timeout should only be set if we've actually called `click()` on something (i.e. only if we make it past the 2 early returns). It's either-or: Either go next/prev and set a timeout, _or_ do nothing at all. If `setTimeout` is called before the 2nd return, as you suggest, rapid key presses will keep setting new timeouts even if they're otherwise ignored."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T07:45:14.267",
"Id": "66060",
"Score": "0",
"body": "Oh, you're right. +1 then :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:27:55.743",
"Id": "18804",
"ParentId": "18792",
"Score": "2"
}
},
{
"body": "<pre><code>$(document).keydown(function (e) {\n\n //there is a very minor overhead when accessing properties\n //or querying elements in jQuery\n //cache the value in a variable if they are to be used repeatedly\n //\n //if they don't change during the course of the page's life,\n //or by dynamic means, cache them outside the handler\n //\n //I'll just assume .project-current is dynamic and will need requerying\n //everytime we call the handler\n\n var keycode = e.keyCode,\n loading = $html.hasClass('client-loading'),\n currentProject = $('.project-current');\n\n //run the code only on 38 and 40, when not loading and can animate\n //otherwise do nothing\n //why would you run code when it shouldn't?\n\n //when testing for boolean, it makes no sense comparing to true and false\n //you can use the variable directly to represent it's state\n\n if((keycode===38 || keycode===40) && !loading && canAnim ){\n\n //there is a minor optimization done when using \"else\"\n //when the first condition is met, conditions chained with else\n //will not be evaluated anymore. This means process time savings\n //without it, the second condition will still be evaluated\n\n if(keycode===38){\n currentProject.prev('.project').click();\n } else if(keyCode===40){\n currentProject.next('.project').click();\n }\n\n canAnim = false;\n setTimeout(function(){\n canAnim = true;\n },2000);\n\n } \n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T18:42:29.687",
"Id": "31736",
"Score": "1",
"body": "The line `} else if (e.keyCode===40){` should presumably read `keyCode` instead of `e.keyCode` and anyway you could just have a simple `} else {` there since you have already checked keyCode is either 38 or 40."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-22T01:48:40.553",
"Id": "31746",
"Score": "0",
"body": "@Stuart thanks! kinda forgot that I already cached the keycode value. However, I added the additional \"if 40\" for clarity. If I omitted it, a future developer might miss reading the \"if 38 || 40\" at the top and might think that the \"if 40\" part was a \"default\" like in a `switch` statement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:15:09.903",
"Id": "18844",
"ParentId": "18792",
"Score": "0"
}
},
{
"body": "<p>Less readable, but another way.</p>\n\n<pre><code>var prevNext = (e.keyCode == 38) ? \"prev\" : \n (e.keyCode == 40) : \"next\" : null;\nif ( prevNext && !$html.hasClass('client-loading') && canAnim !== false ) {\n $('.project-current')[prevNext]('.project').click(); \n canAnim = false;\n setTimeout(function() { canAnim = true;},2000); }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T18:40:05.953",
"Id": "31734",
"Score": "0",
"body": "think on the 2nd line it should be `e.keyCode == 40` ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:23:43.470",
"Id": "18856",
"ParentId": "18792",
"Score": "2"
}
},
{
"body": "<p>Another variation. I've taken the liberty of altering the method of timing, but that can easily be reverted.</p>\n\n<pre><code>$(document).keydown(function(e) {\n var now = (new Date()).getTime(), direction = ({38: 'prev', 40: 'next'})[e.keyCode];\n if (!direction || $html.hasClass('client-loading') || now < lastPressed + 2000) {\n return false;\n }\n lastPressed = now;\n $('.project-current')[direction]('.project').click();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T18:58:30.370",
"Id": "19851",
"ParentId": "18792",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T13:16:01.127",
"Id": "18792",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Keypress function conditional"
}
|
18792
|
<p>I run a small server, and to check whether clients are being hosted on my server, I wrote this. I'm new to object oriented programming. How stratified should my programs really be? Do I want to have every possible variable and piece in their own function? Also, how am I doing in general? Any recommendations?</p>
<pre><code>class Domain_check
def vhost_grab
return full_domain_path = `ls /etc/httpd/conf.d/vhost_* | grep -v 000_defaults.conf`.chomp.split(' ')
end
def vhost_stripper
prefix = Domain_check.new.vhost_grab
vhost_stripped = []
prefix.each_index do |x|
vhost_stripped[x] = `echo '#{prefix[x]}' | awk -F'vhost_' '{print $2}' | awk -F'.conf' '{print $1}'`
end
return vhost_stripped
end
def vhost_display
puts "\n%s %40s %43s" %["Domain name", "IP Address Listed", "IP Address Currently in Use"]
final_vhost = vhost_stripper
final_vhost.each_index { |x|
padding = 50
print final_vhost[x].strip
padding = padding.to_i - final_vhost[x].length
print "%0#{padding}s" %[`grep '<VirtualHost .*:80>' #{Domain_check.new.vhost_grab[x]} | awk -F'<VirtualHost' '{print $2}'|awk -F':' '{print $1}'`.strip.to_s]
puts "%40s" %[`dig #{final_vhost[x].strip} +short`]
}
end
end
d1 = Domain_check.new
d1.vhost_display
</code></pre>
|
[] |
[
{
"body": "<p>Some observations:</p>\n\n<ul>\n<li><p>Regarding the \"stratification\". It's hard to give practical advice, this is something that comes from experience and personal taste. Some basics to start with: a) write classes/modules with low coupling to achieve real modularization, b) write fairly short methods than do only one thing. c) Keep model-view separations. d) Don't use global variables.</p></li>\n<li><p><code>class Domain_check</code>: that's against Ruby practices, a class or module names are named <em>CamelCase</em>: <code>class DomainCheck</code>.</p></li>\n<li><p>Don't write an explicit <code>return</code> on the last line of a method/block, it's non idiomatic. </p></li>\n<li><p>Don't assign a variable on this last expression, why would be it different from the method name itself? </p></li>\n<li><p>Don't call to external commands (ls, grep, awk, ...), Ruby is more than able to perform those tasks, check the <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/\" rel=\"nofollow\">standard library</a>.</p></li>\n<li><p>About this: <code>prefix = DomainCheck.new.vhost_grab</code>. You are already in the instance, just <code>prefix = vhost_grab</code>.</p></li>\n<li><p>You are using a <code>class</code> just nominaly, you don't use any of its facilities. You can convert all these methods to classmethods if you store nothing in the instances.</p></li>\n<li><p>Init empty + iterate with <code>each</code> + <code>push</code> is an anti-pattern in Ruby (and in any language with decent functional capabilities, for that matter). Use <code>Enumerable#map</code>. Also, you use <code>each_index</code> to iterate in a C fashion, use <code>each</code> (or better, <code>map</code>, <code>select</code>, <code>inject</code>, as required, read the <a href=\"http://ruby-doc.org/core-1.9.3/Enumerable.html\" rel=\"nofollow\">Enumerable</a> documentation from start to finish).</p></li>\n<li><p>Having only a C background your code has a serious problem, it's very, very imperative. <a href=\"http://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow\">Functional programming</a> allows far better abstraction and clarity, check <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">this wiki page I maintain</a>.</p></li>\n<li><p>If every method is prefixed with <code>vhost_</code> there's no point in prefixing anything. Besides, if all the methods start with <code>vhost_</code>, the class should probably be called <code>VirtualHostChecker</code> instead (@Flambino).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:12:16.940",
"Id": "29986",
"Score": "2",
"body": "+1 - I think you touched on everything. Only thing I'd add is that if every method is prefixed with `vhost_` there's no point in prefixing anything. Besides, if all the methods start with `vhost_`, the class should probably be called `VirtualHostChecker` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:58:59.130",
"Id": "29990",
"Score": "1",
"body": "@Flambino: I also frowned upon all theses prefixed `vhost_`, you explained it very well, edited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T20:25:40.890",
"Id": "29993",
"Score": "0",
"body": "I know this is sort of a silly question, but how do you learn if you don't ask, right? :)\nAre using bash commands within ruby programs just a bad practice, or is there a performance hit involved also?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T21:08:52.933",
"Id": "29997",
"Score": "1",
"body": "@SecurityGate: someone said there are no stupid questions, only stupid answers :-) Yeah, it will be slower if you call external programs, no doubt, but I don't think there's a serious performance hit unless you create a *lot* of processes (and you know, Linux for example is very efficient on creating new processes). If it's a bad practice is mainly because it makes the script less portable and mixes unnecessarily another language and tools when Ruby is already a great language to do text processing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T22:02:18.820",
"Id": "30003",
"Score": "2",
"body": "@SecurityGate As tokland just wrote, it's certainly not \"wrong\" to invoke shell commands in Ruby. It's just that your code is doing so much shell invocation, that _Ruby_ ends up being the unnecessary element in the mix. I.e. the \"meat\" of all three methods is shell commands anyway, so you could no doubt write it all as a plain bash script -- _or_ you could use Ruby to a fuller extent, and gain some nice code (it's a lovely language). It's just that right now, your code is doing both and neither, so to speak."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T14:37:13.850",
"Id": "30046",
"Score": "0",
"body": "One final question, I read through your recommendations, and I really appreciate them, it's nice to get some constructive recommendations. :) How do I keep my functions modular, while passing a value through them? I know I can use global variables or class variables, but is there a different way to go about it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T16:36:24.507",
"Id": "30060",
"Score": "0",
"body": "If you check the FP docs I linked, you'll realize that global state is a bad idea. So don't use global variables (read-only vars are ok, I talk about updating them), variables used by a function should be arguments to that function. With OOP this rule is widen to include instance variables (watch out, no class variables) since the instance itself can be seen as an argument to a method. But again, better code style is achieved when no variables, not even instance variables are modified in-place (check Scala for example, a functional OOP language). Create new objects instead of updating them."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T16:32:57.377",
"Id": "18797",
"ParentId": "18796",
"Score": "7"
}
},
{
"body": "<p>I would highly recommend picking up a copy of \"<a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean Code</a>\" by Robert C. Martin. All of the example code in the book is in Java, but as a Ruby developer with absolutely no Java background I was still able to get a <em>lot</em> out of the book.</p>\n\n<p>It won't teach you Ruby specific conventions like when to use CamelCaseNames (classes and modules) vs underscored_names (methods and variables) vs ALL_UPPERCASE (constants). It does, however, do an <em>excellent</em> job of explaining how to write good, readable, object oriented code that is highly applicable to any OO language.</p>\n\n<p>For instance, it would probably have taught you to..</p>\n\n<ul>\n<li>rename the Domain_check class to something more appropriate, such as VirtualHostPrinter, since that is, in fact, what this class does.</li>\n<li>not prefix your method names with <code>vhost_</code> (Chapter 2, \"Meaningful Names\", \"Avoid Encodings/Member Prefixes\" section)</li>\n<li>use method and variable names to describe precisely what they do</li>\n<li>break complex methods down into more/smaller methods that do only one thing each (see <a href=\"https://www.google.com/search?client=ubuntu&channel=fs&q=single%20responsibility%20principal&ie=utf-8&oe=utf-8\" rel=\"nofollow\">Single Responsibility Principal</a>)</li>\n<li>etc.</li>\n</ul>\n\n<p>Below is your code after I applied some refactoring. I would have done more with the awks and greps to refactor those into pure ruby, but my awk is rusty and I wasn't sure exactly what you were trying to achieve. </p>\n\n<pre><code>class VirtualHostPrinter\n class << self\n\n def engage\n print_formatted_header\n domain_paths.each do |domain_path|\n print_virtual_host_for(domain_path)\n end\n end\n\n #######\n private\n #######\n\n def print_formatted_header\n puts \"\\n%s %40s %43s\" %[\"Domain name\", \"IP Address Listed\", \"IP Address Currently in Use\"]\n end\n\n def domain_paths\n `ls /etc/httpd/conf.d/vhost_* | grep -v 00_defaults.conf`.chomp.split(' ')\n end\n\n def print_virtual_host_for(domain_path)\n print strip(domain_path)\n print \"%0#{padding_for(domain_path)}s\" %[`grep '<VirtualHost .*:80>' #{domain_path} | awk -F'<VirtualHost' '{print $2}'|awk -F':' '{print $1}'`.strip.to_s]\n puts \"%40s\" %[`dig #{final_vhost[x].strip} +short`]\n end\n\n def strip(domain_path)\n `echo '#{domain_path}' | awk -F'vhost_' '{print $2}' | awk -F'.conf' '{print $1}'`\n end\n\n def padding_for(domain_path)\n 50 - strip(domain_path).length\n end\n end\nend\n\nVirtualHostPrinter.engage\n</code></pre>\n\n<p>Note, that I haven't tested this at all to see if it actually works, and outside the full context of the rest of the program, it's hard to say if any of this actually makes any sense.</p>\n\n<p>Also note that I didn't just rewrite your code from scratch. I made a copy of your code and then applied lots and lots of very small incremental changes. Much of my intermediate code got completely removed as later refactorings made it obsolete. There's lots more refactoring that could be done to make this even more clean and readable, but I think this is a step in the right direction.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:59:30.160",
"Id": "19169",
"ParentId": "18796",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18797",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T15:16:11.153",
"Id": "18796",
"Score": "3",
"Tags": [
"beginner",
"ruby"
],
"Title": "Checking host status for clients on server"
}
|
18796
|
<p>I wrote a little code to list a number's prime factors:</p>
<pre><code>import java.util.Scanner;
import java.util.Vector;
public class Factorise2
{
public static Vector<Integer> get_prime_factors(int number)
{
//Get the absolute value so that the algorithm works for negative numbers
int absoluteNumber = Math.abs(number);
Vector<Integer> primefactors = new Vector<Integer>();
//Get the square root so that we can break earlier if it's prime
for (int j = 2; j <= absoluteNumber;)
{
//Test for divisibility by j
if (absoluteNumber % j == 0)
{
primefactors.add(j);
absoluteNumber /= j;
if (newprime && j > (int)Math.sqrt(absoluteNumber))
{
break;
}
}
else j++;
}
return primefactors;
}
public static void main(String[] args)
{
//Declare and initialise variables
int number;
int count = 1;
Scanner scan = new Scanner(System.in);
//Get a number to work with
System.out.println("Enter integer to analyse:");
number = scan.nextInt();
//Get the prime factors of the number
Vector<Integer> primefactors = get_prime_factors(number);
//Group the factors together and display them on the screen
System.out.print("Prime factors of " + number + " are ");
primefactors.add(0);
for (int a = 0; a < primefactors.size() - 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
else
{
System.out.print(primefactors.elementAt(a) + " (" + count + ") ");
count = 1;
}
}
}
}
</code></pre>
<p>I decided that I would try to optimise the algorithm, by skipping testing for divisibility with composite numbers.</p>
<pre><code>import java.util.Scanner;
import java.util.Vector;
public class Factorise2
{
public static Vector<Integer> get_prime_factors(int number)
{
//Get the absolute value so that the algorithm works for negative numbers
int absoluteNumber = Math.abs(number);
Vector<Integer> primefactors = new Vector<Integer>();
Vector<Integer> newprimes = new Vector<Integer>();
boolean newprime = true;
int b;
//Get the square root so that we can break earlier if it's prime
for (int j = 2; j <= absoluteNumber;)
{
//Test for divisibility by j, and add to the list of prime factors if it's divisible.
if (absoluteNumber % j == 0)
{
primefactors.add(j);
absoluteNumber /= j;
if (newprime && j > (int)Math.sqrt(absoluteNumber))
{
break;
}
newprime = false;
}
else
{
for (int a = 0; a < newprimes.size();)
{
//Change j to the next prime
b = newprimes.elementAt(a);
if (j % b == 0)
{
j++;
a = 0;
}
else
{
a++;
}
}
//Add j as a new known prime;
newprimes.add(j);
newprime = true;
}
}
return primefactors;
}
public static void main(String[] args)
{
//Declare and initialise variables
int number;
int count = 1;
Scanner scan = new Scanner(System.in);
//Get a number to work with
System.out.println("Enter integer to analyse:");
number = scan.nextInt();
//Get the prime factors of the number
Vector<Integer> primefactors = get_prime_factors(number);
//Group the factors together and display them on the screen
System.out.print("Prime factors of " + number + " are ");
primefactors.add(0);
for (int a = 0; a < primefactors.size() - 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
else
{
System.out.print(primefactors.elementAt(a) + " (" + count + ") ");
count = 1;
}
}
}
}
</code></pre>
<p>I can't see anything that I have done wrong, but it is much slower. On 9876103, for example, it takes too long to wait for it to report back that its only prime factor is itself. Can anyone see why it is eating CPU cycles?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:54:36.073",
"Id": "29981",
"Score": "1",
"body": "By a glance: you have nested loops in second version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:55:41.130",
"Id": "29982",
"Score": "4",
"body": "Do not use `Vector` as it is `synchronized`. Use an unsynchronized Collection class like `ArrayList` or similar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-07T16:11:04.333",
"Id": "119119",
"Score": "0",
"body": "Use Sieve of Eratosthenes."
}
] |
[
{
"body": "<p>Q: Do you know if it's a) \"consuming a lot of CPU cycles\", or b) just \"taking a long time\"?</p>\n\n<p>I suspect the latter - that you're <em>underutilizing</em> the CPU ... because you're using (legacy, Java 1.0) \"Vector\" instead of an ArrayList.</p>\n\n<p>Try ArrayList, and benchmark the difference.</p>\n\n<p>Be sure to look at \"Task Mgr\" (Windows) or \"top\" (Linux) to check CPU utilization.</p>\n\n<p>My guess is that you'll have <em>higher</em> CPU usage for the ArrayList version ... and that the ArrayList version will complete sooner :)</p>\n\n<p>IMHO...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T19:10:34.360",
"Id": "29983",
"Score": "0",
"body": "They both max out the CPU, and both are equally slow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T16:49:09.443",
"Id": "30210",
"Score": "0",
"body": "you can not see cpu cycles in task manager or top. and even if you see cpu cycles, you do not know the load factor for modern cpus. For java, focus on algorithms, not cpu optimizations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-07T16:27:45.643",
"Id": "119128",
"Score": "0",
"body": "@tb You can use procexp.exe for that. you can download it from here: technet.microsoft.com/en-us/sysinternals/bb896653.aspx"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:58:52.987",
"Id": "18800",
"ParentId": "18799",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p>I decided that I would try to optimise the algorithm, by skipping testing for divisibility with composite numbers.</p>\n</blockquote>\n\n<p>That is only worthwhile if you factorise a lot of numbers. And then you need to remember the list of known primes between different factorisations.</p>\n\n<p>In your case, the change is a massive pessimisation, because now you check each potential divisor for primality, which in the best case takes one division, and in the worst case about <code>2*sqrt(j)/log(j)</code> divisions. The worst case, which is common enough, takes much much more time than a simple division by <code>j</code> to check whether <code>j</code> is a divisor.</p>\n\n<p>You have changed the algorithm from <code>O(sqrt(n))</code> complexity for the simple trial division to about <code>O(n^0.75)</code> (ignoring logarithmic factors) in good cases, and about <code>O(n^1.5)</code> in the worst case (when <code>n</code> is a prime).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T19:14:36.627",
"Id": "18801",
"ParentId": "18799",
"Score": "8"
}
},
{
"body": "<p>I do not think that your algorithm is correct. Try to run it for 24=2*2*2*3 (first version)</p>\n\n<p>I think the sqrt part is not correct. Even more, a sqrt is quite hard to calculate.<br>\nThink about it and change it (you can completely remove this part)</p>\n\n<p>After you have fixed it, try to compare both cases, make a small example.<br>\nLets look at 100.</p>\n\n<p>Before:</p>\n\n<pre><code>number = 100\nj = 2\n100 % 2 = 0, (2)\nnumber = 50\n50 % 2 = 0, (2,2)\nnumber = 25\nj = 3\nj = 4\nj = 5\n25 / 5 = 5 (2,2,5)\nnumber = 5\n5 % 5 = 0 (2,2,5,5)\nnumber = 1\nend\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>number = 100\nj = 2\n100 % 2 = 0, (2)\nnumber = 50\n50 % 2 = 0, (2,2)\nnumber = 25\nj = 3\n-something is happening\nj = 4\n-something is happening\nj = 5\n25 / 5 = 5 (2,2,5)\nnumber = 5\n5 % 5 = 0 (2,2,5,5)\nnumber = 1\nend\n</code></pre>\n\n<p>As you see, you just do more work.</p>\n\n<p>And now the last thing: The new version is wrong, too. Try 4 or 9.<br>\nAnd I do not see the idea behind it, so I can not help you there.</p>\n\n<p>For the complexity, see answer from Daniel Fischer.</p>\n\n<p>In general, i would advise to not do any speed optimization until it is really needed and then only for profiled code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T17:22:58.757",
"Id": "18942",
"ParentId": "18799",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "18801",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T18:52:34.920",
"Id": "18799",
"Score": "3",
"Tags": [
"java",
"performance",
"beginner",
"primes"
],
"Title": "Listing a number's prime factors"
}
|
18799
|
<p>I am not a DBA nor do I play one on TV. </p>
<p>My application is retrieving information from Facebook and storing it into our own database. I want to retrieve the Location Post information of <code>Id and AuthorId</code>. <code>AuthorId</code> is a foreign key to another table. I was told by a DBA that foreign keys should always use internal unique identifiers because you can never rely on external unique identifiers. So I created the following table structure...</p>
<pre><code>CREATE TABLE tblAuthor
(
[MyAuthorId] INT NOT NULL PRIMARY KEY IDENTITY
[FacebookAuthorId] BIGINT NOT NULL
...Additional Facebook information...
)
CREATE TABLE tblLocationPost
(
[MyLocationPostId] INT NOT NULL PRIMARY KEY IDENTITY,
[FacebookLocationPostId] BIGINT NOT NULL,
[MyAuthorId] INT NOT NULL,
...Additional Facebook information...
CONSTRAINT [FK_tblLocationPost_Author] FOREIGN KEY (MyAuthorId) REFERENCES tblAuthor(MyAuthorId)
)
</code></pre>
<p>The data I get back from Facebook when querying Location Post is LocationPostId and AuthorId. So I have created the following stored procedure to insert/update the LocationPost information in the database...</p>
<pre><code>CREATE PROCEDURE [dbo].[LocationPost_Save]
@facebookLocationPostId bigint,
@facebookAuthorId bigint
AS
BEGIN
DECLARE @myAuthorId INT
DECLARE @IdentityColumn TABLE ( IdentityId int )
BEGIN TRANSACTION
/* Locate out internal unique id using facebooks unique author id, insert it if necessary */
IF EXISTS (SELECT * FROM tblAuthor WHERE FacebookAuthorId = @facebookAuthorId)
BEGIN
SELECT @myAuthorId = MyAuthorId FROM tblAuthor WHERE FacebookAuthorId = @facebookAuthorId
END
ELSE
BEGIN
INSERT INTO tblAuthor (FacebookAuthorId) VALUES (@facebookAuthorId)
SELECT @myAuthorId = SCOPE_IDENTITY()
END
/* Insert/Update one row in LocationPost */
MERGE tblLocationPost lp
USING (SELECT @facebookId as FacebookId) fb
ON (lp.FacebookId = fb.FacebookId)
WHEN MATCHED THEN
UPDATE SET
MyAuthorId = @myAuthorId,
...Additional data...
WHEN NOT MATCHED THEN
INSERT
(FacebookLocationPostId, MyAuthorId, ...Additional Columns...)
VALUES
(@facebookLocationPostId, @myAuthorId, ...Additional Values...)
OUTPUT INSERTED.MyLocationPostId INTO @IdentityColumn;
COMMIT TRANSACTION
/* Return the identify column of Inserted/Updated row */
SELECT IdentityId FROM @IdentityColumn
END
</code></pre>
<ol>
<li><p>Is this the correct pattern to use for this scenerio or is there a better approach?</p></li>
<li><p>Is the MERGE command the appropriate approach to Insert/Update a record (I am using SQL Server 2008)?</p></li>
<li><p>Do I really need to put my own Author Unique Id in the LocationPost table, or can I simplify this by putting the Facebook Unique Id?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T21:26:35.803",
"Id": "29999",
"Score": "1",
"body": "Generally, the way I see the whole \"don't allow external primary key\" bit, is when an external entities are attempting to declare internal primary keys that _your_ system has to manage. When you're essentially mirroring somebody _else's_ system (as you are here), there's no point, because you have to use _their_ primary keys to match up the records anyways (meaning, you'd essentially have two primary keys, with the same effect, you just 'trust' one 'less')."
}
] |
[
{
"body": "<ol>\n<li>I'd rather use the <code>FacebookAuthorId</code> and <code>FacebookLocationPostId</code> as primary keys, because your logic ensures them to be unique. In case of your current solution you would still require (unique) indexes on these fields (in order for lookups to be efficient) so there is no reason not to use them as primary keys.</li>\n<li>Given suggest optimization you don't need to check/insert an author record <code>LocationPost_Save</code>, just use the merge to insert/update the data in the table, and create a separate <code>Author_Save</code> SP that will do the same job for Authors.</li>\n</ol>\n\n<p>Having said that, assuming that you are using one of the high-level languages :) and you're developing a long-living solution I would actually recommend you to use one of the ORMs available for your language to interact with the database. It'll take a bit longer at the beginning, but you'll get a more flexible solution in a long term.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:12:14.453",
"Id": "30050",
"Score": "0",
"body": "On your note about ORM's. I have always heard they are not efficient because they do not precompile the T-SQL statements as stored procedures do. Is this no longer true? Our application could potentially have hundreds (maybe even thousands) of hits a second during certain times of day."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T10:58:50.587",
"Id": "30098",
"Score": "0",
"body": "You should not be worried about pre-compilation at this stage as it's an example of \"premature optimization\" (google this term). And answering your question - no, they don't suffer from not being pre-compiled because most DBMS (and SQL Server, of course) cache execution plans (\"compiled T-SQL statements\") and thus ORM-generated statements will still be as quick as stored procedures. You might require a tuning stage where you profile queries generated in order to optimize the performance where necessary, but that stage should be done **after** you've got real-world usage statistics"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:51:05.240",
"Id": "18806",
"ParentId": "18803",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18806",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T17:59:47.437",
"Id": "18803",
"Score": "3",
"Tags": [
"sql",
"sql-server"
],
"Title": "Review Insert/Update stored procedure"
}
|
18803
|
<p>I'm evaluating a <code>meeting_type</code> value that determines what kind of pricing structure I should be using. Currently, if my <code>meeting_type</code> value is a <code>w</code>, we charge one price for every 10 registrants. If the <code>meeting_type</code> is anything else, it's a price per registrant model. </p>
<p>I'm using this logic:</p>
<pre><code>if($_POST['meeting_type'] != 'w'){
$total_price = $guests * $price;
}
else{
$webinar_count = ceil($guests / 10);
$total_price = $webinar_count * $price;
}
</code></pre>
<p>Is this logic flawed? Can it be improved upon?</p>
|
[] |
[
{
"body": "<p><strong>Removing intermediate variable <code>$webinar_count</code></strong></p>\n\n<pre><code>$total_price = ($_POST['meeting_type'] == 'w')\n ? (ceil($guests / 10) * $price)\n : ($guests * $price);\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>if ($_POST['meeting_type'] != 'w') {\n $total_price = $guests * $price;\n} else {\n $total_price = ceil($guests / 10) * $price;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T14:42:52.203",
"Id": "18843",
"ParentId": "18805",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T18:44:12.690",
"Id": "18805",
"Score": "3",
"Tags": [
"php"
],
"Title": "Calculating a total price with group pricing"
}
|
18805
|
<p>I'm looking for advice and ways on making it better.</p>
<p><a href="https://github.com/Prashles/Validation" rel="nofollow">Code</a></p>
<pre><code><?php
Class Validate {
private $_errors = array();
public function __construct()
{
require_once 'errors.php';
$this->errorText = $errorText;
}
public function rule($value, $name, $inputRules)
{
$inputRules = explode('|', $inputRules);
foreach ($inputRules as $inputRule) {
if (!strlen($value) && $inputRule != 'required') {
break;
}
if (preg_match('/\[(.*?)\]/', $inputRule, $match)) {
$rule = explode('[', $inputRule);
$rule = $rule[0];
$param = $match[1];
if (!method_exists($this, $rule)) {
throw new Exception("Method {$rule} does not exist");
exit;
}
$call = array($value, $param);
}
else {
if (!method_exists($this, $inputRule)) {
throw new Exception("Method {$inputRule} does not exist");
exit;
}
$rule = $inputRule;
$call = array($value);
}
$response = call_user_func_array(array($this, $rule), $call);
if ($response) {
$error = $this->errorText[$rule];
$replace = array(
':name' => $name,
':param' => (isset($param)) ? $param : NULL
);
$response = str_replace(array_keys($replace), array_values($replace), $error);
$this->_errors[] = $response;
}
}
}
public function exec()
{
return (empty($this->_errors)) ? false : $this->_errors;
}
/*
* Rule functions
*/
public function min_length($value, $param)
{
return (strlen($value) < $param);
}
public function max_length($value, $param)
{
return (strlen($value) > $param);
}
public function email($value)
{
return !filter_var($value, FILTER_VALIDATE_EMAIL);
}
public function required($value)
{
return (strlen($value) !== 0);
}
public function ip($value)
{
return !filter_var($value, FILTER_VALIDATE_IP);
}
public function match($value, $param)
{
return ($value != $param);
}
public function match_exact($value, $param)
{
return ($value !== $param);
}
public function match_password($value, $param)
{
return ($value !== $param);
}
public function alphanum($value)
{
return !ctype_alnum($value);
}
public function url($value)
{
return !filter_var($value, FILTER_VALIDATE_URL);
}
public function numeric($value)
{
return !(is_numeric($value));
}
public function min($value)
{
return ($value < $param);
}
public function max($value) {
return ($value > $param);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Judging your interface: Nice!</p>\n\n<p>You could have provided some static method for simpler checking:</p>\n\n<pre><code>if( Validate::check($email, 'Email', 'required|email') ){ ... }\n</code></pre>\n\n<p>or and check-all-at-once method</p>\n\n<pre><code>$errors = Validate::checkall( array(\n array($email, 'Email', 'required|email'),\n array($name, 'Name', 'required'),\n) );\nif( sizeof( $errors ) ){\n # print errors\n}\n</code></pre>\n\n<p>It looks really nice so far!</p>\n\n<p>Edit: I looked at the two classes: It's really nice! It's undocumented and it's still understandable!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T22:18:54.887",
"Id": "30005",
"Score": "0",
"body": "Thanks man!\nYeah, I wanted something that you could instansiate for each form you're validating, which is why I didn't use static methods. Good suggestion though!\nAppreciate the compliments :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T21:46:26.290",
"Id": "18816",
"ParentId": "18814",
"Score": "2"
}
},
{
"body": "<p><strong>Technical Issues</strong></p>\n\n<pre><code>public function __construct()\n{\n require_once 'errors.php';\n $this->errorText = $errorText;\n}\n</code></pre>\n\n<p>Will not do what you think it will do.</p>\n\n<pre><code>$val1 = new Validate();\n$val2 = new Validate();\n</code></pre>\n\n<p>The second instance will not include 'errors.php', and thus <code>$errorText</code> will not be defined.</p>\n\n<p>You should probably consider generalizing your error message handling since you might need to have different messages or internationalization.</p>\n\n<p>In other words, your class should probably either return error codes (class constants), or your class should have some kind of facility for requesting a different error message at run time.</p>\n\n<p>If you do stick with your current approach though, consider structuring it something like:</p>\n\n<pre><code>public function __construct()\n{\n $this->errorText = $this->getErrorText();\n}\n\nprivate function getErrorText()\n{\n include 'errors.php';\n}\n</code></pre>\n\n<p>Your <code>errors.php</code> would then look like:</p>\n\n<pre><code><?php\nreturn array(\n 'something' => 'Some message'\n 'somethingElse' => 'some other message',\n ...\n);\n</code></pre>\n\n<p>This would of course mean that the file is included on every object instantiation though. A different approach could be to store the messages in a static variable the first time they're needed.</p>\n\n<p>Also, while I'm talking about this, <code>errors.php</code> could be a problematic path. You should probably use something like <code>dirname(__FILE__) . '/errors.php';</code> so the path is more resistant to outside factors.</p>\n\n<hr>\n\n<pre><code>if (!method_exists($this, $rule)) {\n throw new Exception(\"Method {$rule} does not exist\");\n exit;\n}\n</code></pre>\n\n<p>There's two issues here:</p>\n\n<ul>\n<li><code>exit</code> will never be reached</li>\n<li><code>exit</code> shouldn't here</li>\n</ul>\n\n<p>When you throw an exception, you bail out of the current scope up until you hit a catch block. No code under the throw will be executed.</p>\n\n<pre><code>function f() {\n throw new Exception();\n //No code here is ever excecuted\n}\n\nfunction f() {\n if (...) {\n throw new Exception();\n //Code here is never excecuted\n }\n //Code here will be executed only if the throw above is not reached\n}\n\nfunction f() {\n try {\n if () {\n throw new Exception();\n //Code here is never exceuted\n }\n //Code here is executed if the throw is not reached\n } catch (Exception $e) { }\n //Code here is always executed\n}\n</code></pre>\n\n<p>It gets a bit more complicated than that, but those examples should illustrate the basic behavior.</p>\n\n<p><code>exit</code> shouldn't be in there anyway though. Would you actually want script execution to completely stop? Typically <code>exit</code> should only be used if there is no way to continue the program execution without compromising security or stability.</p>\n\n<p>Imagine if instead of throwing exceptions, you had only the exits there. This means that no error message would be displayed. Nothing would be logged. The code would just bail.</p>\n\n<p>Imagine if someone was using your class based only on the API. They would have no idea why the code exited.</p>\n\n<p>Typically low level flow control like exiting or redirecting to a different page, so on, should be handled in dedicated \"controller\" code and not in classes that have responsibilities unrelated to that.</p>\n\n<p>Throwing an exception is the right thing to do here. It allows the code that called <code>rule</code> to decide how to handle it. <code>rule</code> should only responsible for saying \"Hey, ummm, something wen't horribly wrong,\" not deciding how to handle it. (In fact, an uncaught exception is basically an <code>exit</code> with debugging information included :p. You do have to be careful with uncaught exceptions though as you need to make sure they don't get displayed to end clients. Some exceptions, like <code>PDOException</code>, may contain sensitive data like database credentials.)</p>\n\n<p><strong>Design Issues</strong></p>\n\n<p>Your class does way too much. This is just using a class as a collection of functions. Each validation can be seen as a \"responsibility\" and thus your class completely violates the single responsibility principle.</p>\n\n<p>Imagine that in the future you want to add a new validation. How can you do this? Well, you have two options, both of which are unpleasant:</p>\n\n<ol>\n<li><p>Edit the source code. What if many people are using your class though, or you're using it across 10 applications? Suddenly you have a lot of version management going on. Since you control the class, you could just commit it all to git which would alleviate the synchronization, but what about end-consumers of your code? This isn't a viable option for them.</p></li>\n<li><p>Extend the class. This is also a bad option. You would have to change all of the object types in your code to be a <code>MyValidation</code> instead of <code>Validation</code>. Depending on how widespread this was, this could be a huge chore.</p></li>\n</ol>\n\n<p>Or, you have a third option. Scrap your current design and abstract each validation into its own class. You could have a very simple interface:</p>\n\n<pre><code>interface Validator\n{\n\n /**\n * Validates the given $data against whatever rule(s) the implementation of this\n * interface enforces. Returns an array of error messages, or an empty array\n * if $data is valid.\n *\n * @param mixed $data\n * @return array An array of error messages\n */\n public validate($data);\n\n}\n</code></pre>\n\n<p>And then you could build on this:</p>\n\n<pre><code>class RangeValidator implements Validator\n{\n\n private $_from;\n private $_to;\n\n const ERROR_INVALID_TYPE = 'type';\n const ERROR_OUT_OF_RANGE = 'range';\n\n //You could pull this into an abstract base class to handle code -> message mapping automatically.\n //That would also allow for easy internationalization later. \n private $_messages = array(\n\n );\n\n public function __construct($from, $to)\n {\n //You could make this a lot looser and perhaps put it in methods setFrom and setTo.\n //Just an example.\n if (!is_int($from)) {\n throw new InvalidArgumentException(\"\\$from must be an int. Given value: '{$from}'\");\n }\n if (!is_int($to)) {\n throw new InvalidArgumentException(\"\\$to must be an int. Given value: '{$from}'\");\n }\n $this->_from = $from;\n $this->_to = $to;\n }\n\n public function validate($data)\n {\n if (is_int($data) || (is_string($data) && ctype_digit($data))) {\n if ($data >= $this->_from && $data <= $this->_to) {\n return array();\n } else {\n return array(self::ERROR_INVALID_TYPE => $this->_messages[self::ERROR_INVALID_TYPE]);\n }\n } else {\n return array(self::ERROR_INVALID_TYPE => $this->_messages[self::ERROR_INVALID_TYPE]);\n }\n }\n\n}\n</code></pre>\n\n<p>This looks very laborious at first, but it gives you a certain degree of flexibility you didn't have before. Consider how you add a new validator now. You just create a new class completely unrelated to any of the other ones. (Technically it would implement Validator, and perhaps extend an abstract base class. What I mean though is that it doesn't <em>change</em> any of the other classes.)</p>\n\n<p>In this system, consumption of your code is much simpler too. How does someone that doesn't have write access to your git repository create their own validator? They just implement validator in their own namespace rather than in yours. (Oh, side note, you should probably be using namespaces.)</p>\n\n<p>For simplicity, you could make a \"composite\" Validator that just ties a bunch of validators together:</p>\n\n<pre><code>class EvenValidator implements Validator\n{\n //Imagine that this validates whether or not a number is even\n //(Yes, really weird example :p)\n}\n\nclass CompositeValidator implements Validator\n{\n\n $this->_validators = array();\n\n public function __construct(array $validators = array())\n {\n foreach ($validators as $validator) {\n $this->addValidator($validator);\n }\n }\n\n public function addValidator(Validator $validator)\n {\n $this->_validators[] = $validator;\n }\n\n public funtion validate($data)\n {\n $errors = array();\n foreach ($this->_validators as $validator) {\n $errors += $validator->validate($data);\n }\n return $errors;\n }\n\n}\n</code></pre>\n\n<p>You could then use it like:</p>\n\n<pre><code>$range = new RangeValidator(1, 100);\n$even = new EvenValidator();\n$comp = new CompositeValidator(array($range, $even));\n\n$comp->validate(5); //Returns an array of one message: 5 isn't odd\n$comp->validate(2); //Returns an empty array\n$comp->validate(222); //Returns an array of one message: 222 out of range\n$comp->validate(223); //Two messages: 223 out of range and odd\n</code></pre>\n\n<p>This is some pretty clumsy usage here. With more than 5 seconds of thought though, an interface could be designed that allowed for very robust functionality while leaving the code highly maintainable and extensible.</p>\n\n<p>You could even take it a step farther than a composite validator and make a \"Form\" class that has \"Element\"s which each have zero or more \"Validator\"s. (The approach take by Zend Framework, and I'm sure others).</p>\n\n<hr>\n\n<p>If you're familiar with any PHP frameworks, you might note that all of that above looks eerily familiar. In particular, that's a modified version of the <a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate.php\" rel=\"nofollow\">Zend_Validate</a> interface from the Zend Framework.</p>\n\n<p>I would suggest you pick a framework, go through the code, figure out how they designed things, and then ask yourself <em>why</em> they designed them that way: what the alternatives could have been and why they picked the path they chose. If you do look at frameworks for design, make sure you look at more than one. Though most of the major PHP frameworks/libraries are very well written overall, all of them have at least one area where they far from shine.</p>\n\n<p>Also, if you haven't already, read everything you can find about <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T00:39:08.677",
"Id": "386059",
"Score": "1",
"body": "Hi @corbin. It's 6 years later and I have an established career as a developer. I just wanted to reach out to you and thank you so much for this answer - it was invaluable and I learned so much; I think it was the turning point for me going from an amateur to reaching the point I'm at now. The effort you put into this helped me to build a livelihood and pushed me on the journey allowing me to support myself and my family. \n\nBest"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T04:46:09.223",
"Id": "386501",
"Score": "1",
"body": "@Prash I'm glad to hear you're doing well and got value out of this! I've wondered back on the time when I used to be really active on this site and wondered if I ever had any meaningful impact so it's so nice to hear I did. Honestly this was just me repeating information from people much smarter than myself (tech talks on YouTube, blogs, emulating Zend, etc), but I'm glad I could be the right person at the right time to help you. Thanks again for reaching out, and I hope you keep having a great, happy career! :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T03:00:21.603",
"Id": "18824",
"ParentId": "18814",
"Score": "7"
}
},
{
"body": "<p>Please <strong>don't</strong> use static methods as was suggested to you by max.haredoom. Static methods cause tight coupling in the code that calls them. See the following answers for reasons to avoid static: <a href=\"https://codereview.stackexchange.com/questions/7658/php-database-class/7660#7660\">Why</a>, oh <a href=\"https://codereview.stackexchange.com/questions/8059/authentication-class/8184#8184\">why</a> and <a href=\"https://codereview.stackexchange.com/questions/16367/php-simple-oop-class/16384#16384\">what to do</a>?</p>\n\n<p><strong>Properties</strong></p>\n\n<ul>\n<li><p>Remove the underscore from <code>$_errors</code>. See <a href=\"https://codereview.stackexchange.com/questions/14234/code-review-for-my-class/14241#14241\">this answer</a> for the reason that underscore should not be used for class properties.</p></li>\n<li><p><code>errorText</code> should be defined as a property of the class and its accessibility should be defined. </p></li>\n</ul>\n\n<p><strong>Constructor</strong></p>\n\n<ul>\n<li><code>require_once</code> in the constructor is a bad idea. This class cannot stand alone as a unit and it is completely broken with more than one object. Pass in the required information as arguments to the constructor.</li>\n</ul>\n\n<p><strong><code>rule</code> method</strong></p>\n\n<ul>\n<li>The name of this method does not explain what it is doing.</li>\n<li><p>Pass <code>$inputRules</code> as an array (and typehint for it). I can't see the reason for mashing together rules as a string when they are a list of rules. The array type represents lists very well, so I would use it and avoid having to explode the string on <code>|</code>.</p>\n\n<p><code>public function rule($value, $name, Array $inputRules)</code></p></li>\n<li><p>Your code for throwing an exception is repeated. Calculate the variables in the <code>if</code> / <code>else</code> and then check only once.</p></li>\n<li>The variables should be renamed to something more meaningful. <code>$rule</code> should be <code>$validationMethod</code> and <code>$call</code> should be <code>$validationArguments</code>.</li>\n<li>Use <code>is_callable</code> rather than <code>method_exists</code> it ensures that you will be able to call it (which is what you really want).</li>\n</ul>\n\n<p><strong><code>exec</code> method</strong></p>\n\n<ul>\n<li>This does not exec anything (thankfully).</li>\n<li>Perhaps it should be named validate, but I would have expected it to return true when there weren't any errors?</li>\n</ul>\n\n<p><strong>Design</strong></p>\n\n<p>I agree with Corbin. A validation interface is a great way to do this sort of thing. I think the key part of a validation class should be returning whether the data is valid or not. Your class does not make this a focus. Personally I like a simple interface that checks the validity and returns a boolean of whether the data is valid or not. The other thing that is needed is a method to return the errors from the last validation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T03:30:30.813",
"Id": "18825",
"ParentId": "18814",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18824",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T21:22:48.460",
"Id": "18814",
"Score": "7",
"Tags": [
"php",
"object-oriented",
"validation"
],
"Title": "PHP Validation Class"
}
|
18814
|
<p>This is a start on a multi-threaded game loop and I just wish to confirm my code is going in the correct direction, and if not, if there is any way it can be improved. I have good experience in game development and C++ in general, but limited experience when it comes to multi-threaded environments.</p>
<pre><code>#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <memory>
#include <chrono>
class Test
{
public:
Test()
{
std::cout << "Test starting" << std::endl;
start();
}
~Test()
{
stop();
std::cout << "Test finished" << std::endl;
}
inline void quit()
{
running = false;
}
private:
void start()
{
renderThread = std::unique_ptr<std::thread>(new std::thread(&Test::renderFunc, this));
updateThread = std::unique_ptr<std::thread>(new std::thread(&Test::updateFunc, this));
std::cout << "Threads Created" << std::endl;
running = true;
}
void stop()
{
renderThread->join();
updateThread->join();
std::cout << "Threads joined" << std::endl;
}
void updateFunc()
{
while(running)
{
mutex.lock();
std::cout << "update" << std::endl;
mutex.unlock();
}
}
void renderFunc()
{
while(running)
{
mutex.lock();
std::cout << "render" << std::endl;
mutex.unlock();
}
}
volatile bool running;
std::mutex mutex;
std::unique_ptr<std::thread> renderThread;
std::unique_ptr<std::thread> updateThread;
};
int main(int argc, char* argv[])
{
std::unique_ptr<Test> test = std::unique_ptr<Test>(new Test());
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::seconds Seconds;
Clock::time_point t0, t1;
Seconds seconds;
t0 = Clock::now();
do
{
t1 = Clock::now();
seconds = std::chrono::duration_cast<Seconds>(t1 - t0);
}while(seconds.count() <= 15);
test->quit();
return 0;
}
</code></pre>
<p>(The timer code is just there for testing the threaded code.)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T05:51:59.907",
"Id": "30023",
"Score": "0",
"body": "Maybe I'm misunderstanding what's going on in your code but what's the point in having multiple threads if you're just going to have them wait on the same mutex? You've essentially made it single threaded since the threads can only execute sequentially. Right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T08:54:37.113",
"Id": "30026",
"Score": "0",
"body": "@Jeff Mercardo You may very well be right, like I said I have little to no experience with multithreaded programs, but most examples I have seen only used one mutex, but that may be down to the fact most were only reader/writer programs. Having two mutexs would probably be more beneficial but how would that ensure thread safety?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T13:49:14.353",
"Id": "30041",
"Score": "0",
"body": "When I compile and run this I get an exception `terminate called after throwing an instance of 'std::system_error'\n what(): Operation not permitted`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T14:03:45.773",
"Id": "30042",
"Score": "0",
"body": "Compiles and runs using Visual Studio 2012 for me. What compiler are you using?"
}
] |
[
{
"body": "<p>Yes you have added enough explicit locks to make it safe (under normal situations).</p>\n\n<p>But it is not exception safe and not written in C++ style. You are writing the code as if it was Java (maybe). Which is causing all sorts of problems.</p>\n\n<p>Why do you need the start() and stop() functions? They provide no utility and they initialize members that should be initialized in the constructor. Also the threads are started before the object is fully initialized and thus you have a thread running in a function when the object is not initialized correctly (and thus will probably immediately exit).</p>\n\n<pre><code> void start()\n {\n // Soon as you create a thread \n // It starts running. So the next thing that is going to be\n // executed is the function `renderFunc()` which also depends\n // on member 'running' which has not been set.\n renderThread = std::unique_ptr<std::thread>(new std::thread(&Test::renderFunc, this));\n updateThread = std::unique_ptr<std::thread>(new std::thread(&Test::updateFunc, this));\n std::cout << \"Threads Created\" << std::endl;\n\n\n // You already have running threads that depend on this variable.\n // Yet this is the first time you even set it. Your code is already\n // broken.\n running = true;\n }\n</code></pre>\n\n<p>The next thing is the dynamic creation of the thread objects. Why. There is no need to dynamically create them. They should be automatic variables (ie non pointer members). The problem is that you need to be very careful with the initialization order.</p>\n\n<pre><code>class Test\n{\n volatile bool running;\n std::mutex mutex;\n std::thread renderThread;\n std::thread updateThread;\n public:\n Test()\n : running(false) // Make sure this is first.\n , renderThread(&Test::renderFunc, this)\n , updateThread(&Test::updateFunc, this)\n {\n std::cout << \"Test starting\" << std::endl;\n }\n ~Test()\n {\n std::cout << \"Test finished\" << std::endl;\n updateThread.join();\n renderThread.join();\n }\n inline void quit()\n {\n running = false;\n }\n</code></pre>\n\n<p>Next thing is your locking and unlocking of the mutex.</p>\n\n<pre><code> void updateFunc()\n {\n while(running)\n {\n mutex.lock();\n std::cout << \"update\" << std::endl;\n mutex.unlock();\n }\n }\n</code></pre>\n\n<p>This is not exception safe. Any situation were you do:</p>\n\n<pre><code>{\n lock(x);\n work();\n unlock(x);\n}\n</code></pre>\n\n<p>Where lock/unlock is a combination that must be called as a pair. Then you should be using RAII. This is where you have an object where lock() is called in the constructor and unlock() is called in the destructor. This also makes the code exception safe because the destructor will always be called <strong>even</strong> if their are exceptions.</p>\n\n<pre><code>{\n LockObject locker(x); // calls lock(x)\n work();\n} // destructor of locker will call unlock(x)\n</code></pre>\n\n<p>For this simple situation there is no need to create your own type. There is one defined in the standard scoped locked.</p>\n\n<pre><code> void updateFunc()\n {\n while(running)\n {\n std::lock_guard<std::mutex> locker(mutex);\n std::cout << \"update\" << std::endl;\n }\n }\n</code></pre>\n\n<p>Stop using dynamic allocation when you do not need it:</p>\n\n<pre><code> std::unique_ptr<Test> test = std::unique_ptr<Test>(new Test());\n\n // Just do this:\n Test test;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-30T01:52:59.177",
"Id": "307876",
"Score": "0",
"body": "While Loki Astari said that you don't need dynamic memory allocation, one efficiency thing to note is that `std::unique_ptr<Test> = std::unique_ptr<Test>(new Test());` is inefficient due to the code needing to make 2 allocations (`new Test()` creates a raw pointer that is passed to the `unique_ptr`'s constructor) and should be changed to `std::unique_ptr<Test> = std::make_unique<Test>();`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-30T02:00:56.333",
"Id": "307877",
"Score": "0",
"body": "@RafaelPlugge: I agree that it should be changed if you have C++17 (for consistency with `std::make_shared()`) but implying its more efficient is just wrong. Go look at an implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-14T17:55:13.323",
"Id": "19619",
"ParentId": "18817",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "19619",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T22:19:19.327",
"Id": "18817",
"Score": "8",
"Tags": [
"c++",
"multithreading",
"c++11"
],
"Title": "Multi-threaded game loop"
}
|
18817
|
<p>I wanted to see if I fully understood recursion so I attempted the <a href="http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/" rel="nofollow">FizzBuzz</a> challenge and applied recursion to it. </p>
<p>Did I do it correctly? Is this good code? Is there a more efficient way of doing it? How can I improve?</p>
<pre><code>//---------------------------------------------------------------------------------------
//[RecurFizzBuzz]
// FizzBuzz using recursion
//---------------------------------------------------------------------------------------
// Author : Jimmy
//---------------------------------------------------------------------------------------
public class RecurFizzBuzz {
// Specify a range to recurse, starts at int a, ends at int b
public static void recurse(int a, int b){
if(a <= b){
if(a % 3 == 0 && a % 5 == 0){
System.out.println("FizzBuzz");
} else if(a % 3 == 0){
System.out.println("Fizz");
} else if(a % 5 == 0){
System.out.println("Buzz");
} else {
System.out.println(a);
}
recurse(++a, b);
} else {
System.exit(0);
}
}
public static void main(String[]args) {
recurse(1, 100);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-23T10:38:50.863",
"Id": "236279",
"Score": "0",
"body": "Hello! You have received four answers. Would you please [accept](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) one of them? This gives you and the person with the accepted answer more reputation and gets this question off the list of unanswered questions. Thanks! :)"
}
] |
[
{
"body": "<ol>\n<li><p>It's worth to mention a disadvantage of recursion: the possibility of stack overflow. Calling <code>recurse(1, 6500)</code> throws a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/StackOverflowError.html\" rel=\"nofollow noreferrer\"><code>StackOverflowError</code></a> on my machine.</p></li>\n<li><p><del><code>a % 3 == 0 && a % 5 == 0</code> could be <code>a % 15 == 0</code>.</del> (Deleted, based on @QPaysTaxes's comment.)</p></li>\n<li><p><code>recurse</code> isn't a descriptive method name. <code>printFizzBuzz</code> would be better. </p></li>\n<li><p>Use longer variable names for the parameters which explain the purpose, for example: <code>lowerBound</code> and <code>upperBound</code>.\nThey're easier to read and maintain.</p>\n\n<blockquote>\n <p>Without proper names, we are constantly decoding and reconstructing the\n information that should be apparent from reading the code alone.</p>\n</blockquote>\n\n<p>(From <a href=\"https://codereview.stackexchange.com/a/15939/7076\">codesparkle's former answer</a>.)</p></li>\n<li><p><code>System.exit</code> isn't the nicest way to stop the recursion. You could use a simple <code>return</code> or omit the whole <code>else</code> block since the method returns anyway.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-09T17:37:12.210",
"Id": "209844",
"Score": "2",
"body": "\"*`a % 3 == 0 && a % 5 == 0` could be `a % 15 == 0`.*\" While they're equivalent, I tend to favor writing exactly what I mean, even if it's more verbose, because if I come back later (having forgotten what FizzBuzz is) I'll wonder why I check mod 3, mod 5, and mod 15, and it'll take me longer to realize that mod 15 is equivalent to both mod 3 and mod 5."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-10T12:29:55.310",
"Id": "210055",
"Score": "0",
"body": "@QPaysTaxes: Yeah, I agree, you're right, being explicit is helpful. I've modified the answer. Thanks for the feedback!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T23:18:46.197",
"Id": "18821",
"ParentId": "18820",
"Score": "10"
}
},
{
"body": "<p>Your recursion looks solid to me if you only wish to print the results. However, often recursion is used so that the recursive function actually has a return value. It's more useful that way when you can do whatever you want with the result, instead of only printing it. That printer-method is also difficult to test with unit tests. So try changing the method from returning <code>void</code> to, say, <code>String</code>, and then concatenating the current result with the results-to-come:</p>\n\n<pre><code>public static String recurse(int a, int b) {\n String result;\n if (a <= b) {\n final int mod3 = a % 3;\n if (mod3 == 0 && a % 5 == 0) {\n result = \"FizzBuzz\";\n } else if (mod3 == 0) {\n result = \"Fizz\";\n } else if (a % 5 == 0) {\n result = \"Buzz\";\n } else {\n result = String.valueOf(a);\n }\n return result + \"\\n\" + recurse(++a, b);\n } else {\n return \"\";\n }\n}\n</code></pre>\n\n<p>You'll notice that I also stored the result of <code>a % 3</code> and reused it in the second else-if block, because it makes the program run a tiny bit faster when it doesn't need to calculate the same value for the second time. According to my benchmarks, storing the result of <code>a % 5</code>, on the other hand, does not make the program run faster, as it's not needed as often as the result of <code>a % 3</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T23:55:40.263",
"Id": "30014",
"Score": "0",
"body": "@user1048606 No problem! Actually I suddenly thought of something else besides just reusing the `a % 3` result, namely that recursive functions often have return values. I have revised my answer, so please take another look at it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T00:00:09.107",
"Id": "30016",
"Score": "1",
"body": "+1, nice idea. You could store the result of the comparison too (`final boolean mod3 = ((a % 3) == 0)`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T00:08:01.210",
"Id": "30017",
"Score": "0",
"body": "One question, is result = String.valueOf(a); necessary? Couldn't you just use result = \"\"+upperRange;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T09:18:07.890",
"Id": "30027",
"Score": "0",
"body": "@user1048606 You could, but concatenating an empty string with an integer is a slower and internally much more complicated operation than using the `valueOf` method. See [Stack Overflow: String valueOf vs concatenation with empty string](http://stackoverflow.com/questions/7752347/string-valueof-vs-concatenation-with-empty-string)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T11:41:11.907",
"Id": "30033",
"Score": "3",
"body": "I'm not sure why you want to store the result of \"a % 3\", but please don't do it for performance reasons. The compiler (JIT) is perfectly capable of doing this optimizing for you. So don't make your code less readable for no performance benefit. In general, compilers are much better than you think they are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T14:06:20.697",
"Id": "30043",
"Score": "1",
"body": "@flamingpenguin I agree with your point, but the OP did ask if there was any more efficient way of doing the algorithm, and my little benchmarks indicated that storing the result would be slightly better for time efficiency. Also, I don't think my version loses any readability, but I guess that's a matter of personal preference. There are also different compilers, mind you, and they all cannot necessarily do all the same optimizations. Not that it really matters in this particular case, but anyway."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T23:40:59.897",
"Id": "18822",
"ParentId": "18820",
"Score": "3"
}
},
{
"body": "<p>Well, this is not that good example for recursion.<br>\nMy suggestion:</p>\n\n<pre><code>public static void printFizzBuzzFromToInclusive(final int start, final int end) {\n if (start <= end) {\n String toPrint = \"\";\n if (start % 3 == 0)\n toPrint += \"Fizz\";\n if (start % 5 == 0)\n toPrint += \"Buzz\";\n System.out.println(toPrint.length() > 0 ? toPrint : start);\n printFizzBuzzFromToInclusive(start + 1, end);\n }\n}\n\npublic static void main(final String[] args) {\n printFizzBuzzFromToInclusive(1, 100);\n}\n</code></pre>\n\n<p>Most of the changes are documented in the answer from palacsint.<br>\nAdditions: </p>\n\n<ul>\n<li>Do not use ++ for an argument. Try to keep your arguments final or unexpected things can happen (e.g. with ++ side effects if you use the variable somewhere after this line of code)</li>\n<li>For readability, I like the String concatenating approach. But this is only taste.</li>\n<li>You do not need a else cause, because the action (print) is always done inside the if case.</li>\n</ul>\n\n<p>For efficiency: There are some ways, but for the typical situation (job interview) you should aim for the solution with best readability (which is not necessarily the recursive way, but well).<br>\nIf someone asks you about it, always claim that readability is the first major goal (there are many reasons, main reason is the cost of support, which makes easily more than 90% of a project). Than, if you need speed, start profiling it and do the right thing.</p>\n\n<p>For this approach, you could talk about:</p>\n\n<ul>\n<li>Make it a while loop</li>\n<li>Use StringBuffer</li>\n<li>Use custom output channel</li>\n<li>Use int/byte array and set the corresponding results (0=number 1=fizz 2=buzz 3=fizzbuzz) (no modulo is needed anymore)</li>\n<li>Unroll the loop (then you do not need any modulo any more)</li>\n</ul>\n\n<p>Specific improvements depending on the exact requirements:</p>\n\n<ul>\n<li>Precalc the solutions up to a specific number</li>\n<li>Use multithreaded (either fork/join with an array or multiple threads with different steps)</li>\n<li>Talk with the customer to get rid of this thing</li>\n<li>Do it in some other language, where you can code for specific cpu architecture features</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T18:19:38.473",
"Id": "18947",
"ParentId": "18820",
"Score": "0"
}
},
{
"body": "<p>Recursive solutions are generally short in terms of lines of code. Yours appears to have too many lines at first glance.</p>\n\n<p>My expectation of a recursive method is that it will check for some end condition first otherwise it will call itself with a modification of the input parameter received.</p>\n\n<p><strong>Fibonacci example</strong></p>\n\n<pre><code> public long fib(int n) {\n if (n <= 1) {\n return n;\n }\n else {\n return fib(n-1) + fib(n-2);\n }\n}\n</code></pre>\n\n<p><strong>Suggestion #1</strong></p>\n\n<p>Having said that, your implementation is 'backwards' because you aren't checking for the end condition first - you are checking if you can keep going, <strong>if(a <= b)</strong>, and your end condition is at the bottom, <strong>System.exit(0)</strong>.</p>\n\n<p>Suggest swapping the order: check for end condition first so you can exit immediately otherwise keep processing.</p>\n\n<hr>\n\n<p><strong>Suggestion #2</strong></p>\n\n<p>Extract all of the code relating to printing into its own method. This will greatly simplify the recursive method and increase its readability.</p>\n\n<pre><code> private static void evaluate(int a) {\n if (a % 3 == 0 && a % 5 == 0){\n System.out.println(a + \" - FizzBuzz\");\n } else if(a % 3 == 0) {\n System.out.println(a + \" - Fizz\");\n } else if(a % 5 == 0) {\n System.out.println(a + \" - Buzz\");\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Suggestion #3</strong></p>\n\n<p>In the fizzbuzz problem, I am not a fan of a two parameter method - it seems like overkill. You can get away with just passing in one parameter - the number that you are currently processing. This is because one of the numbers (1 or 100, depending where you start from) never changes!</p>\n\n<p>Your method could be simplified to this:</p>\n\n<pre><code> public static int calculate(int value)\n</code></pre>\n\n<p>Feel free to keep the second parameter in the method signature if you think the bounds of the problem will change.</p>\n\n<hr>\n\n<p><strong>Putting it all together</strong></p>\n\n<p>Starting from 1 and going up to 100:</p>\n\n<pre><code>public static int calculate(int value) {\n if (value > 100) {\n return 0;\n } else {\n evaluate(value);\n return calculate(++value);\n }\n}\n</code></pre>\n\n<p>Starting from 100 and going down to 1:</p>\n\n<pre><code>public static int calculate(int value) {\n if (value== 0) {\n return 0;\n } else {\n evaluate(value);\n return calculate(--value);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T17:01:17.500",
"Id": "18964",
"ParentId": "18820",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T22:57:14.650",
"Id": "18820",
"Score": "7",
"Tags": [
"java",
"recursion",
"fizzbuzz"
],
"Title": "What do you think of my Recursive FizzBuzz?"
}
|
18820
|
<p>The Resource Pool is similar to the implementation of a semaphore. It takes the class type of the resource and number of resource pools associated with it as the constructor parameters. There is a small ambiguity here, when the <code>Resource</code> instance is created it uses reflection, but when we require the resource name a call to <code>getName()</code> from the <code>ResourceA</code> interface is sufficient. Each Resource has a corresponding resource pool entry in the <code>resource_pool_table Map</code>. The <code>poolAvailable</code> <code>Condition</code> variable will signal all waiting threads when a resource is released back into the pool. Correspondingly threads will wait on the Resource Pool lock condition until an object pool is available for the resource with the <code>resourceName</code>. </p>
<pre><code>package concurrency;
import java.util.Hashtable;
import java.util.Vector;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
interface ResourceA {
String getName();
}
interface ResourceExceptionHandler {
void handle(Exception exc);
}
class ResourceExceptionHandlerImpl implements ResourceExceptionHandler {
@Override
public void handle(Exception exc) {
}
}
class ResourceCreationException extends Exception {
}
public class ResourcePool<R extends ResourceA> {
private final Lock lock = new ReentrantLock();
private final Condition poolAvailable = lock.newCondition();
private int num_resource_pools;
private final Hashtable<String, Vector<R>> resource_pool_table = new Hashtable<String, Vector<R>>();
private final Class<R> resourceClass;
private final ResourceExceptionHandler resourceExceptionHandler = new ResourceExceptionHandlerImpl();
private R createResource(String str) {
R resource = null;
try {
resource = resourceClass.getDeclaredConstructor(String.class)
.newInstance(str);
if (resource == null)
throw new ResourceCreationException();
} catch (Exception e) {
resourceExceptionHandler.handle(e);
}
return resource;
}
public ResourcePool(Class<R> resourceClass, int num_resource_pools) {
lock.lock();
try {
this.resourceClass = resourceClass;
this.num_resource_pools = num_resource_pools;
} finally {
lock.unlock();
}
}
public R acquireResource(String resourceName) throws InterruptedException {
lock.lock();
try {
while (num_resource_pools <= 0)
poolAvailable.await();
--num_resource_pools;
Vector<R> pool = resource_pool_table.get(resourceName);
if (pool != null) {
int size = pool.size();
if (size > 0)
return pool.remove(size - 1);
}
return createResource(resourceName);
} finally {
lock.unlock();
}
}
public void releaseResource(R resource) {
lock.lock();
try {
String resourceName = resource.getName();
Vector<R> pool = resource_pool_table.get(resourceName);
if (pool == null) {
pool = new Vector<R>();
resource_pool_table.put(resourceName, pool);
}
pool.addElement(resource);
++num_resource_pools;
poolAvailable.signal();
} finally {
lock.unlock();
}
}
}
</code></pre>
<p><strong>JUnit tests</strong></p>
<pre><code> package concurrency;
import junit.framework.TestCase;
/*
* Test Resource
*/
class SomeResource implements ResourceA {
private String name;
public SomeResource(String name) {
super();
this.name = name;
}
@Override
public String getName() {
return name;
}
}
/*
* Test cases for Resource Pool
*/
public class ResourcePoolTest extends TestCase {
/*Checks the number of the resources in the Resource Table.
Resource is created only if needed.*/
public void testIsEmptyBeforeResourceAcquired() throws Exception {
ResourcePool<SomeResource> resPool = new ResourcePool<SomeResource>(
SomeResource.class, 5);
assertTrue(resPool.isEmpty("A"));
}
/* Checks if the number of resouces in the Resource Table is equal to the
* maximum number of resources declared at the Resouce Pool creation time.*/
public void testIsFull() throws Exception {
ResourcePool<SomeResource> resPool = new ResourcePool<SomeResource>(
SomeResource.class, 5);
SomeResource[] res = new SomeResource[5];
for (int i = 0; i <= 4; i++) {
res[i] = resPool.acquireResource("A");
}
for (int i = 0; i <= 4; i++) {
resPool.releaseResource(res[i]);
}
assertTrue(resPool.isFull("A"));
assertFalse(resPool.isEmpty("A"));
}
public void testAcquireBlocksWhenEmpty() throws Exception {
final ResourcePool<SomeResource> resPool = new ResourcePool<SomeResource>(
SomeResource.class, 0);
Thread resourceConsumer = new Thread() {
public void run() {
try {
SomeResource unused = resPool.acquireResource("A");
fail(); // error if control flow reaches this line
} catch (InterruptedException e) {
}
}
};
resourceConsumer.start();
Thread.sleep(1000); // waits for the resourceConsumer to block
resourceConsumer.interrupt();
resourceConsumer.join(1000); // resume after the resourceConsumer ends
assertFalse(resourceConsumer.isAlive());
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>No need to use synchronization in the constructor - at the moment of creation the object is not yet visible to any concurrent thread.</p></li>\n<li><p>Declare a field <code>Constructor<R> resourceConstructor</code> and in the constructor, initialize it with <code>resourceClass.getDeclaredConstructor(String.class)</code>. Thus the possible error when there is no such constructor is determined early, and saves time to extract the constructor later. Use it in the method <code>createResource()</code>:</p>\n\n<pre><code> resource = resourceConstructor.newInstance(str);\n</code></pre></li>\n<li><p>Rename <code>num_resource_pools</code> to <code>num_resources</code>, as it actually counts the overall number of resources, not number of pools.</p></li>\n<li><p>Create a couple of tests and run them every time the code is modified.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T07:44:02.880",
"Id": "19130",
"ParentId": "18826",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T06:29:47.777",
"Id": "18826",
"Score": "3",
"Tags": [
"java",
"locking"
],
"Title": "Resource Pool implementation with ReentrantLock and Condition"
}
|
18826
|
<p>This does the job, but is not especially elegant.</p>
<p>What is the preferred Pythonic idiom to my childish nests?</p>
<pre><code>def bytexor(a, b):
res = ""
for x, y in zip(a, b):
if (x == "1" and y == "0") or (y =="1" and x == "0"):
res += "1"
else:
res += "0"
return res
def get_all():
res = []
bit = ["0","1"]
for i in bit:
for j in bit:
for k in bit:
for l in bit:
res.append(i+j+k+l)
return res
if __name__=="__main__":
for k0 in get_all():
for k1 in get_all():
for k2 in get_all():
for k3 in get_all():
for k4 in get_all():
if bytexor(bytexor(k0, k2), k3) == "0011":
if bytexor(bytexor(k0, k2), k4) == "1010":
if bytexor(bytexor(bytexor(k0,k1),k2),k3) == "0110":
print k0, k1, k2, k3, k4
print bytexor(bytexor(bytexor(k0, k1),k2),k4)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T07:52:44.243",
"Id": "30024",
"Score": "0",
"body": "What is the code supposed to be doing? You're apparently trying to get all combinations of 4-bit binary numbers... but what are you trying to get from that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T10:31:20.897",
"Id": "30030",
"Score": "0",
"body": "@JeffMercado the problem was homework. There was an encryption algorithm given and some sample cyphertext - this code does an exhaustive search for keys that fit with the ciphertext, and encrypts a message using the same algorithm for each valid key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:00:45.253",
"Id": "30560",
"Score": "0",
"body": "I know this is not really what you were looking for, but you could leave the loops and optimize their runtime using *cython* or *numba*."
}
] |
[
{
"body": "<p>Depending on what you are ultimately doing, probably the neatest way is to use a standard module, <code>itertools</code>. Using <code>get_all</code> as an example:</p>\n\n<pre><code>import itertools\n\ndef get_all_bitpatterns():\n res = []\n bit = [ \"0\", \"1\" ]\n for z in itertools.product( bit, bit, bit, bit ):\n res.append( \"\".join(z) )\n return res\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T12:06:00.437",
"Id": "30034",
"Score": "2",
"body": "`product` takes a `repeat` argument, which would be useful here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T12:14:00.510",
"Id": "30036",
"Score": "2",
"body": "You could also use `bit = '01'` as string is iterable in Python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T13:30:34.943",
"Id": "30038",
"Score": "4",
"body": "`return [\"\".join(z) for z in itertools.product(bit, repeat=4)]`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T09:07:33.487",
"Id": "18829",
"ParentId": "18828",
"Score": "6"
}
},
{
"body": "<p>To convert an integer to a bit string with a particular number of digits, use <a href=\"http://docs.python.org/2/library/stdtypes.html#str.format\"><code>string.format</code></a> with the <a href=\"http://docs.python.org/2/library/string.html#format-specification-mini-language\"><code>b</code> format type</a>. For example:</p>\n\n<pre><code>>>> ['{0:04b}'.format(i) for i in range(16)]\n['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',\n '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']\n</code></pre>\n\n<p>But really it looks to me as though you don't want to be working with bit strings at all. You just want to be working with integers.</p>\n\n<p>So instead of <code>get_all</code>, just write <code>range(16)</code> and instead of <code>bytexor</code>, write <code>^</code>. Your entire program can be written like this:</p>\n\n<pre><code>from itertools import product\nfor a, b, c, d, e in product(range(16), repeat=5):\n if a ^ c ^ d == 3 and a ^ c ^ e == 10 and a ^ b ^ c ^ d == 6:\n print a, b, c, d, e, a ^ b ^ c ^ e\n</code></pre>\n\n<p>(This will also run a lot faster without all that fiddling about with strings.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T16:11:51.460",
"Id": "30057",
"Score": "0",
"body": "Thanks.. I can't believe it took me all that to write what could be done with five lines :s"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T12:02:08.500",
"Id": "18835",
"ParentId": "18828",
"Score": "29"
}
},
{
"body": "<p>This is <strong><em>just</em></strong> a little bit improved edition of '<strong>Glenn Rogers</strong>' answer ;)\nSimply work around <code>bit</code>, say <code>bit='abcd'</code> and number <code>n</code>.</p>\n\n<pre><code>from itertools import product\n\ndef AllBitPatterns(bit='01',n=2):\n out = []\n for z in product(bit,repeat=n*len(bit)): #thanks to a comment\n out.append(''.join(z))\n return out\n\nprint AllBitPatterns()\nprint AllBitPatterns(n=3)\nprint AllBitPatterns(bit='-~')\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>>>> \n['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']\n['000000', '000001', '000010', '000011', '000100', '000101', '000110', '000111', '001000', '001001', '001010', '001011', '001100', '001101', '001110', '001111', '010000', '010001', '010010', '010011', '010100', '010101', '010110', '010111', '011000', '011001', '011010', '011011', '011100', '011101', '011110', '011111', '100000', '100001', '100010', '100011', '100100', '100101', '100110', '100111', '101000', '101001', '101010', '101011', '101100', '101101', '101110', '101111', '110000', '110001', '110010', '110011', '110100', '110101', '110110', '110111', '111000', '111001', '111010', '111011', '111100', '111101', '111110', '111111']\n['----', '---~', '--~-', '--~~', '-~--', '-~-~', '-~~-', '-~~~', '~---', '~--~', '~-~-', '~-~~', '~~--', '~~-~', '~~~-', '~~~~']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-31T07:49:28.897",
"Id": "302048",
"Score": "0",
"body": "This answer is not mine, please remove it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T12:19:19.730",
"Id": "18836",
"ParentId": "18828",
"Score": "0"
}
},
{
"body": "<p><a href=\"https://stackoverflow.com/a/12403964/1273830\">I have answered awhile ago to this very type of question</a>. This is a very simple problem. You should not complicate it at all with iterators.</p>\n\n<p>The trick is that the bit pattern you are seeking for is actually the bits of numbers incremented by 1!</p>\n\n<p>Something like:</p>\n\n<pre><code>def get_all():\n res = []\n for i in range(16):\n # get the last four bits of binary form i which is an int\n bin(i) # a string like '0b0000' - strip '0b', 0 pad it to 4 length\n</code></pre>\n\n<p>I am not really the python guy, but I hope the idea is clear. Equivalent Java code:</p>\n\n<pre><code>int len = 3; // your number of for loops\nint num = (int)Math.pow(2, len);\nfor(int i=0; i<num; i++){\n // https://stackoverflow.com/a/4421438/1273830\n System.out.println(String.format(\"%\"+len+\"s\", Integer.toBinaryString(i)).replace(' ', '0'));\n}\n</code></pre>\n\n<p>Happy coding.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T13:18:26.130",
"Id": "18839",
"ParentId": "18828",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "18835",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T07:17:35.717",
"Id": "18828",
"Score": "14",
"Tags": [
"python",
"combinatorics",
"bitwise"
],
"Title": "Exhaustive search for encryption keys"
}
|
18828
|
<p>I'm looking for alternative ways to do it and in general parts that don't look write on this code.</p>
<pre><code>using System.Collections.Generic;
namespace Algorithms
{
public class SudokuPuzzleValidator
{
readonly int[,] _board;
public SudokuPuzzleValidator()
{
_board = new int[9,9];
}
public SudokuPuzzleValidator(int[,] board)
{
_board = board;
}
public bool Validate()
{
const int integersInGame = 9;
var rowSet = new HashSet<int>[integersInGame];
InitializeSet(integersInGame, rowSet);
var columnSet = new HashSet<int>[integersInGame];
InitializeSet(integersInGame, columnSet);
var subGridSet = new HashSet<int>[integersInGame];
InitializeSet(integersInGame, subGridSet);
for (var row = 0; row < integersInGame; row++)
{
for (var column = 0; column < integersInGame; column++)
{
var cval = _board[row, column];
if (rowSet[row].Contains(cval))
{
return false;
}
rowSet[row].Add(cval);
if (columnSet[column].Contains(cval))
{
return false;
}
columnSet[column].Add(cval);
var subGridNumber = FigureOutSubGrid(row, column);
if (subGridSet[subGridNumber].Contains(cval))
{
return false;
}
subGridSet[subGridNumber].Add(cval);
}
}
return true;
}
private static void InitializeSet(int integersInGame, HashSet<int>[] rowSet)
{
for (var i = 0; i < integersInGame; i++)
{
rowSet[i] = new HashSet<int>();
}
}
private static int FigureOutSubGrid(int row, int column)
{
return column/3 + row/3*3;
}
}
}
</code></pre>
<p>Link to my post:
<a href="http://alfredoalvarez.com/blog/?p=372" rel="nofollow">http://alfredoalvarez.com/blog/?p=372</a></p>
|
[] |
[
{
"body": "<p>This looks way overcomplicated. There are a lot of solutions on the web, for example:\n<a href=\"https://stackoverflow.com/questions/723213/sudoku-algorithm-in-c-sharp\">https://stackoverflow.com/questions/723213/sudoku-algorithm-in-c-sharp</a></p>\n\n<p>Regarding your code:</p>\n\n<ul>\n<li>You have hard-coded numbers everywhere </li>\n<li>Second ctor accepts arbitrary\narray and does not check parameter for validity. It can be null or of\nany size different from 9</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T11:48:15.947",
"Id": "18833",
"ParentId": "18831",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T10:40:59.563",
"Id": "18831",
"Score": "2",
"Tags": [
"c#"
],
"Title": "I could use a review of my sudoku validation"
}
|
18831
|
<p>I didn't make the math myself since I'm an idiot. I did however try to make it more versatile and usable for my multilingual page, which involves making it simple to use for advanced plural forms such as Polish and Russian.</p>
<p>Is this code any good to use on a website? or is it overkill?
I'm using the laravel framework, but this code should work everywhere.</p>
<p>I use it like this :</p>
<pre><code>Time::since($user->updated_at)
</code></pre>
<p>And here is the code:</p>
<pre><code>class Time
{
public static function since($timestamp) {
date_default_timezone_set('Europe/Rome');
$time = strtotime($timestamp);
$time = time() - $time;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
switch ($text)
{
case 'year':
return sprintf(ngettext(
"Last visit: %d year ago",
"Last visit: %d years ago",
$numberOfUnits), $numberOfUnits);
break;
case 'month':
return sprintf(ngettext(
"Last visit: %d month ago",
"Last visit: %d months ago",
$numberOfUnits), $numberOfUnits);
break;
case 'week':
return sprintf(ngettext(
"Last visit: %d week ago",
"Last visit: %d weeks ago",
$numberOfUnits), $numberOfUnits);
break;
case 'day':
return sprintf(ngettext(
"Last visit: %d day ago",
"Last visit: %d days ago",
$numberOfUnits), $numberOfUnits);
break;
case 'hour':
return sprintf(ngettext(
"Last visit: %d hour ago",
"Last visit: %d hours ago",
$numberOfUnits), $numberOfUnits);
break;
case 'minute':
return sprintf(ngettext(
"Last visit: %d minute ago",
"Last visit: %d minutes ago",
$numberOfUnits), $numberOfUnits);
break;
case 'second':
return sprintf(ngettext(
"Last visit: %d second ago",
"Last visit: %d seconds ago",
$numberOfUnits), $numberOfUnits);
break;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I've not coded any PHP in last five years but if I'm right the following is the same:</p>\n\n<pre><code>$tokens = array (\n 31536000 => array('msgid1' => \"Last visit: %d year ago\", \n 'msgid2' => \"Last visit: %d years ago\"),\n 2592000 => array('msgid1' => \"Last visit: %d month ago\", \n 'msgid2' => \"Last visit: %d months ago\"),\n 604800 => array('msgid1' => \"Last visit: %d week ago\", \n 'msgid2' => \"Last visit: %d weeks ago\"),\n 86400 => array('msgid1' => \"Last visit: %d day ago\", \n 'msgid2' => \"Last visit: %d days ago\"),\n 3600 => array('msgid1' => \"Last visit: %d hour ago\", \n 'msgid2' => \"Last visit: %d hours ago\"),\n 60 => array('msgid1' => \"Last visit: %d minute ago\", \n 'msgid2' => \"Last visit: %d minutes ago\"),\n 1 => array('msgid1' => \"Last visit: %d second ago\", \n 'msgid2' => \"Last visit: %d seconds ago\")\n);\n\nforeach ($tokens as $unit => $data) {\n if ($time < $unit) {\n continue;\n }\n $numberOfUnits = floor($time / $unit);\n\n $formatString = ngettext($data['msgid1'], $data['msgid2'], $numberOfUnits);\n return sprintf($formatString, $numberOfUnits);\n}\n</code></pre>\n\n<p>I think you should handle <code>0</code> too. Currently it prints nothing for this input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T12:00:35.310",
"Id": "30163",
"Score": "1",
"body": "Great idea, and it works. You just have to wrap the strings in _() and translate them in the .po file. Much better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T18:09:26.113",
"Id": "18849",
"ParentId": "18834",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T11:53:26.477",
"Id": "18834",
"Score": "2",
"Tags": [
"php",
"datetime",
"static"
],
"Title": "PHP: multilingual Time::since() static class"
}
|
18834
|
<p>How can I simplify this code?</p>
<pre><code> if (directory.Exists)
{
smallFileNames = directory.GetFiles("*.csv").Select(i => i.FullName).ToList();
if(smallFileNames.Count == 0)
smallFileNames = DivideIntoFiles(fileName);
}
else
smallFileNames = DivideIntoFiles(fileName);
</code></pre>
<p>I confused by identical lines...</p>
|
[] |
[
{
"body": "<p>...and you could simplify the second conditional by initializing <code>smallFileNames</code> :</p>\n\n<pre><code>List<string> smallFileNames = new List<string>\n\nif (directory.Exists)\n{\n smallFileNames = directory.GetFiles(\"*.csv\").Select(i => i.FullName).ToList();\n}\n\nif (smallFileNames.Count == 0)\n smallFileNames = DivideIntoFiles(fileName);\n</code></pre>\n\n<p>However, the whole logic seems unclear to me: there seems to be a hidden relation between <code>directory</code> and <code>fileName</code>. I would consider reviewing the surrounding code also.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T19:15:42.673",
"Id": "30068",
"Score": "0",
"body": "You could also do something like this: var smallFileNames = directory.Exists ? directory.GetFiles(\"*.csv\").Select(i => i.FullName).ToList() : new List<string>();"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:23:52.837",
"Id": "30073",
"Score": "0",
"body": "But it would always create a list, even when not needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T22:08:07.830",
"Id": "30078",
"Score": "2",
"body": "I'm a big fan of always creating a list. Takes out the if (list == null) checks every time you want to use it. An empty list is just that, empty, so an iteration or check if there are values will fail if there are any."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T06:40:57.973",
"Id": "30090",
"Score": "0",
"body": "`hidden relation between directory and fileName`\nThank you. I think it's good idea."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T19:00:17.697",
"Id": "18851",
"ParentId": "18837",
"Score": "1"
}
},
{
"body": "<p>Jumping in after the horse has bolted with a very minor different approach (using Any rather than Count and null). </p>\n\n<pre><code>IEnumerable<string> GetSmallFileNames(Directory directory, string fileName, string filter) \n{\n var smallFileNames = new List<string>();\n\n if (directory.Exists)\n {\n smallFileNames = directory.GetFiles(filter).Select(i => i.FullName); \n }\n\n return smallFileNames.Any() ? smallFileNames : DivideIntoFiles(fileName);\n}\n</code></pre>\n\n<p>Then used such as</p>\n\n<pre><code>IEnumerable<string> smallFileNames = GetSmallFileNames(directory, fileName, \"*.csv\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T14:52:20.103",
"Id": "30199",
"Score": "0",
"body": "Isn't `Count` faster than `Any()`? Maybe that wasn't your point though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T18:39:49.200",
"Id": "30221",
"Score": "0",
"body": "Yes it probably is. But I would think the speed is actually so small that in this case it's irrelevant. Also people often mix .Count with .Count() which are subtly different. So .Any() just removes that confusion...."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T21:11:41.540",
"Id": "18859",
"ParentId": "18837",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T12:51:01.013",
"Id": "18837",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Simplify 'if' condition"
}
|
18837
|
<p>I'm working with lots of code that looks like this:</p>
<pre><code>-(void)switchToPercent{
int tmp;
tmp = (statisticsObject.idag3_orig != 0) ? statisticsObject.idag3_orig : [self compareValue:statisticsObject.idag2 withValue:statisticsObject.idag3];
statisticsView.idag3.text = [NSString stringWithFormat:@"%i", tmp];
tmp = (statisticsObject.igar3_orig != 0) ? statisticsObject.igar3_orig : [self compareValue:statisticsObject.igar2 withValue:statisticsObject.igar3];
statisticsView.igar3.text = [NSString stringWithFormat:@"%i", tmp];
tmp = (statisticsObject.veckan3_orig != 0) ? statisticsObject.veckan3_orig : [self compareValue:statisticsObject.veckan2 withValue:statisticsObject.veckan3];
statisticsView.veckan3.text = [NSString stringWithFormat:@"%i", tmp];
tmp = (statisticsObject.manaden3_orig != 0) ? statisticsObject.manaden3_orig : [self compareValue:statisticsObject.manaden2 withValue:statisticsObject.manaden3];
statisticsView.manaden3.text = [NSString stringWithFormat:@"%i", tmp];
tmp = (statisticsObject.kvartalet3_orig != 0) ? statisticsObject.kvartalet3_orig : [self compareValue:statisticsObject.kvartalet2 withValue:statisticsObject.kvartalet3];
statisticsView.kvartalet3.text = [NSString stringWithFormat:@"%i", tmp];
tmp = (statisticsObject.aret3_orig != 0) ? statisticsObject.aret3_orig : [self compareValue:statisticsObject.aret2 withValue:statisticsObject.aret3];
statisticsView.aret3.text = [NSString stringWithFormat:@"%i", tmp];
tmp = (statisticsObject.r123_orig != 0) ? statisticsObject.r123_orig : [self compareValue:statisticsObject.r122 withValue:statisticsObject.r123];
statisticsView.r123.text = [NSString stringWithFormat:@"%i", tmp];
[self formatText:statisticsView.idag3];
[self formatText:statisticsView.igar3];
[self formatText:statisticsView.veckan3];
[self formatText:statisticsView.manaden3];
[self formatText:statisticsView.kvartalet3];
[self formatText:statisticsView.aret3];
[self formatText:statisticsView.r123];
}
</code></pre>
<p>I'm trying to remove the repetition as much as I can. Originally, the business logic was repeated once for each of the properties shown, but I've moved that into a method named <code>compareValue:withValue:</code>. I've also introduced the conditional operator to remove larger <code>ifelse</code> blocks. I imagine the next step is to reduce the seven chunks of code into one, and iterate over a list of keywords, but how?</p>
|
[] |
[
{
"body": "<p>I can't really judge if it's a good idea, but one way could be creating an NSArray (or NSSet) containing NSDictionaries with the keypaths that should be compared, and then enumerating through that. Something like this:</p>\n\n<pre><code>#define keyOriginal = \"original\"\n#define keyComparisonItem1 = \"comparisonItem1\"\n#define keyComparisonItem2 = \"comparisonItem2\"\n\n NSMutableArray * evaluations = [NSMutableArray array];\n\n [evaluations addObject:@{keyOriginal : @\"idag3_orig\", keyComparisonItem1 : @\"idag2\", keyComparisonItem2 : @\"idag3\"}];\n [evaluations addObject:@{keyOriginal : @\"igar3_orig\", keyComparisonItem1 : @\"igar2\", keyComparisonItem2 : @\"igar3\"}];\n // and so on...\n\n for (NSDictionary * evaluation in evaluations) {\n\n if ([statisticsObject valueForKey:keyOriginal] != 0) {\n tmp = (int)[statisticsObject valueForKey:keyOriginal];\n } else {\n\n tmp = [self compareValue:[statisticsObject valueForKey:keyComparisonItem1]\n withValue:[statisticsObject valueForKey:keyComparisonItem2]];\n }\n\n [self formatText:[statisticsView valueForKey:keyOriginal]];\n\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T16:13:51.903",
"Id": "19943",
"ParentId": "18841",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T14:15:59.903",
"Id": "18841",
"Score": "2",
"Tags": [
"objective-c"
],
"Title": "Iterating over object properties"
}
|
18841
|
<p>here is my implementation to find the lowest common ancestor in a binary tree. It works but i would like to know if i could have done anything better or if i have missed an specific case. would really appreciate ur feedback:</p>
<pre><code>//The function findOrQueue is to enqueue all elements upto target node to a queue
public void findOrQueue(Node target, Node top, LLQueue q) {
int cmp = target.getData().compareTo(top.getData());
if(cmp == 0) {
q.enqueue(top);
return ;
}
else if (cmp < 0) {
q.enqueue(top);
findOrQueue(target, top.getLeftChild(),q);
}
else {
q.enqueue(top);
findOrQueue(target, top.getRightChild(),q);
}
}
public Node LCA(Node n1, Node n2) throws QueueEmptyException {
LLQueue q1 = new LLQueue();
LLQueue q2 = new LLQueue();
findOrQueue(n1,getRoot(),q1);
findOrQueue(n2,getRoot(),q2);
Node t = null;
while (!q1.isEmpty() && !q2.isEmpty()) {
Node t1 = (Node)q1.dequeue();
Node t2 = (Node)q2.dequeue();
if(t1.getData() != t2.getData()) {
return t;
}
else t = t1;
}
if(q1.isEmpty() && q2.isEmpty())
return null;
else
return t;
}
</code></pre>
|
[] |
[
{
"body": "<p>I would simplify the <code>findOrQueue</code> function to make sure it stays <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a></p>\n\n<pre><code>public void findOrQueue(Node target, Node top, LLQueue q) {\n int cmp = target.getData().compareTo(top.getData()); \n q.enqueue(top);\n if(cmp != 0) {\n Node nextTop = (cmp < 0) ? top.getLeftChild() : top.getRightChild();\n findOrQueue(target, nextTop, q);\n }\n}\n</code></pre>\n\n<p>Since it's used recursively, it might not be a horrible idea to keep the exit condition explicit for readability:</p>\n\n<pre><code>if(cmp == 0) {\n return; // Exit condition\n} else {\n // ... as above\n}\n</code></pre>\n\n<p>Edit: The return condition can also be made more direct:</p>\n\n<pre><code>boolean bothEmpty = q1.isEmpty() && q2.isEmpty();\nreturn (!bothEmpty) ? t : null;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:34:22.067",
"Id": "30074",
"Score": "0",
"body": "ok thnx!! but the solution looks good?? how can i extend it to binary trees and not just binary search trees??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T08:46:45.653",
"Id": "30093",
"Score": "0",
"body": "You can directly write : `findOrQueue(target, ((cmp < 0) ? top.getLeftChild() : top.getRightChild()), q);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:17:25.253",
"Id": "30437",
"Score": "0",
"body": "I actually had that originally, but thought it might be more clear in this context to make it more than a one-liner."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:31:29.987",
"Id": "18857",
"ParentId": "18845",
"Score": "1"
}
},
{
"body": "<pre><code>public Node LCA(Node top, Node n1, Node n2) {\n if (top.getData() < n1.getData() && top.getData() < n2.getData()) {\n return LCA(top.getLeftChild(), n1, n2);\n } \n\n if (top.getData() > n1.getData() && top.getData() > n2.getData()) {\n return LCA(top.getRightChild(), n1, n2);\n }\n\n return top;\n}\n</code></pre>\n\n<p>Frankly, I don't understand what you are trying to do with LLQ's.</p>\n\n<p>For general trees the answer is not trivial, see <a href=\"http://en.wikipedia.org/wiki/Lowest_common_ancestor\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Lowest_common_ancestor</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-13T09:48:41.497",
"Id": "19571",
"ParentId": "18845",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T01:55:26.470",
"Id": "18845",
"Score": "3",
"Tags": [
"java"
],
"Title": "Lowest Common Ancestor"
}
|
18845
|
<p>I have written a JavaScript API that loads and houses libraries of code to do all sorts of things on websites.</p>
<p>Effectively, this is (will be) the base JavaScript for all the websites I build.</p>
<p>The aim of this API is to load the required libraries (<code>SM.load()</code>) needed for a particular page, and add them to the library as a plugin (<code>SM.run()</code>).</p>
<p>You may be surprised as to how I have written this library, just to explain in brief. I have aliased the jQuery selector, so that if you run:</p>
<pre><code>SM('#test').foo()
</code></pre>
<p>It will retrieve <code>#test</code> using the jQuery constructor function and then chain the result through to the <code>foo()</code> function. However, you can also run functions like this:</p>
<pre><code>SM.bar()
</code></pre>
<p>Effectively this just mimics the way you can do this in jQuery:</p>
<pre><code>$('#test').show()
$.ajax(options)
</code></pre>
<hr>
<pre><code>/**
* Sine Macula Javascript API
* The Sine Macula API contains all base functions for the Sine Macula
* Javascript Library
* @name class.sinemacula.js
* @author Ben Carey
* @version 1.0
* @date 20/11/2012
* @copyright (c) 2012 Sine Macula Limited (sinemaculammviii.com)
*/
(function(global, $){
// Enable strict mode
"use strict";
// Set the global variables for Sine Macula
var oldSM, SM;
// Make sure jQuery has loaded
if(typeof $ !== "function"){
throw "jQuery must be loaded";
}
/**
* Sine Macula Object
* The main Sine Macula library
*
* @param string The element to be selected
*/
SM = global.SM = global.SineMacula = SineMacula;
function SineMacula(selector){
// Construct and return an instance of the
// Sine Macula object
return new _initialize(selector);
}
/**
* Sine Macula Constructor
* Alias of the jQuery Selector
*
* @param string The element to be selected
*/
function _initialize(selector){
// Retrieve the elements matching the selector
// and make it available to all the Sine Macula
// methods
this.elements = $(selector);
}
// So that plugins can add to _initialize.prototype, make it available
// as a property of SineMacula: SineMacula.fn (aka SM.fn)
SM.fn = _initialize.prototype;
/**
* Sine Macula Run
* Makes it easy to write plugins for the Sine Macula library
*
* @param function callback
*/
SM.run = run;
function run(callback){
// Call the function with the Sine Macula
// and jQuery objects
callback(SM, $);
}
/**
* Sine Macula Load
* Load the Sine Macula Libraries and Plugins
* into the current document
*
* The options:
* - package: the package of libraries to load
* - packageURL: a remote source to load the package details from
* - libraries: any additional libraries to load
*
* @param object options The options for the Sine Macula load
*/
SM.load = load;
function load(options){
var url,query,script;
// Set the defaults for the loader
var options = $.extend({
package: 'none', // Do not load any packages by default
packageURL: false, // Do not retrieve the package details from a URL by default
libraries: [] // Do not load any libraries by default
},options);
// Build the query based on the parameters supplied
if(options.packageURL){
// Build the query to allow for a remote
// package definition
query = '?packageURL='+encodeURIComponent(options.packageURL);
}else if(options.package=='none'){
// If no package has been supplied then just
// provide libraries to load
query = '?libraries='+encodeURIComponent(options.libraries.join());
}else{
// If a package has been supplied then
// request it, and any additional libraries
query = encodeURIComponent(options.package)+'/?libraries='+encodeURIComponent(options.libraries.join());
}
// Complete the url by appending the query
url = '//libraries.sinemaculammviii.com/'+query;
// Append the script tag to the end of the document
script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
$('head')[0].appendChild(script);
}
/**
* IndexOf
* A fix to allow the call of the indexOf function
* in Internet Explorer
*/
if(!Array.prototype.indexOf){
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
})(this, this.jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:54:38.410",
"Id": "30052",
"Score": "1",
"body": "SM? [Really](http://en.wikipedia.org/wiki/Sadomasochism)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:56:16.390",
"Id": "30053",
"Score": "0",
"body": "[related](http://www.urbandictionary.com/define.php?term=SM)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:56:27.540",
"Id": "30054",
"Score": "0",
"body": "@FlorianMargaine Hahahaha, oh dear!! Didnt think of that!! It stands for Sine Macula. I may change that now!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T16:09:39.530",
"Id": "30056",
"Score": "0",
"body": "@BenCarey And btw fix your `indexOf` shim. Right now, it shims all the time even when the method exists. See the [official shim](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T16:15:21.573",
"Id": "30058",
"Score": "0",
"body": "@FlorianMargaine Thank you very much, have amended my script :-)"
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>I like <code>use strict</code> in an IIFE</li>\n<li>However, the second <code>use strict</code> in <code>indexOf</code> is overkill</li>\n<li>You are not using the variable <code>oldSM</code></li>\n<li>Lots of comments are good as well</li>\n<li><p>The below code is prepending really, and the hostname should be called out in separate variable or even better be derived from <code>window.location</code></p>\n\n<pre><code>// Complete the url by appending the query\nurl = '//libraries.sinemaculammviii.com/'+query; \n</code></pre></li>\n<li><p>From a design perspective, I am not sure what you are providing with your script, except for a shell over jQuery. jQuery even has <code>jQuery.getScript()</code> which could replace <br></p>\n\n<pre><code>// Append the script tag to the end of the document\nscript = document.createElement('script');\nscript.type = 'text/javascript';\nscript.src = url;\n$('head')[0].appendChild(script); \n</code></pre>\n\n<p>it also has <code>jQuery.inArray</code> which you could use instead of your <code>indexOf</code> shim.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T19:24:19.700",
"Id": "40876",
"ParentId": "18846",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40876",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T15:46:12.907",
"Id": "18846",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"api"
],
"Title": "JavaScript API that loads and houses libraries of code"
}
|
18846
|
<p>Please help me improve this Google Apps Script for reminding the user to contact people they haven't contacted in a while:</p>
<p><strong>Purpose:</strong></p>
<ul>
<li>Creates tasks for you to contact people you haven't talked to for a while.</li>
<li>Adds a 'Touch Frequency (Days)' field to contacts - make a schedule per Contact</li>
<li>New emails to/from a contact with make Task go away automatically</li>
<li>"Complete" the task manually to signify a touch over a different channel (Phone, Chat, In-person)</li>
</ul>
<p><strong>Known issues:</strong></p>
<ol>
<li>'Touch Frequency (Days)' field not appearing in Google Contacts interface</li>
<li>Sporadic execution errors "Data Storage Error", "Backend Error" - not sure why. But try it again and it works.</li>
<li>Tasks are duplicated with each run - major issue - should we also search by task title as a backup if the task is missing (in case the DB was wiped out)?</li>
<li>Slower and more reads than necessary, perhaps?</li>
</ol>
<p><a href="http://code.google.com/p/touchminder/source/browse/touchMinder.js" rel="nofollow">Code</a></p>
<pre><code>// http://code.google.com/p/touchminder
//
// Run TouchMinder() on a scheduled trigger as a Google Apps Script.
// You'll need to add an API Key for your Tasks Service integration (Easy: https://developers.google.com/apps-script/service_tasks, https://developers.google.com/console/help/)
//
// Creates tasks for you to contact people you haven't talked to for a while.
// Adds a 'Touch Frequency (Days)' field to contacts - make a schedule per Contact
// New emails to/from a contact with make Task go away automatically
// "Complete" the task manually to signify a touch over a different channel (Phone, Chat, In-person)
//
// Known issues:
// 'Touch Frequency (Days)' field not appearing
// Currently, this doesn't fully work. Sporadic execution errors "Data Storage Error", "Backend Error" - not sure why. But try it again and it works.
// Tasks are duplicated with each run - major issue
// Slower and more reads than necessary, perhaps?
function TouchMinder() {
Logger.log('Starting TouchMinder');
Logger.log('');
var db = ScriptDb.getMyDb(); // Get the db
// Cursor to [] of contactTouches ({ table: 'ContactTouches', contactId: 0, lastTouch: 0, taskId: 0 })
var contactTouches = [];
var queryResults = db.query({ table: 'ContactTouches' });
while(queryResults.hasNext()) { contactTouches.push(queryResults.next()); }
// Who am I?
var currentUserEmailAddress = Session.getActiveUser().getEmail();
var myId = ContactsApp.getContact(currentUserEmailAddress).getId();
var allCurrentUserEmailAddresses = ContactsApp
.getContact(currentUserEmailAddress)
.getEmails()
.map(function (ea) { return ea.getAddress().trim().toLowerCase(); });
// Cursor to [] of contactTouches ({ table: 'ContactTouches', ownerContactId: myId, contactId: contactId, lastTouch: number, taskId: taskId }) // Cannot store Date, so store milliseconds instead
// ownerContactId because I believe the scriptDb is shared by the domain in Google Apps accounts. If not, no real harm, right?.
var contactTouches = [];
var queryResults = db.query({ table: 'ContactTouches', ownerContactId: myId });
while(queryResults.hasNext()) { contactTouches.push(queryResults.next()); }
Logger.log('currentUserEmailAddresses: ' + allCurrentUserEmailAddresses.join(', '));
// load all contacts
var trackedContacts = loadContacts(contactTouches, myId);
var maxDays = Math.max.apply( Math, trackedContacts.map(function (c) { return c.frequency; }) ) || 0; // What's the furthest back we should search?
var earliestDate = new Date(); earliestDate.setDate(earliestDate.getDate() - maxDays);
Logger.log('Found ' + trackedContacts.length + ' trackedContacts');
Logger.log('');
var tasklistId = getTouchMinderTaskList();
var processedTasks = processCompletedTasksGetRemaining(tasklistId, db); // { completed: number, remaining: taskId[] }
Logger.log('Touched ' + processedTasks.completed + ' contacts from completed tasks.');
Logger.log('');
Logger.log('Searching back as far as ' + earliestDate.toLocaleString());
Logger.log('');
var messages = new IterateMessages('in:anywhere -in:drafts'); // Iterate through ALL emails, sent & received.
while (messages.moveNext()) {
try {
var message = messages.current.message;
var thread = messages.current.thread;
if (thread.getLastMessageDate() < earliestDate) break;
var sender = extractRawEmailAddresses(message.getFrom())[0];
var recipients = extractRawEmailAddresses(message.getTo() + ',' + message.getCc());
var date = message.getDate().getTime(); // number!
if (allCurrentUserEmailAddresses.filter(function (myEmail) { return sender === myEmail; }).length !== 0) { // Sent email
for (var r in recipients) {
var recipient = recipients[r];
var matchingContacts = trackedContacts.filter(function (tc) { // find matching contacts where the lastTouch is older than this date AND there's an email match
return tc.contactTouch.lastTouch < date &&
0 < tc.allEmails.filter(function (ea) { return ea === recipient }).length; });
for (var mc in matchingContacts) // update the lastTouch
{
matchingContacts[mc].contactTouch.lastTouch = date;
}
}
} else { // Received email
var matchingContacts = trackedContacts.filter(function (tc) { // find matching contacts where the lastTouch is older than this date AND there's an email match
return tc.contactTouch.lastTouch < date &&
0 < tc.allEmails.filter(function (ea) { return ea === sender }).length; });
for (var mc in matchingContacts) // update the lastTouch
{
matchingContacts[mc].contactTouch.lastTouch = date;
}
}
} catch (ex) {
Logger.log('Error ' + ex + ' ' + message.getSubject());
throw ex;
}
}
Logger.log('Finished scanning');
// For which tasks to remove
var allRecentlyEmailed = trackedContacts.filter(function (tc) {
return tc.cutoffDate < tc.contactTouch.lastTouch && // lastTouch is after the cutoff for this contact
tc.contactTouch.taskId != null; // and the taskId is not null
});
// For which tasks to add
var allNewlyExpired = trackedContacts.filter(function (tc) {
return tc.contactTouch.lastTouch <= tc.cutoffDate && // lastTouch is before the cutoff for this contact
(tc.contactTouch.taskId == null || // and there is no taskId
processedTasks.remaining.filter(function (r) { return r === tc.contactTouch.taskId }).length === 0); // or the task is missing
});
for (var re in allRecentlyEmailed)
{
// delete the task
var recentlyEmailed = allRecentlyEmailed[re];
var task = processedTasks.remaining.filter(function (r) { return r.getId() === recentlyEmailed.contactTouch.taskId; })[0];
if (task)
{
task.setDeleted(true);
Tasks.Tasks.update(task, tasklistId, recentlyEmailed.contactTouch.taskId);
}
recentlyEmailed.contactTouch.taskId = null;
}
Logger.log('Deleted ' + allRecentlyEmailed.length + ' tasks');
for (var ne in allNewlyExpired)
{
// add a task
var newlyExpired = allNewlyExpired[ne];
var title = 'Check in on ' + newlyExpired.contact.getFullName();
Logger.log('Adding task "' + title + '"');
var newTask = Tasks.newTask().setTitle(title);
newlyExpired.contactTouch.taskId = Tasks.Tasks.insert(newTask, tasklistId).getId();
}
Logger.log('Added ' + allNewlyExpired.length + ' tasks');
db.saveBatch(contactTouches, false);
};
// From and To lines in email are each presented as a raw string - we need to extract just the email address for matching to Contact email addresses.
// This takes a string of comma or semi-colon delimited email addresses (including optionally quotes full-names preceeding brackets addresses, or just naked email addresses)
// and returns an array of normalized addressed.
function extractRawEmailAddresses(addressLine)
{
var reEmail = /\s*(?:([^"<,;]+)|(?:(?:(?:(?:"(?:""|[^"<,;])*")|[^"<,;]*)?\s*<([^"<>,;]*)>)))(?:$|,|;)/gi;
var extracted = [];
var captures;
while (captures = reEmail.exec(addressLine))
{
extracted.push((captures[2] || captures[1]).trim().toLowerCase());
}
return extracted;
}
// Ensure that the TaskList exists and return the ID.
function getTouchMinderTaskList()
{
var title = "TouchMinders";
var allLists = Tasks.Tasklists.list().getItems();
var id;
for (var i in allLists) {
if (title == allLists[i].getTitle()) {
return allLists[i].getId();
}
}
var newTaskList = Tasks.newTaskList();
newTaskList.setTitle(title);
return Tasks.Tasklists.insert(newTaskList).getId();
}
// Look for manually Completed Tasks and interpret that to mean that the Contact was touched by the user through another channel (Phone, Chat, in-person)
function processCompletedTasksGetRemaining(tasklistId, contactTouches, myId)
{
var tasks = Tasks.Tasks.list(tasklistId).getItems();
var completed = 0;
var remaining = [];
for (var t in tasks) {
var task = tasks[t];
var taskId = task.getId();
var completion = task.getCompleted();
if (completion)
{
var found = contactTouches.filter(function (ct) { return ct.taskId == taskId })[0];
if (found) {
var lastTouch = new Date(completion.replace(/\-/g,'\/').replace(/[T|Z]/g,' ')).getTime();
found.lastTouch = found.lastTouch < lastTouch ? lastTouch : found.lastTouch;
found.taskId = null;
task.setDeleted(true);
Tasks.Tasks.update(task, tasklistId, taskId);
completed++;
}
else
{
remaining.push(taskId);
}
}
}
return { completed: completed, remaining: remaining };
}
// Get all contacts from ContactsApp Google Service and pair them with cached data found in contactTouches ScriptDB
function loadContacts(contactTouches, myId)
{
// My Contacts only - perhaps later this is configurable?
return ContactsApp.getContactGroup("System Group: My Contacts").getContacts()
.map(function (c) {
var touchFrequency = c.getCustomFields('Touch Frequency (Days)'); // Get the Contact's preferred Touch Frequency in Days as configured in the Google Contacts App custom field
if (!touchFrequency) { // if there is no such setting, create one and set it to a default of 30 days
touchFrequency = '30';
c.addCustomField('Touch Frequency (Days)', touchFrequency);
}
var contactId = c.getId();
var contactTouch = contactTouches.filter(function (ct) { return ct.contactId === contactId; })[0]; // Find the matching contactTouch
if (!contactTouch) // if it doesn't exist, add it to the array (it will be saved to the ScriptDB at the end of the entire script execution)
{
contactTouch = { table: 'ContactTouches', ownerContactId: myId, contactId: contactId, lastTouch: 0, taskId: null };
contactTouches.push(contactTouch);
}
var frequency = parseInt(touchFrequency, 10) || 30; // Attempt to parse the touchFrequency string as an int or default to 30 days
var cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - frequency); // Calculate the earliest date to search for touches with this contact
return {
frequency: frequency,
cutoffDate: cutoffDate.getTime(),
contact: c,
contactId: contactId,
primaryEmail: c.getPrimaryEmail,
allEmails: c.getEmails().map(function (ea) { return ea.getAddress().trim().toLowerCase(); }),
contactTouch: contactTouch
};
});
}
/*
// IterateMessages created with the help of the Tracuer project from this source:
function* IterateMessages(searchCriteria, backwardFromDate) {
var oldestYetObserved = (backwardFromDate || new Date()).getTime()/1000 | 0;
while(true)
{
// Older seems non-inclusive, which is desirable for this purpose, otherwise we'd loop infinitely on any single result
var batchSearchCriteria = searchCriteria + ' older:' + oldestYetObserved.toString();
var threads = GmailApp.search(batchSearchCriteria, 0, 10);
if (threads.length === 0) break;
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
yield messages[j];
}
}
oldestYetObserved = threads[threads.length - 1].getLastMessageDate().getTime()/1000 | 0;
}
};
for (var message in IterateMessages('in:anywhere'))
{
console.log(message);
}
*/
// Lazily iterates through email messages.
// Optionally pass any search criteria other than 'older:' for searchCriteria ex: 'in:inbox from:(john.doe@internet.com) subject:(Lunch?) has:attachment'.
// Optionally pass a Date from which to iterate backwards in time (by each Thread's most recent email date)
// Refer to the commented ECMAScript Harmony version above for basic details
function IterateMessages(searchCriteria, backwardFromDate) {
var $that = this;
var $arguments = arguments;
var $state = 20;
var $storedException;
var $finallyFallThrough;
var batchSearchCriteria;
var i;
var j;
var messages;
var threadMessages;
var oldestYetObserved;
var threads;
var $result = {moveNext: function($yieldSent) {
while (true) try {
switch ($state) {
case 20:
oldestYetObserved = (backwardFromDate || new Date()).getTime() / 1000 | 0;
$state = 21;
break;
case 21:
if (true) {
$state = 10;
break;
} else {
$state = 19;
break;
}
case 10:
batchSearchCriteria = (searchCriteria || '') + ' older:' + oldestYetObserved.toString();
$state = 11;
break;
case 11:
threads = GmailApp.search(batchSearchCriteria, 0, 50);
messages = GmailApp.getMessagesForThreads(threads);
$state = 13;
break;
case 13:
if (messages.length === 0) {
$state = 14;
break;
} else {
$state = 15;
break;
}
case 14:
$state = 19;
break;
case 15:
i = 0;
$state = 7;
break;
case 7:
if (i < messages.length) {
$state = 5;
break;
} else {
$state = 9;
break;
}
case 4:
i++;
$state = 7;
break;
case 5:
threadMessages = messages[i];
$state = 6;
break;
case 6:
j = 0;
$state = 2;
break;
case 2:
if (j < threadMessages.length) {
$state = 0;
break;
} else {
$state = 4;
break;
}
case 1:
j++;
$state = 2;
break;
case 0:
$result.current = { thread: threads[i], message: threadMessages[j] };
$state = 1;
return true;
case 9:
oldestYetObserved = threads[threads.length - 1].getLastMessageDate().getTime() / 1000 | 0;
$state = 21;
break;
case 19:
$state = 23;
case 23:
return false;
case 22:
throw $storedException;
default:
throw "invalid state in state machine " + $state;
}
} catch ($caughtException) {
$storedException = $caughtException;
switch ($state) {
default:
throw $storedException;
}
}
}};
return $result;
}
// Quickly reset the taskId for all ContactTouches
function reset() {
var currentUserEmailAddress = Session.getActiveUser().getEmail();
var myId = ContactsApp.getContact(currentUserEmailAddress).getId();
var contactTouches = [];
var db = ScriptDb.getMyDb();
var queryResults = db.query({ table: 'ContactTouches', ownerContactId: myId });
while(queryResults.hasNext()) { var next = queryResults.next(); next.taskId = null; contactTouches.push(next); }
db.saveBatch(contactTouches, false);
}
// Slowly delete the ScriptDB items one at a time (might affect all domain users!)
function deleteAll() {
var db = ScriptDb.getMyDb();
while (true) {
var result = db.query({});
if (result.getSize() == 0) {
break;
}
while (result.hasNext()) {
db.remove(result.next());
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A couple of points to make this more readable and maintainable:</p>\n\n<hr>\n\n<p>It has <strong>Magic Numbers</strong> everywhere:</p>\n\n<pre><code>switch ($state) {\n case 20:\n</code></pre>\n\n<p>Use constants / comment what the values mean. You will probably come back to this and it will be very hard to track down what all the values mean.<br>\nFor example:</p>\n\n<pre><code>var AWESOME_STATE_OF_AWESOMENESS = 23;\n\n\nswitch ($state) {\n case AWESOME_STATE_OF_AWESOMENESS:\n //...\n break;\n case HORRIBLE_FAIL:\n</code></pre>\n\n<hr>\n\n<p>Your code reads very <strong>horizontal</strong>. There is a lot of code all on one line. Its like trying to read a paragraph squished into one sentence.</p>\n\n<pre><code>while(queryResults.hasNext()) { var next = queryResults.next(); next.taskId = null; contactTouches.push(next); }\n</code></pre>\n\n<p>Sentences have full stops and paragraphs. Javascript has semicolons and newlines. The compiler will ignore white space so it is perfectly normal to use it. If you are trying to save bandwidth down the line then use a minifier.</p>\n\n<pre><code>while(queryResults.hasNext()) \n{\n var next = queryResults.next();\n next.taskId = null;\n contactTouches.push(next);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T05:29:43.133",
"Id": "35569",
"ParentId": "18850",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T18:11:46.467",
"Id": "18850",
"Score": "2",
"Tags": [
"email",
"google-apps-script",
"google-contacts-api"
],
"Title": "Google Apps Email, Contacts, Tasks, ScriptDB services integration"
}
|
18850
|
<p>This code solves the problem of FizzBuzz. Is it possible in any way to improve it?</p>
<pre><code>main = main' 1 where
main' n = do
(putStrLn . choose) (show n, "Fizz", "Buzz", "FizzBuzz", n)
if n < 100 then main' (succ n) else putStrLn "End!"
where
choose (n0, n3, n5, n15, n)
| mod n 3 == 0 && mod n 5 == 0 = n15
| mod n 5 == 0 = n5
| mod n 3 == 0 = n3
| True = n0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:33:28.507",
"Id": "30264",
"Score": "0",
"body": "Which definition of FizzBuzz are you using? Based on the [first Google result](http://c2.com/cgi/wiki?FizzBuzzTest) the #s are fixed at [1..100], so there shouldn't be any inputs."
}
] |
[
{
"body": "<p>You could separate your I/O from the pure code:</p>\n\n<pre><code>fizzBuzz :: Int -> String\nfizzBuzz n | mod n 3 == 0 && mod n 5 == 0 = \"FizzBuzz\"\n | mod n 5 == 0 = \"Buzz\"\n | mod n 3 == 0 = \"Fizz\"\n | otherwise = show n\n\nmain = mapM print (map fizzBuzz [0..100])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T21:08:31.327",
"Id": "30268",
"Score": "5",
"body": "I think `mapM (print . fizzBuzz) [0..100]` would be better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T13:44:22.733",
"Id": "30314",
"Score": "3",
"body": "`mapM_` would be even better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T21:54:26.920",
"Id": "18898",
"ParentId": "18852",
"Score": "6"
}
},
{
"body": "<p>jaket is definitely right, the pure/impure distinction is important. My addition would be that you should avoid recomputing the modulo:</p>\n\n<pre><code>fizzBuzz :: Int -> String\nfizzBuzz n | fizz && buzz = \"FizzBuzz\"\n | buzz = \"Buzz\"\n | fizz = \"Fizz\"\n | otherwise = show n\n where fizz = mod n 3 == 0\n buzz = mod n 5 == 0\n\nsfb = map fizzBuzz [1..15]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T05:27:10.603",
"Id": "18904",
"ParentId": "18852",
"Score": "4"
}
},
{
"body": "<p>I had written something similar to <a href=\"https://codereview.stackexchange.com/users/19659/will\">Will</a>, but the spec I read <a href=\"http://c2.com/cgi/wiki?FizzBuzzTest\" rel=\"nofollow noreferrer\">here</a> says, that FizzBuzz should always cover [1..100], so my implementation was a bit different:</p>\n\n<pre><code>show' :: Int -> String\nshow' n\n | fizz && buzz = \"FizzBuzz\" \n | buzz = \"Buzz\"\n | fizz = \"Fizz\"\n | otherwise = show n\n where fizz = mod n 3 == 0\n buzz = mod n 5 == 0\n\nfizzBuzz = [show' x | x <- [1..100]]\n</code></pre>\n\n<p>Will's idea about using where to cache the mod result was a nice idea IMHO.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:40:20.050",
"Id": "18970",
"ParentId": "18852",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18898",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:05:49.010",
"Id": "18852",
"Score": "5",
"Tags": [
"haskell",
"fizzbuzz"
],
"Title": "FizzBuzz up to 99 in Haskell"
}
|
18852
|
<p>This replaces numbers with the character that appears next to them ('number' times). Is there a a more elegant or shorter way to do this?</p>
<pre><code>var decode = function(str, result) {
var regex = /\d+/,
number = regex.exec(str);
if (number === null) {
return str;
}
var start = number.index,
end = number[0].length + start - 1,
str = str.replace(/\d+/, ""),
repeat = str.charAt(start);
result += str.substring(0, start);
for (var i = 0; i < number[0] - 1; i++) {
result += repeat;
}
result += str.substring(start, str.length);
number = regex.exec(result);
if (number === null) {
return result;
} else {
return decode(result, "");
}
};
</code></pre>
<hr>
<pre><code>var str = "bob2b11a";
console.log(decode(str, ""));
// "bobbbaaaaaaaaaaa"
</code></pre>
|
[] |
[
{
"body": "<p>From my answer on Stack Overflow: <a href=\"https://stackoverflow.com/a/13481139/538551\">https://stackoverflow.com/a/13481139/538551</a></p>\n\n<p>Simply use String.replace():</p>\n\n<pre><code>function decode(str) {\n return str.replace(/(\\d+)([a-zA-A])/g, function (match, num, letter) {\n var ret = '', i;\n for (i = 0; i < parseInt(num, 10); i++) {\n ret += letter;\n }\n return ret;\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:10:31.483",
"Id": "30071",
"Score": "0",
"body": "Yeah, but this is the better place, so I wanted to provide it here just for completeness. @epascarello's answer will probably be better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:08:29.603",
"Id": "18854",
"ParentId": "18853",
"Score": "3"
}
},
{
"body": "<p><strong>The basic concept</strong></p>\n\n<ul>\n<li>Utilize string replace with regular expression</li>\n<li>Utilize new Array Creation with join</li>\n</ul>\n\n<p><strong>The code</strong></p>\n\n<pre><code>function decode (str) {\n return str.replace(/(\\d+)(\\w)/g, \n function(m,n,c){\n return new Array( parseInt(n,10)+1 ).join(c);\n }\n );\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:11:31.963",
"Id": "30072",
"Score": "0",
"body": "Clever. I forgot about [].join..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:29:11.967",
"Id": "415616",
"Score": "0",
"body": "@epascarello please can you tell me in the function, where/how do m, n, c get populated with the values? How does that work? Many thanks in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:31:52.123",
"Id": "415617",
"Score": "0",
"body": "@mtwallet read documentation for replace https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T15:10:39.500",
"Id": "415805",
"Score": "0",
"body": "@epascarello thanks, I looked at https://www.w3schools.com/jsref/jsref_replace.asp which didn't have the same level of detail"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T17:41:39.377",
"Id": "415826",
"Score": "0",
"body": "Avoid w3schools since their documentation lacks in a bunch of areas."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:11:04.773",
"Id": "18855",
"ParentId": "18853",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18855",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:06:53.977",
"Id": "18853",
"Score": "2",
"Tags": [
"javascript",
"strings",
"compression"
],
"Title": "Run-length decoder"
}
|
18853
|
<h2>My problem is I need to know</h2>
<ul>
<li>is my code in my CRUD functions structured well and effectively? I plan to implement CRUD for Locations entity too. hopefully without redundant code.</li>
<li>you see how one CRUD function in the program class calls the other CRUD function in the DataAccess Class? I"m trying to set it up so that i can control which entity gets edited or read in the control class, and access it in the dataAccess class. Is this bad logic?</li>
</ul>
<h2>Info on classes</h2>
<ul>
<li><strong>Program</strong> - I'm trying to put all controlling logic here</li>
<li><strong>DataAccess</strong> - I'm trying to put my Data-accessing logic here, away from everything else. </li>
<li><strong>UserInterface</strong> - I'm trying to put my Interface logic here, away from everything else. Such as the way information gets displayed to the user, the way info gets received from user.</li>
<li><strong>InputValidation</strong> - I want to put all logic that validates user input here, ranging from Type validation to input range validation.</li>
<li><strong>ServiceManager</strong> - class that has a method that checks to see if SQL server is running, before doing LINQ calls to DataBase.</li>
<li><strong>DbResult</strong> - a repository wrapper class containing a string message, and a boolean. Used to report failure/success results with a message like "success!" or whatever exception.ToString() prints. <em>I am thinking this class should be removed</em>?</li>
<li><strong>Man</strong> - <em>auto-generated class by entity framework.</em></li>
<li><strong>Location</strong> - <em>auto-generated class by entity framework.</em> I plan to implement this class in my CRUD functions as soon as I can get working clean logic for the CRUD functions that handle the Man class. And hopefully <code>Man</code> & <code>Location</code> can share the same CRUD functions.</li>
</ul>
<h2>Notes</h2>
<ul>
<li>I'd like to enable CRUD functions to handle more than one entity class, without copying and pasting 4 CRUD functions for each new entity.</li>
<li>I'm considering removing DbResult, but not sure how to without keeping Data-Accessing logic separate from User Interface logic. My thought was to pass whatever message needed to be shown to the user, to the Interface class for it to be displayed. </li>
</ul>
<h2>Program Class</h2>
<pre><code>class Program
{
static private UserInterface _MyUI;
static void Main(string[] args)
{
DbResult resultSQLRunning;
ServiceManager mySM = new ServiceManager();
_MyUI = new UserInterface();
resultSQLRunning = mySM.SQLRunning();
_MyUI.DisplayMessage(resultSQLRunning.Message);
if (resultSQLRunning.bSuccess)
{
using (TestDatabaseEntities myDB = new TestDatabaseEntities())
{
DataAccess myDA = new DataAccess(myDB);
DbResult myResult = myDA.DatabaseExists();
_MyUI.DisplayMessage(myResult.Message);
}
do
{
DecideFromMenuChoice(_MyUI.GetUserAction());
} while (_MyUI._MyMenuStage != UserInterface.MenuStage.MENU_EXIT);
}
Console.ReadLine(); // press any key to exit, basically.
}
static private void DecideFromMenuChoice(int choice)
{
if (_MyUI._MyMenuStage == UserInterface.MenuStage.MENU_CRUD)
{
switch (choice)
{
case 1: DoCreate(); break;
case 2: DoRead(); break;
case 3: DoUpdate(); break;
case 4: DoDelete(); break;
default:
break;
}
}
/* else if (_MyUI._MyMenuStage == UserInterface.MenuStage.MENU_TABLE)
{
switch (choice)
{
// not sure what to do here, somehow select a table to be used in CRUD functions?
// do i need to call more CRUD functions for each new table I add?
}
}*/
}
// ============================
// CRUD FUNCTIONS
// ============================
static private void DoCreate()
{
int myID;
bool isValidID;
var dbEntities = new TestDatabaseEntities();
string newName;
DataAccess MyDA = new DataAccess(dbEntities);
DbResult CreationResult, SaveResult;
do
{
isValidID = _MyUI.GetValidInput<int>("Enter ID: ", int.TryParse, out myID);
}
while (!isValidID);
newName = _MyUI.GetInput<string>("Enter Name:", x => x.Trim());
CreationResult = MyDA.Create(new Man() {ManID = myID, Name = newName });
_MyUI.DisplayMessage(CreationResult.Message);
if (!CreationResult.bSuccess)
return;
SaveResult = MyDA.SaveChanges();
_MyUI.DisplayMessage(SaveResult.Message);
}
static private void DoRead()
{
var dbEntities = new TestDatabaseEntities();
DataAccess myDA = new DataAccess(dbEntities);
string [,] records;
DbResult readResult;
var query = from person in dbEntities.Men
where true
select person;
readResult = myDA.Read(query, out records);
if (readResult.bSuccess)
{
_MyUI.DisplayRecords(records);
}
if (!readResult.bSuccess)
_MyUI.DisplayMessage(readResult.Message);
}
static private void DoUpdate()
{
/* The code in this DoUpdate function is "simplified" and "cleaner"
* than the commented block below, I'm told. is it?*/
int myID = _MyUI.GetInput<int>("Enter ID to update: ", int.Parse);
string newName = _MyUI.GetInput<string>("Enter new name: ", x => x.Trim());
try
{
using (var dbEntities = new TestDatabaseEntities())
{
//TODO: If ManID is unique then we can use FirstOrDefault here.
var allMatchingMen =
from person in dbEntities.Men
where person.ManID == myID
select person;
foreach (var man in allMatchingMen)
man.Name = newName;
dbEntities.SaveChanges();
_MyUI.DisplayMessage("Record(s) updated");
}
}
/*catch (OptimisticConcurrencyException ex)
{
//TODO: add auto-retry logic
_MyUI.DisplayMessage("Someone updated the record, let's retry");
}*/
catch (Exception ex)
{
_MyUI.DisplayMessage("Something went wrong, could not update");
}
}
/*{
int myID;
var dbEntities = new TestDatabaseEntities();
string newName = "";
DataAccess MyDA = new DataAccess(dbEntities);
DbResult updateResult, saveResult;
myID = _MyUI.GetInput<int>("Enter ID to update: ", int.Parse);
newName = _MyUI.GetInput<string>("Enter new name: ", x => x.Trim());
var query =
from person in dbEntities.Men
where person.ManID == myID
select person;
updateResult = myDA.Update(query, new Man() { ManID = myID, Name = sNewName });
_MyUI.DisplayMessage(updateResult.Message);
if (!UpdateResult.bSuccess)
return;
SaveResult = myDA.SaveChanges();
_MyUI.DisplayMessage(saveResult.Message);
}*/
static private void DoDelete()
{
int myID;
bool isValidInput;
var dbEntities = new TestDatabaseEntities();
DataAccess myDA = new DataAccess(dbEntities);
DbResult deleteResult, saveResult;
do
{
isValidInput = _MyUI.GetValidInput<int>("Enter ID to delete: ", int.TryParse, out myID);
} while (!isValidInput);
var Query =
from person in dbEntities.Men
where person.ManID == myID
select person;
deleteResult = myDA.Delete(Query);
_MyUI.DisplayMessage(deleteResult.Message);
if (!deleteResult.bSuccess)
return;
saveResult = myDA.SaveChanges();
_MyUI.DisplayMessage(saveResult.Message);
}
}
</code></pre>
<h2>DataAccess Class</h2>
<pre><code>public class DataAccess
{
private readonly TestDatabaseEntities _MyDBEntities;
public DataAccess(TestDatabaseEntities entities)
{
_MyDBEntities = entities;
}
public DbResult DatabaseExists()
{
DbResult myResult;
if (_MyDBEntities.Database.Exists())
myResult = DbResult.Success("Database Found");
else
myResult = DbResult.Failed("Database Not Found");
return myResult;
}
// ============================
// CRUD FUNCTIONS for MAN TABLE
// ============================
public DbResult Create(Man M)
{
DbResult dbResult;
try
{
_MyDBEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name });
dbResult = DbResult.Success("Record created");
}
catch (Exception e)
{
dbResult = DbResult.Failed(e.ToString());
}
return dbResult;
}
public DbResult Update(IQueryable<Man> myQuery, Man man)
{
DbResult dbResult;
try
{
foreach (Man M in myQuery)
{
M.Name = man.Name;
}
dbResult = DbResult.Success("Record updated");
}
catch (Exception e)
{
dbResult = DbResult.Failed(e.ToString());
}
return dbResult;
}
public DbResult Delete(IQueryable myQuery)
{
DbResult dbResult;
try
{
foreach (Man M in myQuery)
{
_MyDBEntities.Men.Remove(M);
}
dbResult = DbResult.Success("Record deleted");
}
catch (Exception e)
{
dbResult = DbResult.Failed(e.ToString());
}
return dbResult;
}
public DbResult Read(IQueryable myQuery, out string[,] records)
{
DbResult dbResult;
records = null;
try
{
List<Man> men = myQuery.OfType<Man>().ToList();
records = new string[men.Count, 2];
for (int i = 0; i < men.Count; i++)
{
records[i, 0] = men[i].ManID.ToString();
records[i, 1] = men[i].Name;
}
dbResult = DbResult.Success("Read Success");
}
catch (Exception e)
{
dbResult = DbResult.Failed(e.ToString());
}
return dbResult;
}
// ============================
// SAVECHANGES FUNCTION
// ============================
public DbResult SaveChanges()
{
DbResult dbResult;
try
{
_MyDBEntities.SaveChanges();
dbResult = DbResult.Success("Saved successfully");
}
catch (Exception e)
{
dbResult = DbResult.Failed(e.ToString());
}
return dbResult;
}
}
</code></pre>
<h2>UserInterface Class</h2>
<pre><code>public class UserInterface
{
public enum MenuStage
{
MENU_EXIT,
MENU_CRUD,
MENU_TableSelect
}
public MenuStage _MyMenuStage{ get; private set; }
public UserInterface()
{
_MyMenuStage = MenuStage.MENU_CRUD;
}
/// <summary>
/// Prompts user for input with given message, and converts input to type T
/// </summary>
/// <typeparam name="T">Value type to convert to, and return</typeparam>
/// <param name="message">Message to be printed to console</param>
/// <param name="transform">The type conversion function to use on user's input</param>
/// <returns>Type T</returns>
public T GetInput<T>(string message, Converter<string, T> transform)
{
DisplayPrompt(message);
return transform(Console.ReadLine());
}
/// <summary>
/// Asks the user for valid input
/// </summary>
/// <typeparam name="T">The type of result to return as out parameter</typeparam>
/// <param name="message">The message to prompt the user with</param>
/// <param name="errorMessage">The message to Display to user with if input is invalid</param>
/// <param name="typeValidator">The TryParse function to use to test the input.</param>
/// <returns>True if input is valid as per function given to TypeValidator, Result as type T</returns>
public bool GetValidInput<T>(string message, InputValidation.TryParse<T> typeValidator, out T result, int upper = -1, int lower = -1)
{
InputValidation myInputValidator = new InputValidation();
bool isValid = false;
bool shouldTestRange = (upper != -1 && lower != -1);
string input;
input = GetInput(message, x => (x.Trim()));
isValid = myInputValidator.ValidateInputType(input, typeValidator, out result);
if (!isValid)
{
DisplayMessage("Error, invalid input type entered, type required is " + typeof(T).ToString());
return false;
}
if (shouldTestRange)
isValid = myInputValidator.ValidateInputRange(ref result, lower, upper);
if (!isValid)
{
DisplayMessage("Error, input is out of range. Range: " + lower.ToString() + " - " + upper.ToString());
return false;
}
return isValid;
}
public void DisplayMessage(string message)
{
Console.WriteLine(message);
}
public void DisplayPrompt(string message)
{
Console.Write(message);
}
public void DisplayRecords(string[,] message)
{
if (message == null)
return;
DisplayDivider();
for (int i = 0; i < message.GetLength(0); i++)
{
for (int j = 0; j < message.GetLength(1); j++)
{
Console.Write(message[i, j] + " ");
}
Console.Write("\n");
}
DisplayDivider();
}
public void DisplayMenuOptions(string[] items)
{
byte index = 0;
DisplayDivider('~');
Console.WriteLine("Select an action from menu");
foreach (string s in items)
{
Console.WriteLine(index++ + ") " + s);
}
DisplayDivider('~');
}
public void DisplayDivider(char myChar = '|')
{
String myDivider = new String(myChar, 30);
DisplayMessage(myDivider);
}
public int GetUserAction()
{
string[] menuOptions;
int choice = -1;
//TODO: implement logic that Chooses which MenuStage we're at.
menuOptions = DecideMenuOptions();
DisplayMenuOptions(menuOptions);
choice = GetInputFromRange(0, menuOptions.Length - 1);
if (choice == 0)
{
_MyMenuStage = MenuStage.MENU_EXIT;
}
return choice;
}
private int GetInputFromRange(int lowerBound, int upperBound)
{
int choice;
bool isValid = false;
do
{
isValid = (GetValidInput<int>("Enter choice> ", int.TryParse, out choice, lower: lowerBound, upper: upperBound));
} while (!isValid);
return choice;
}
/// <summary>
/// Determines which menu options need to be displayed
/// </summary>
/// <returns>Menu options that need to be displayed</returns>
private string[] DecideMenuOptions()
{
string[] menuCRUD = new string[] { "Exit", "Create", "Read", "Update", "Delete" };
string[] menuTables = new string[] { "Quit", "Men", "Locations" };
string[] myMenuChoices = null;
if (_MyMenuStage == MenuStage.MENU_CRUD)
{
myMenuChoices = menuCRUD;
}
else if (_MyMenuStage == MenuStage.MENU_TableSelect)
{
myMenuChoices = menuTables;
}
return myMenuChoices;
}
}
</code></pre>
<h2>InputValidation Class</h2>
<pre><code>public class InputValidation//<T> where T: class
{
/// <summary>
/// Delegate that matches the signature of TryParse, method defined for all primitives.
/// </summary>
/// <typeparam name="T">Output type of This Delegate</typeparam>
/// <param name="input">input for this Delegate to translate to type T</param>
/// <param name="output">The translated variable to return via out parameter</param>
/// <returns>Whether the Parse was successful or not, and output as output</returns>
public delegate bool TryParse<T>(string sInput, out T output);
public bool ValidateInputType<T>(string sInput, TryParse<T> TypeValidator, out T result)
{
return TypeValidator(sInput, out result);
}
public bool ValidateInputRange<T>(ref T result, int lower, int upper)
{
// How can I use relational operators like > < = on T? without forcing T result to an int?
return isValidRange(int.Parse(result.ToString()), lower, upper);
}
public bool isValidRange(int item, int Lower, int Upper)
{
return (Lower <= item && item <= Upper);
}
}
</code></pre>
<h2>ServiceManager Class</h2>
<pre><code>public class ServiceManager
{
public DbResult SQLRunning()
{
DbResult myResult;
ServiceController sc = new ServiceController("SQL Server (SQLEXPRESS)");
if (sc.Status == ServiceControllerStatus.Running)
myResult = DbResult.Success("SQL Server is running");
else
myResult = DbResult.Failed("SQL Server is NOT running.");
return myResult;
}
}
</code></pre>
<h2>DbResult (wrapper class)</h2>
<pre><code>public class DbResult
{
public bool bSuccess { get; private set; }
public String Message { get; private set; }
private DbResult(bool success, string message)
{
this.bSuccess = success;
this.Message = message;
}
public static DbResult Failed(string message)
{
return new DbResult(false, message);
}
public static DbResult Success(string message)
{
return new DbResult(true, message);
}
}
</code></pre>
<h2>Man Class</h2>
<pre><code>public partial class Man
{
public Man()
{
this.Locations = new HashSet<Location>();
}
public int ManID { get; set; }
public string Name { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
</code></pre>
<h2>Location Class</h2>
<pre><code>public partial class Location
{
public Location()
{
this.Men = new HashSet<Man>();
}
public int PlaceID { get; set; }
public string Place { get; set; }
public virtual ICollection<Man> Men { get; set; }
}
</code></pre>
<h2><strong>UPDATE:</strong></h2>
<p>11/20/12 9:01 CST: Improved seperation of logic in UserInterface class and Program Class. At least I think so.
11/21/12 6:46 CST: Improved UserInterface class slightly.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T15:05:21.923",
"Id": "30110",
"Score": "0",
"body": "I definitely think there's something wrong here, but I'm having a hard time articulating what it is. Are these the default EF-generated classes, or did you apply another code generation template?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T15:55:35.027",
"Id": "30118",
"Score": "0",
"body": "I applied multiple code generation templates, but each time I applied a new one, I deleted the old. Why do you ask?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T16:01:00.670",
"Id": "30120",
"Score": "0",
"body": "That's what's supposed to happen. Each template generates its own set of classes and its own way of interacting with them. You handle POCOs differently from persistance-aware classes, for instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T20:48:43.260",
"Id": "30326",
"Score": "0",
"body": "@Bobson so, can you see anything wrong with the code i have posted above? :-/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T19:00:02.973",
"Id": "30363",
"Score": "0",
"body": "I took my best shot at explaining my instinct, but I'm not an expert. See if it's useful."
}
] |
[
{
"body": "<p>This is hard, because you're writing an application which is <em>specifically</em> a pure CRUD app, so the distinction between the business logic and the database logic isn't as clear as it usually is. Most applications don't let you just create a new <strong>_</strong>, they do that for you behind the scenes as you manipulate the UI. Additionally, I'm not an expert - I've done a lot of experimenting with EF, but I have yet to use it in anything resembling a production context.</p>\n\n<p>That being said, I think almost everything in your <code>DataAccess</code> class needs to go. See <a href=\"http://blogs.msdn.com/b/adonet/archive/2009/05/21/poco-in-the-entity-framework-part-1-the-experience.aspx\" rel=\"nofollow\">these</a> <a href=\"http://blogs.msdn.com/b/adonet/archive/2009/05/28/poco-in-the-entity-framework-part-2-complex-types-deferred-loading-and-explicit-loading.aspx\" rel=\"nofollow\">three</a> <a href=\"http://blogs.msdn.com/b/adonet/archive/2009/06/10/poco-in-the-entity-framework-part-3-change-tracking-with-poco.aspx\" rel=\"nofollow\">posts</a> for examples of working with <a href=\"http://msdn.microsoft.com/en-us/library/dd456853%28v=vs.100%29.aspx\" rel=\"nofollow\">POCO</a> data objects, which looks kindof like what you're trying to do.</p>\n\n<p>Your <code>DataAccess</code> class should probably only expose a <code>Get</code> method for each data type, and an overall <code>SubmitChanges</code> method that saves everything. <code>Get</code> will determine whether the objects exists, and return either a new object (as generated by <code>context.CreateObject<>()</code>) or the object loaded from the database. Then you can manipulate that object as you choose, and <code>SubmitChanges</code> will save all changes to all objects back to the database. You <em>might</em> need to implement a <code>Delete</code> for each object as well, but you can probably avoid that somehow.</p>\n\n<p>From my understanding, proper n-tier architecture means that nothing outside of the data layer should have any idea how CRUD operations work - to everything else, it's just a sequence of either \"Load\" or \"Load, Mutate, Save\".</p>\n\n<p>Does this help?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T00:13:07.920",
"Id": "30399",
"Score": "0",
"body": "About n-tier architecture, I don't understand why CRUD shouldn't be processed in the data layer. CRUD seems _very_ data-relevant. But you mention that most applications don't let the user directly create and modify data. My goal in this is to create an applicable program that I can present to an employer that can show what I've learned and that I'm familiar with what kind of things they do. Are there any suggestions you can give to create an application that is more commonly used or is that a question that belongs elsewhere?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:36:03.127",
"Id": "30462",
"Score": "0",
"body": "I said \"nothing **outside** of the data layer should have any idea how CRUD operations work\". As you said, it is very relevant to the data itself. As for an alternative, I'd suggest building a small business layer on top of it - either a basic receipt entry / Point-of-sale app, or a basic address management app. Either one is a fairly typical programming exercise that exercises all CRUD functionality + business logic. They may just be glorified CRUD, but they separate the business concept (a person or a receipt) from the database details (person -> addresses, receipt -> details)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T18:58:28.553",
"Id": "19029",
"ParentId": "18858",
"Score": "0"
}
},
{
"body": "<p>Since it's to show off to an employer I'll look at it in that context.</p>\n\n<p>One style issue I have is that you are mixing naming conventions. You are using both hungarian notation and CamelCase. I would suggest to get rid of the hungarian notation (sParam, bIsTrue, ...).</p>\n\n<p>Regarding the overall structure of your code:</p>\n\n<ul>\n<li><p>The Program-class: </p>\n\n<ul>\n<li>it has too much logic (too many responsibilities). I would refactor the logic out of there into a mediator-kind of class. The Program-class should only start something.</li>\n<li>IMHO: the interpretation of the user input (choice 1, 2, etc) should be done by the UI class (actually if you go MVC the controller, but it looks like overkill). The UI class should expose events or delegates where the program (or better a mediator) can plugin the necessary actions.</li>\n</ul></li>\n<li><p>The DataAccess-class:</p>\n\n<ul>\n<li>The DataAccess class has the role of a repository. Why not call it that. It'll show you know the repository pattern. However on second thought it looks like it has the role of a helper class?</li>\n<li>Use <code>IEnumerable<string></code> and <code>yield return</code> instead of a string array in the read method</li>\n<li>No disposing of the <code>TestDatabaseEntities</code>? It is missing from the CRUD methods on your program class.\nUsually the <code>TestDatabaseEntities</code> has a lifetime equal to the repository, a repository encapsulates the `TestDatabaseEntities and exposes the disposing by implementing IDisposable.</li>\n</ul></li>\n<li><p>Also in your create method why do this:</p>\n\n<p>_MyDBEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name });</p></li>\n</ul>\n\n<p>and not directly:</p>\n\n<pre><code>_MyDBEntities.Men.Add(M);\n</code></pre>\n\n<p>I hope that this is in the direction of the kind of advice you were hoping for?</p>\n\n<p>I'll see if I can whip up an example later that explains better what I am trying to tell.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T01:25:54.220",
"Id": "30499",
"Score": "0",
"body": "so if user's input methods are defined in the view aka `UserInterface` then what kinds of things should `program` aka controller do so i may justify doing mvc so i can practice, learn, and demonstrate that I understand it to a potential employer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T14:12:02.803",
"Id": "30529",
"Score": "0",
"body": "@MattRohde - The controller generally uses data objects to populate a view model, then chooses the correct view to display. A view model contains just the information needed for the view to do its work, and can be populated from several different database objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T19:51:12.100",
"Id": "30563",
"Score": "0",
"body": "@bobson I see, well, this program has only one view, the UserInterface Class, so the controller would function to swap out other UserInterface-like classes if the program had them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T20:31:19.877",
"Id": "30568",
"Score": "0",
"body": "@MattRohde - Ideally, UserInterface would be a base type for each interface you'd actually show (like Mvc.View is for websites), but for this you probably don't need that. If you do want to go the formal MVC route, though, you might want to look into libraries to help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T01:09:41.530",
"Id": "30576",
"Score": "0",
"body": "@bobson I am not sure how to move the CRUD functions in Program to the `DataAccess` Class without also moving references to the `UserInterface` class to within the DataAccess class too. And according to [this post](http://codereview.stackexchange.com/questions/18366/how-to-organize-this-code-and-prepare-more-versatile-crud-functions/18393#18393) I'm not supposed to make the UI interact directly with EF layer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:14:47.163",
"Id": "30696",
"Score": "0",
"body": "@MattRohde - UserInterface (View) calls the controller. Controller calls DataAccess (Model). View doesn't interact with Model directly. For example: You have a \"Save receipt\" button on the view. That calls `Controller.SaveReceipt(ReceiptData data)`. That, in turn, breaks `ReceiptData` down into the appropriate changes to the database."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T06:17:47.527",
"Id": "30723",
"Score": "0",
"body": "@Bobson I understand what you're saying, but am having a hard time picturing it in my code, could you perhaps provide a simplified coding sample of how the CRUD should be divided between Controller, View, and Model?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T11:01:39.150",
"Id": "30799",
"Score": "1",
"body": "For example: Your controller would create an instance of the Man-class setting defaults if necessary. The controller passes the Man-class to the userinterface, after the user interface is done editing it will return the changed Man-class to the controller. The controller will now execute the necessary actions to save (create/update/delete) the Man-class using methods of the dataAccess class."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T12:28:12.150",
"Id": "19058",
"ParentId": "18858",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19058",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T20:56:52.650",
"Id": "18858",
"Score": "4",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Trying to clearly seperate my logic in my program"
}
|
18858
|
<p>I'd like to improve my router.</p>
<p>This is the current code for my autoloading action within my MVC application:</p>
<pre><code>spl_autoload_register(function ($className) {
if (file_exists(ROOT . DS . 'library' . DS . 'intranet' . DS . 'classes' . DS .strtolower($className) . '.php')){
require_once(ROOT . DS . 'library' . DS . 'intranet' . DS . 'classes' . DS .strtolower($className) . '.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'controller' . DS . strtolower($className) . '.php')) {
require_once(ROOT . DS . 'application' . DS . 'controller' . DS . strtolower($className) . '.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'model' . DS . strtolower($className) . '.php')) {
require_once(ROOT . DS . 'application' . DS . 'model' . DS . strtolower($className) . '.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'view' . DS . strtolower($className) . '.php')) {
require_once(ROOT . DS . 'application' . DS . 'view' . DS . strtolower($className) . '.php');
} else {
throw new exception("$className" class failed to load: file not found");
});
</code></pre>
<p>It is looking for the class file in different folder, requiring it. If that fails, an exception is thrown.</p>
<p>It doesn't seem flexible, and I doubt that it'll play well with other libraries and autoloaders that are introduced as the project goes.</p>
<p>How could I improve my existing autoloader?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:21:16.790",
"Id": "30083",
"Score": "0",
"body": "Any particular reason why you're not using namespaces?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:23:06.267",
"Id": "30084",
"Score": "0",
"body": "At this moment in time, I'm not extremely comfortable using namespaces, it's something I do plan to implement. The reason I'm not comfortable is because I don't fully understand them. How would I implement it here?"
}
] |
[
{
"body": "<p>What you've written is more or less the standard implementation of <code>spl_autoload()</code>.</p>\n\n<p>This is an equivalent approach:</p>\n\n<pre><code>$paths = array(\n get_include_path(),\n ROOT . DS . 'library' . DS . 'intranet' . DS . 'classes',\n ROOT . DS . 'application' . DS . 'controller',\n ROOT . DS . 'application' . DS . 'model',\n ROOT . DS . 'application' . DS . 'view',\n);\n\n// help system to find your classes\nset_include_path(join(PATH_SEPARATOR, $paths));\n\n// use standard auto loader\nspl_autoload_register();\n</code></pre>\n\n<p>Using namespaces in your application would help a lot as well; for instance, in each of your controller classes you simply add:</p>\n\n<pre><code>namespace controller;\n</code></pre>\n\n<p>When you take a similar approach for models and views as well, you reduce above code to this:</p>\n\n<pre><code>$paths = array(\n get_include_path(),\n ROOT . DS . 'library' . DS . 'intranet' . DS . 'classes',\n ROOT . DS . 'application',\n);\n\nset_include_path(join(PATH_SEPARATOR, $paths));\n\n// use standard auto loader\nspl_autoload_register();\n\n// ...\n$x = new controller\\something();\n</code></pre>\n\n<p>Namespaces are converted to directories by <code>spl_autoload()</code> so you only need to set the <code>application</code> directory to make it work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:35:29.567",
"Id": "18868",
"ParentId": "18861",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18868",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T21:59:00.697",
"Id": "18861",
"Score": "2",
"Tags": [
"php",
"url-routing"
],
"Title": "Improving my PHP autoloader"
}
|
18861
|
<p>I have a lot of variables that I need to check for exceptions and output the empty field in case of a null returned value (I am reading a calender list from Sharepoint and my program is supposed to send email notifications if some of the conditions are met).</p>
<p>I surrounded my variables with a try-catch with a generic output "variable not found". Here is an example;</p>
<pre><code>try
{
var name = item["Name"].ToString();
var dueDate= item["Due Date"].ToString();
.
.//more variables
.
var Title= item["Title"].ToString();
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine(ex.Message); //generic message for now
Console.WriteLine();
}
</code></pre>
<p>Is there is a way to handle this better? I know that going to each individual line and adding an exception is an option but it would save me a lot of time if I can just output something like the variable name.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T14:26:15.953",
"Id": "30105",
"Score": "0",
"body": "What is the type if `item`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T16:09:32.283",
"Id": "30121",
"Score": "0",
"body": "@ANeves SPListItem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T04:26:58.303",
"Id": "30241",
"Score": "0",
"body": "Where do these values come from? Are they settings of some sort?"
}
] |
[
{
"body": "<p>Refactor into a method:</p>\n\n<pre><code>var name = this.GetVariable(\"Name\"); \nvar dueDate= this.GetVariable(\"Due Date\");\n.\n.//more variables\n. \nvar Title= this.GetVariable(\"Title\"); \n\nprivate string GetVariable(string name)\n{\n try\n {\n return item[name].ToString(); \n }\n catch (Exception ex)\n {\n Console.WriteLine();\n Console.WriteLine(name + \" not found.\");\n Console.WriteLine();\n return null;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T22:47:33.870",
"Id": "30330",
"Score": "0",
"body": "Nicely done. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T22:58:44.003",
"Id": "18863",
"ParentId": "18862",
"Score": "7"
}
},
{
"body": "<p>Create a class that wraps the information you need. Within the class you would have a method that retrieves the information, or even retrieves the information and strongly types it.</p>\n\n<pre><code>public sealed class ValueConverter\n{\n private readonly IDictionary<string, dynamic> _item;\n\n public ValueConverter(IDictionary<string, dynamic> item)\n {\n _item = item;\n }\n\n public T ConvertTo<T>(string fieldName)\n {\n var type = typeof(T);\n\n var value = _item[fieldName];\n\n if (value == null)\n {\n throw new ApplicationException(string.Format(\"Field '{0}' is empty.\", fieldName));\n }\n\n return Convert.ChangeType(value, type);\n }\n}\n</code></pre>\n\n<p>I used <code>IDictionary<string, dynamic></code> because I don't know what 'item' is.</p>\n\n<p>you would then do something like this:</p>\n\n<pre><code>var converter = new ValueConverter(item);\n\nvar name = converter.ConvertTo<string>(\"name\"); \nvar dueDate= = converter.ConvertTo<DateTime>(\"Due Date\");\n.\n.//more variables\n. \nvar Title = converter.ConvertTo<string>(\"Title\"); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:06:57.270",
"Id": "18865",
"ParentId": "18862",
"Score": "4"
}
},
{
"body": "<p>This is my two attempts at keeping it simple. I normally try not to rely on the exceptions to detect errors of validation. Therefore one answer with exception and one without.</p>\n\n<p>Also you might want to return a string for the error message from the method instead of writing directly at the console.</p>\n\n<pre><code> public string ExecuteUsingTry()\n {\n var empty = string.Empty;\n string[] objectsInTheCollection = { \"Name\", \"Due Date\", \"Title\" };\n var item = new Dictionary<string, object>();\n\n foreach (var key in objectsInTheCollection)\n {\n try\n {\n item[key].ToString();\n }\n catch (Exception ex)\n {\n empty += \"\\n\";\n empty += ex.Message;\n empty += \"\\n\";\n }\n }\n\n return empty;\n }\n</code></pre>\n\n<p>Example number two</p>\n\n<pre><code> public string ExecuteUsingContains()\n {\n var empty = string.Empty;\n string[] objectsInTheCollection = { \"Name\", \"Due Date\", \"Title\" };\n var item = new Dictionary<string, object>();\n\n foreach (var key in objectsInTheCollection)\n {\n if (!item.ContainsKey(key))\n {\n empty += \"\\n\";\n empty += \"Error related to\" + key;\n empty += \"\\n\";\n }\n else\n {\n // Your Processing\n item[key].ToString();\n }\n }\n return empty;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:22:26.740",
"Id": "30305",
"Score": "0",
"body": "+1 I like the approach without exceptions because the scenario doesn't sound very exceptional and I think it's much better to read here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-24T16:53:39.183",
"Id": "37488",
"Score": "0",
"body": "smasher I like the second one more also is very predictable what the need is.\n\nAlso should mention that you might want to use a string.format in those examples when creating empty I suffered a bit of tunnel vision when writing the samples."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:27:35.803",
"Id": "18866",
"ParentId": "18862",
"Score": "3"
}
},
{
"body": "<p>If you actually just need the empty string instead of null, and you don't care about alerting the user that the value was null, just do:</p>\n\n<pre><code>var name = (item[\"Name\"] ?? \"\").ToString(); \nvar dueDate= (item[\"Due Date\"] ??).ToString();\n...\n</code></pre>\n\n<p>Alternatively, you could even make a small helper method to do this for you:</p>\n\n<pre><code>public static string GetValue(object o)\n{\n if (o == null) return \"\";\n else return o.ToString();\n}\n</code></pre>\n\n<p>and call it as:</p>\n\n<pre><code>var name = GetValue(item[\"Name\"]); \nvar dueDate= GetValue(item[\"Due Date\"]);\n</code></pre>\n\n<p>You won't get any exceptions with either of these ways - just empty strings. You should avoid throwing (or deliberately expecting) an exception whenever possible. See <a href=\"https://stackoverflow.com/a/77361/298754\">this answer</a> and some of the other answers on that page - exceptions should be for an unexpected scenario, not normal control flow.</p>\n\n<hr>\n\n<p>In the case where the column doesn't even exist when it has no data (which indicates an issue with the generation of the data), you can modify it as follows:</p>\n\n<pre><code>public static string GetValue(DataRow row, string column)\n{\n if (!row.Table.Columns.Contains(column) || row[column] == null) return \"\";\n else return row[column].ToString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T14:27:12.630",
"Id": "30106",
"Score": "0",
"body": "What if item doesn't have `[\"name\"]`? Exception **does** jump out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T14:52:01.533",
"Id": "30108",
"Score": "0",
"body": "@ANeves - That's an issue with the process which gets the data - if it's not returned in a standard format, then you're going to have a lot more issues with processing it. However, edited to handle that scenario."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T14:12:32.890",
"Id": "18888",
"ParentId": "18862",
"Score": "3"
}
},
{
"body": "<p>I prefer a more functional approach to the problem, using a little LINQ. I'm assuming that \"item\" is a Dictionary. To see how the code behaves, add or remove items from this Dictionary, or play with the values by using null and empty strings. Whitespace left as an exercise to the reader ;)</p>\n\n<pre><code>var required = new [] { \"Name\", \"Due Date\", \"Title\" };\nvar items = new Dictionary<string, string>{\n {\"Name\", \"Joe\"},\n {\"Title\", \"a title\"},\n {\"Due Date\", \"11/23/2012\"},\n {\"Foo\", \"A non required field\"}\n};\n\nvar filledOutValues = items.Where(i => !String.IsNullOrEmpty(i.Value));\nvar missingFields = required.Except(filledOutValues.Select(i => i.Key));\n\nif(missingFields.Any()) {\n var missing = missingFields.Aggregate((acc, m) => acc + \", \" + m);\n Console.WriteLine(\"Missing Fields: \" + missing);\n}\nelse {\n //Rock On!\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T06:18:31.030",
"Id": "30244",
"Score": "0",
"body": "Although .Count() == 0 is probably quicker I would personally still prefer to get rid of the isValid and use missingFields.Any()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T14:35:07.340",
"Id": "30533",
"Score": "0",
"body": "Great suggestion! Much more readable. I updated the code sample. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T04:20:27.133",
"Id": "18959",
"ParentId": "18862",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18863",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T22:42:46.840",
"Id": "18862",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"exception"
],
"Title": "Handling null exception when having multiple variables"
}
|
18862
|
<p>I'm learning JavaScript and came up with this basic game code structure (using the CreateJS framework): </p>
<pre><code>var stage;
var totalLoaded = 0;
var manifest;
var game = game || {};
game.init = {
load: function () {
var canvas = document.getElementById('gameCanvas');
images = createjs.images || {};
stage = new createjs.Stage(canvas);
manifest = [{
src: "http://i47.tinypic.com/swtj03.png",
id: "circleImg"
}, ]
loader = new createjs.PreloadJS(false);
loader.onFileLoad = game.init.handleFileLoad;
loader.loadManifest(manifest);
game.init.ticker();
game.init.processText();
game.init.interaction();
},
handleFileLoad: function (o) {
if (o.type == "image") {
images[o.id] = o.result = new createjs.Bitmap(o.result);
switch (o.id) {
case "circleImg":
images[o.id].y = 302;
break;
}
game.init.handleLoadComplete();
}
},
handleLoadComplete: function (e) {
totalLoaded++;
if (manifest.length == totalLoaded) {
game.init.handleComplete();
}
},
handleComplete: function () {
game.menu();
},
ticker: function () {
createjs.Ticker.addListener(window);
createjs.Ticker.useRAF = true;
createjs.Ticker.setFPS(60);
},
text: [{
"name": "startText",
"content": "START",
"style": "bold 50px Arial",
"color": "red",
"x": "325",
"y": "140",
"scaleX":"1",
"scaleY":"1"
},
{
"name": "animationComplete",
"content": "ANIMATION COMPLETE",
"style": "bold 50px Arial",
"color": "red",
"x": "125",
"y": "140",
"scaleX":"1",
"scaleY":"1"
},
{
"name": "animationRestart",
"content": "RESTART TO MENU?",
"style": "bold 20px Arial",
"color": "gray",
"x": "125",
"y": "340",
"scaleX":"1",
"scaleY":"1"
}
],
textId: [],
processText: function () {
for (i = 0; i < this.text.length; i++) {
this.textId[i] = new createjs.Text(this.text[i].content, this.text[i].style, this.text[i].color);
this.textId[i].x = this.text[i].x;
this.textId[i].y = this.text[i].y;
this.textId[i].scaleX = this.text[i].scaleX;
this.textId[i].scaleY = this.text[i].scaleY;
this.textId[i].name = this.text[i].name;
}
},
resource: function (e) {
stage.addChild(e);
},
remove: function (e) {
stage.removeChild(e);
},
interaction: function () {
this.textId[0].onClick = handleClick;
this.textId[2].onClick = handleClick;
function handleClick(event) {
switch (event.target.name) {
case "startText":
game.init.remove(game.init.textId[0]);
game.init.resource(images['circleImg']);
game.animation.circle();
break;
case "animationRestart":
game.restart();
break;
}
}
}
}
game.animation = {
circle: function () {
var circleTween = new createjs.Tween.get(images['circleImg'], {
loop: false
}).to({
x: 800
}, 2000, createjs.Ease.quadIn).call(function () {
game.animation.callComplete();
});
},
callComplete: function() {
game.init.resource(game.init.textId[1]);
game.animation.restartText();
},
restartText: function() {
game.init.resource(game.init.textId[2]);
var restartBlink = new createjs.Tween.get(game.init.textId[2], {
loop:true
}).to({
scaleX: 1,
scaleY: 1
}, 500, createjs.Ease.quadOut)
.to({
scaleX: 1.1,
scaleY: 1.1
}, 500, createjs.Ease.quadOut)
.to({
scaleX: 1,
scaleY: 1
}, 500, createjs.Ease.quadOut)
}
}
game.resetPositions = function() {
images['circleImg'].x = 0;
}
game.restart = function () {
stage.removeAllChildren();
game.resetPositions();
game.menu();
}
game.menu = function () {
game.init.resource(game.init.textId[0]);
}
tick = function () {
stage.update();
}
</code></pre>
<p><a href="http://jsfiddle.net/f8kXc/2/" rel="nofollow">JSFiddle</a></p>
<p>(<a href="http://jsfiddle.net/f8kXc/" rel="nofollow">old version before changes</a>)</p>
<p>Is this a viable basic game structure? How can I improve game data storage (in this basic case text storage) and naming?</p>
<p>EDIT: added repeat functionality and a dedicated namespace.</p>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Object notation does not require the properties to be quoted, you can simply do this:</p>\n\n<pre><code>{\n name: \"startText\",\n content: \"START\",\n style: \"bold 50px Arial\",\n color: \"red\",\n x: 325,\n y: 140,\n scaleX:1,\n scaleY:1\n}\n</code></pre>\n\n<p>Note that I also removed quotes from the numeric constants, you do not need them.</p></li>\n<li>I would have named your text array <code>texts</code> instead of <code>text</code></li>\n<li>There are some variables you are not declaring with <code>var</code> : <code>i</code>, <code>images</code>, and <code>loader</code>, this pollutes the global namespace.</li>\n<li>It is better to use <code>images.circleImg</code> then <code>images['circleImg']</code>.</li>\n<li>There is no need capture the results of <code>new createjs.Tween</code> into <code>circleTween</code> and <code>restartBlink</code> since you do nothing with those variables</li>\n<li>The magic number <code>500</code>, <code>2000</code> and <code>800</code> in <code>restartText</code> should be capture in a single constant </li>\n<li>This : <code>this.textId[0].onClick = handleClick;</code> is old skool, please look into <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener\" rel=\"nofollow\"><code>addEventListener</code></a></li>\n<li>I would have made <code>stage</code>, <code>totalLoaded</code> and <code>manifest</code> part of <code>game</code></li>\n<li>I would add some error handling to <code>loader</code> especially if you are loading an image from a different domain..</li>\n<li>On a final note, the jsfiddle does not work for me, but then again, this a 2012 question ;)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:27:34.107",
"Id": "41416",
"ParentId": "18867",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:33:25.460",
"Id": "18867",
"Score": "5",
"Tags": [
"javascript",
"game",
"canvas"
],
"Title": "Basic game code structure tips"
}
|
18867
|
<p>I'm submitting this code in a couple of days as part of an an interview process. The company knows that I don't have any formal experience with Java. I'm hoping they are testing my ability to learn it on the fly. </p>
<p>This is my first non-trivial Java program and I'm looking for improvements and advice as if to whether I'm following "best practice" Java.</p>
<p>The comments below explain a bit about the program and example input/output is posted below as well. </p>
<p>The rounding was a bit weird, as it was always up to the next .05 cents to satisfy the requirements.</p>
<p>The code can be tested <a href="http://ideone.com/ZEPZVl" rel="nofollow">here</a>.</p>
<pre><code>/*************************************************************************
* RUN AT: http://ideone.com/ZEPZVl
* REVIEWED AT:
*
* ASSUMPTIONS: That the input is well-formed. A group is terminated by
* an empty line of form "^\\s*$". Headings are of the form
* "^Input (\\d):". Monetary values are of the form
* "(\\sat) ([0-9]+\\.[0-9]+)".
*
* MODIFYING: Strings that mark food, books and medical supplies can be set
* in base_array. String that mark imports can be set in import_array.
*
* NOTE: This code was developed at ideone.com. The final empty line
* was not detected and I was required to put an END. I assume the
* the front end of the web-app was stripping trailing white space.
*
*************************************************************************/
import java.io.InputStream;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main (String[] args) {
try {
Taxer taxer = new Taxer();
taxer.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Taxer {
private String[] import_array = {"import"},
base_array = {"book", "chocolate", "pills"};
private Scanner scanner = new Scanner(System.in);
private final Pattern p_input = Pattern.compile("^Input (\\d):"),
p_money = Pattern.compile("(\\sat) ([0-9]+\\.[0-9]+)"),
p_empty = Pattern.compile("^\\s*$");
private final double TAX5 = .05,
TAX10 = .10;
private double tax_group_sum = 0,
price_group_sum = 0,
price,
tax_import,
tax_base;
private String line;
public void run() {
while(scanner.hasNext()) {
analyzeLine();
}
}
private void analyzeLine () {
Matcher m_input,
m_money,
m_empty;
line = scanner.nextLine();
m_input = p_input.matcher(line);
m_money = p_money.matcher(line);
m_empty = p_empty.matcher(line);
price = 0;
// heading
if (m_input.find()) {
System.out.println("Output " + m_input.group(1) + ":" );
// line containing money amount
} else if (m_money.find()) {
line = m_money.replaceFirst(": ");
price = Double.parseDouble(m_money.group(2));
checkTaxed();
checkImports();
addValues();
printLine();
// empty line
} else if(m_empty.find()) {
printTotal();
tax_group_sum = 0;
price_group_sum = 0;
// catch all echos input
} else {
System.out.println(line);
}
}
private boolean checkImports () {
Pattern p;
Matcher m;
tax_import = 0;
for (String s : import_array) {
p = Pattern.compile(s);
m = p.matcher(line);
if(m.find()) {
tax_import = roundSingleValue(price * TAX5);
return true;
}
}
return false;
}
private boolean checkTaxed() {
Pattern p;
Matcher m;
tax_base = 0;
for (String s : base_array) {
p = Pattern.compile(s);
m = p.matcher(line);
if(m.find()) {
return false;
}
}
tax_base = roundSingleValue(price * TAX10);
return true;
}
private double roundSingleValue (double value) {
double accuracy = 20;
value = value * accuracy;
value = Math.ceil(value);
value = value / accuracy;
return value;
}
private void addValues () {
double tax_total = tax_base + tax_import;
price = price + tax_total;
tax_group_sum += tax_total;
price_group_sum += price;
}
private void printTotal () {
System.out.printf("Sales Taxes: %.2f%n", tax_group_sum);
System.out.printf("Total: %.2f%n%n", price_group_sum);
}
private void printLine () {
System.out.print(line);
System.out.printf("%.2f%n", price);
}
}
/*
Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85
Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50
Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25
END
*/
/*
Output 1:
1 book: 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83
Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15
Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 box of imported chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
END
*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T20:46:13.920",
"Id": "30148",
"Score": "0",
"body": "Also, consider a more functional approach - instead of methods that work on instance variables (reading or mutating), use parameters and returns. This should help to limit side-effects, which can be a _huge_ cause of program errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T19:52:40.500",
"Id": "31297",
"Score": "0",
"body": "they specifically asked for an oo approach"
}
] |
[
{
"body": "<p>Just a few quick notes:</p>\n\n<ol>\n<li><p>The catch block in the main method seems unnecessary. Throwing out exceptions has the same effect:</p>\n\n<pre><code>public static void main(final String[] args) {\n final Taxer taxer = new Taxer();\n taxer.run();\n}\n</code></pre></li>\n<li><p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Don't use floating point variables where you may need exact results:</p>\n\n<ul>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n<li><a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">Why not use Double or Float to represent currency?</a></li>\n</ul></li>\n<li><p>Variable name prefixes are unnecessary and uncommon in the Java world. See <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T03:59:09.163",
"Id": "18872",
"ParentId": "18869",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18872",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:50:25.080",
"Id": "18869",
"Score": "4",
"Tags": [
"java",
"interview-questions",
"finance"
],
"Title": "Swedish Tax Calculator"
}
|
18869
|
<p>I'm trying to write a little page which will help me - when it ever gets finished - in my job to get some stuff done easier and faster. I'd like some hints and tricks for better structuring the code, i.e. to better divide logic from the UI.</p>
<p>I use jQuery a bit (need to expand my knowledge of using it) and will finally probably use twitter bootstrap as a framework.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*
* This section is about the "select" input elements
*
* This should realize a cascading dropdown, which
* shows options in the second select input elemen
* "protocols" depending on the selection of a scanner
*
* Found this solution on the web an adopted it ab bit
* to my needs.
*/
function appendOptionToSelect(sel, opt) {
try {
sel.add(opt, null);
} catch (e) {
//for IE7 and earlier
if (e.name == "TypeError") {
sel.options[sel.options.length] = opt;
} else {
throw e;
}
}
};
function removeAllChildNodes(element) {
if (element.hasChildNodes()) {
while (element.childNodes.length >= 1) {
element.removeChild(element.firstChild);
};
};
};
function selChanged(sel, data, dependentSel) {
var selection = sel.options[sel.selectedIndex].value;
var arrOptions = data[selection];
var opt;
removeAllChildNodes(dependentSel);
for (var i in arrOptions) {
opt = new Option(arrOptions[i]);
appendOptionToSelect(dependentSel, opt);
}
};
// This should be the object which holds the protocols specific
// for a scanner
var scanner = {
"scanner1" : ["--choose--", "protocol 1", "protocol 2", "protocol 3"],
"scanner2" : ["--choose--", "protocol 2", "protocol 4", "protocol 5"],
"scanner3" : ["--choose--", "protocol 1", "protocol 2", "protocol 5", "protocol 6"],
"scanner4" : ["--choose--", "protocol 3a", "protocol 4b", "protocol xyz"]
};
// Needed down in the eventhandlers
var selectScanner = document.getElementById("scanner");
var selectProtocol = document.getElementById("protocols");
// Calculation the age in years (found this on the web)
function getAge() {
var dateOfExam = new Date(document.getElementById('dateOfExam').value);
var dateOfBirth = new Date(document.getElementById('dateOfBirth').value);
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// age in days
var days = Math.floor((dateOfExam.getTime() - dateOfBirth.getTime()) / 1000 / 60 / 60 / 24);
var age = 0;
// calculating years
for (var y = dateOfBirth.getFullYear(); y <= dateOfExam.getFullYear(); y++) {
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear) {
days -= daysInYear;
age++;
// just increment the year if there are enough days for a year
}
}
return age;
}
/* Bodysurface and BMI
*
* Ok, now it gets chaotic, this is my solution.
* The aim is, to calculate both BSA and BMI depending on the input-values from
* the elements "weight" and "height".
* I need to get
* - a string like (for BSA): 2,3 m2
* - a string like (for BMI): 25,5
* - global(?) variables which stores the floats for bmi and bsa
* I guess my way is weird...
*/
var bsa, bmi, kof;
function Kof(cm, kg) {
var mosteller = Math.sqrt(Number(cm) * Number(kg) / 3600);
var bmi = Number(kg) / Math.pow((Number(cm) / 100), 2);
this.getStringMosteller = function() {
return mosteller.toFixed(1).replace(/\./, ",") + " m<sup>2</sup>";
};
this.getStringBmi = function() {
return bmi.toFixed(1).replace(/\./, ",");
};
this.getMosteller = function() {
return mosteller;
};
this.getBmi = function() {
return bmi;
};
}
function setBmiAndBsa() {
var cm = parseFloat($('#height').val());
var kg = parseFloat($('#weight').val());
if (!isNaN(cm) && !isNaN(kg)) { // checking that there are numbers
kof = new Kof(cm, kg);
bsa = kof.getMosteller(); // getting the floats for bsa
bmi = kof.getBmi(); // and bmi
// and writing the string values to the html-page
$('#bsa').html(kof.getStringMosteller());
$('#bmi').html(kof.getStringBmi());
};
}
$(document).ready(function() {
// set the current date as the date of examination
$('#dateOfExam').val(new Date().toJSON().substring(0, 10));
// calculate the age when a date of birth is entered
$('#dateOfBirth').change(function() {
$('#age').html(getAge()); // and writing it to the page
});
// The eventhandlers for height and weight
$('#height').change(function() {
setBmiAndBsa();
});
$('#weight').change(function() {
setBmiAndBsa();
});
/*
* Why the heck aren't these handlers working?
*
* $('#selectScanner').change(function() {
* selChanged(selectScanner, scanner, selectProtocol);
* });
* $('#selectProtocol').change(function() {
* alert(selectProtocol.options[selectProtocol.selectedIndex].value);
* });
*
* I have to write them like this:
*/
});
selectScanner.onchange = function() {
selChanged(selectScanner, scanner, selectProtocol);
};
selectProtocol.onchange = function() {
alert(selectProtocol.options[selectProtocol.selectedIndex].value);
};</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testpage</title>
</head>
<body>
<div>
<form>
<legend>
Step 1
</legend>
<label><h6>1. Choose Scanner:</h6></label>
<select id="scanner">
<option>choose</option>
<optgroup label="Group 1">
<option value="scanner1">Test Scanner 1</option>
<option value="scanner2">Test Scanner 2</option>
</optgroup>
<optgroup label="Group 2">
<option value="scanner3">Test Scanner 3</option>
<option value="scanner4">Test Scanner 4</option>
</optgroup>
</select>
<label><h6>2. Choose protocol:</h6></label>
<select id="protocols">
<option></option>
</select>
</form>
</div>
<div>
<form>
<legend>Step 2</legend>
<label><h6>Date of Examination:</h6></label>
<input type="date" id="dateOfExam" />
<label><h6>Date Of Birth:</h6></label>
<input type="date"id="dateOfBirth" />
<span>Age: <span id="age"> </span> </span>
<br>
<label><input type="radio" name="optionsRadios" id="genderMale" value="male" checked />male</label>
<label><input type="radio" name="optionsRadios" id="genderFemale" value="female" />female </label>
<br />
<h6>Height [cm] and weight [kg]:</h6>
<input type="number" id="height" name"height" placeholder="cm" >
<input type="number" id="weight" name="weight" placeholder="kg" >
<br>
<span>BSA (Mosteller): <span id="bsa"> </span> </span>
<br>
<span>BMI: <span id="bmi"> </span> </span>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.8.2.min.js"><\/script>')
</script>
<script src="js/main.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T23:54:50.427",
"Id": "31744",
"Score": "0",
"body": "If you're still looking for an answer, can you say whether your code works as intended or not? Are there any specific problems with it, other than the one about jQuery event handlers not working?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-22T00:09:16.197",
"Id": "31745",
"Score": "1",
"body": "Maybe you could also say what your motivation is for making the object `Kof` instead of just, say, having functions `getBMI(cm, kg)` and `getBSA(cm, kg)`, and why you are storing bmi and bsa as global variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-23T16:20:23.197",
"Id": "31774",
"Score": "0",
"body": "Hello Stuart. Thank you for finding, viewing and answering to this question. Of course I'm still interested in any hints how to write better scripts. To answer your questions: The code works like intended, but it is just a snippet out of the project i'm trying to code. About my motivation for making the object Kof: I thought it is a possibility to structure the code a bit more, and it's a component i need on multiple pages. Actually i'm trying to develop a \"patient\" or \"human\" object with a lot of attributes and methods, but I tried to start simple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-23T16:20:52.993",
"Id": "31775",
"Score": "0",
"body": "I used bmi and bsa as global variables because i wanted to separate some logic (mainly generating reports). And that logic (partially in the eventhandlers - i dislike it that way and have to change it) needs to get these values. But while reading more about scripting i just reached the chapter about self invoking anonymous functions - surely I should start using them in some parts. By the way: I changed the structure of the site, so no more selecting scanners and protocols is necessary... Thanks again - Phil."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-23T19:53:32.947",
"Id": "31779",
"Score": "1",
"body": "Okay. Then I have nothing to say about the code, it looks fine to me. I don't see anything 'weird' about it. If Kof becomes a person/patient object you might want to start recording the weight and height as properties of the object `this.cm = cm; this.kg = kg`. I would not bother having the functions `getMosteller` and `getBMI` until/unless you need them. You can write `$('#height').change(setBMIandBSA)` instead of `$('#weight').change(function() { setBmiAndBsa();})`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-24T00:48:46.757",
"Id": "31782",
"Score": "0",
"body": "Thank you. I'll implement your hint. And merry christmas."
}
] |
[
{
"body": "<p>This is only about your HTML as I don't know much about JS. I guess your page will only be used internally by you, so it is not that important, but it may help others that come by.</p>\n\n<ul>\n<li><a href=\"http://www.w3.org/TR/html5/the-legend-element.html#the-legend-element\" rel=\"nofollow\"><code>legend</code></a> must only be used in <a href=\"http://www.w3.org/TR/html5/the-fieldset-element.html#the-fieldset-element\" rel=\"nofollow\"><code>fieldset</code></a></li>\n<li><a href=\"http://www.w3.org/TR/html5/the-label-element.html#the-label-element\" rel=\"nofollow\"><code>label</code></a> can only include \"phrasing content\", so <code>h6</code> is not allowed there (in general I wouldn't use headings inside of the <code>form</code> at all)</li>\n<li>you should \"connect\" the <code>label</code> and it's <code>input</code>/<code>select</code>: with the <a href=\"http://www.w3.org/TR/html5/the-label-element.html#attr-label-for\" rel=\"nofollow\"><code>for</code> attribute</a></li>\n<li>omit <code><option>choose</option></code> as it is (probably) no valid choice</li>\n<li>group the two gender radio boxes in a <code>fieldset</code> with a <code>legend</code> like \"Select gender\"\n<ul>\n<li>same with \"Height [cm] and weight [kg]\" (<code>fieldset</code>><code>legend</code> instead of <code>h6</code>)</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T15:31:24.983",
"Id": "30112",
"Score": "0",
"body": "Tried to fix the points you mentioned above. Thank you again for your help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T17:00:40.163",
"Id": "30123",
"Score": "0",
"body": "Great. I don't think that my answer deserves the green checkmark, because I didn't review your JS. Feel free to give it to someone that might do that in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T17:26:59.923",
"Id": "30127",
"Score": "0",
"body": "I'm a complete newbie regarding posting on stackexchange. I thought it might be a kind of saying: your answer helped me. But I'm going to take a look at the vote / check system of stackexchange. Thanks for the hint."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T11:05:06.373",
"Id": "30159",
"Score": "0",
"body": "@Phil: It also means that you probably don't need any more help, because the checked answer solved all your questions. So it is often a good idea to wait some time for more answers until you accept an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T14:31:10.963",
"Id": "30165",
"Score": "0",
"body": "in the meantime I read about the checking and voting features, but thanks again for clarifying that issue. Phil"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T06:59:15.530",
"Id": "18874",
"ParentId": "18870",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T01:01:23.637",
"Id": "18870",
"Score": "3",
"Tags": [
"javascript",
"performance",
"jquery",
"html5"
],
"Title": "Body mass index / Body surface area calculator"
}
|
18870
|
<p>I am currently trying to learn Haskell (after taking a Scala course on Coursera); but while I can write functions that do what I want, I worry that I am not learning to write idomatic/clean/performant code. I am hoping that this is an acceptable place to receive feedback on how I am progressing. Please let me know if my examples are too small/'toy'/not appropriate for this area of the site.</p>
<p>Which of these two parenthesis matching functions is better - or how best <em>should</em> it be written? The function takes a String, and returns True if the parentheses are balanced, otherwise False.</p>
<pre><code>"(hello)()" = True
")(test()" = False
"())" = False
</code></pre>
<p>Explicitly written:</p>
<pre><code>balance :: String -> Bool
balance xs = bal 0 xs == 0
where bal c [] = c
bal c (x:xs)
| c < 0 = c
| x == '(' = bal (c + 1) xs
| x == ')' = bal (c - 1) xs
| otherwise = bal c xs
</code></pre>
<p>Using foldl:</p>
<pre><code>balance' :: String -> Bool
balance' xs = foldl bal 0 xs == 0
where bal count char
| count < 0 = count
| char == '(' = count + 1
| char == ')' = count - 1
| otherwise = count
</code></pre>
<p>I think that the explicitly-recursing one is better since it will terminate early if it detects the String is flawed, but the other one might be 'clearer' since it uses foldl. Both of them happen to be tail-recursive. How would I improve either?</p>
<p>How important is writing tail-recursive functions in Haskell? I have read somewhere that Haskell is very smart about making things tail recursive, but I do not understand enough to understand quite how.</p>
<p>Any help and suggestions would be greatly appreciated, thank you!</p>
|
[] |
[
{
"body": "<p>I would propose an even less performant solution, but maybe you can improve it...</p>\n\n<pre><code>balance xs = head cumulated == 0 && all (>= 0) cumulated where\n cumulated = scanr (+) 0 $ map depth xs\n depth '(' = -1 \n depth ')' = 1\n depth _ = 0\n</code></pre>\n\n<p>Note that I work \"backwards\" (<code>scanr</code> and inverted parens values) in order to avoid a call to <code>last cumulated</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T21:13:04.363",
"Id": "31300",
"Score": "0",
"body": "How about? `balance xs = all (>=0) (init cumulated) && last cumulated == 0` (`(&&)` checks first argument before right one) and `cumulated = scanl (+) 0 $ map depth xs` (with inverted parenthes). That will not check rest of the string for `\")(test()\"`. Btw, you can use `foldr` since you are using right side."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T08:48:40.170",
"Id": "19248",
"ParentId": "18878",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T09:53:56.657",
"Id": "18878",
"Score": "2",
"Tags": [
"haskell",
"recursion",
"beginner"
],
"Title": "Which of these two paren-matching functions is better?"
}
|
18878
|
<p>I am working on a code snippet to make a function which can be called with an object literal. </p>
<p>Problem area: If I do not need to track the product value, then a check has been placed for undefined. But do I really need to make check for each and every value if it's not there in the object literal?</p>
<pre><code>trackProduct = function (args) {
if(args.label == undefined) {
value.push([args.category, args.action, args.value]);
} else if(args.value == undefined){
value.push([args.category, args.action, args.label]);
} else {
value.push([args.category, args.action, args.label, args.value]);
}
};
</code></pre>
<p>I'm calling this function via below object literal. I have not passed the value parameter. </p>
<pre><code>trackProduct({
category: elemcategory,
action: elemaction,
label: elemlabel
});
</code></pre>
<p>Do we need to check for undefined for all three parameters? Any suggestions on how to improve this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T10:43:33.687",
"Id": "30095",
"Score": "0",
"body": "Are you using jQuery?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T10:44:12.490",
"Id": "30096",
"Score": "0",
"body": "You are using array to store different things, that doesn't make sense. You should just `value.push( args )`"
}
] |
[
{
"body": "<p>First, just a note: You check against <code>undefined</code>, but <code>undefined</code> is unfortunately <em>not</em> a keyword, meaning it's mutable. Better to use <code>typeof something === 'undefined'</code></p>\n\n<p>If I understand you right, you want to be able to \"leave out\" anyone of the object values. In that case, here's my take on the code (I'm returning an array, just for clarity)</p>\n\n<pre><code>function trackProduct(obj) {\n var keys = ['category', 'action', 'label', 'value'], // properties to look for\n values = [],\n i, l, value;\n\n for(i = 0, l = keys.length ; i < l ; i++) {\n value = obj[keys[i]];\n if(typeof value !== 'undefined') {\n values.push(value); // if the value's there, put it in the array\n }\n }\n\n return values;\n}\n</code></pre>\n\n<p>This would work like so:</p>\n\n<pre><code>trackProduct({\n category: \"foo\",\n label: \"bar\",\n value: \"23\",\n ignored: \"something\"\n}); // => [\"foo\", \"bar\", \"23\"]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-09T12:47:43.710",
"Id": "93580",
"Score": "0",
"body": "Not referencing the builtin `undefined` variable because it's mutable is equivalent of not calling any of the builtin functions (like `Array.push()`) because these too are mutable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-09T14:57:06.343",
"Id": "93597",
"Score": "0",
"body": "@ReneSaarsoo I see your point, but I stand by mine. The point is that `undefined` _isn't_ a built-in variable in some runtimes. Saying `x === undefined` only works in those cases precisely because the variable doesn't exist at all, and thus it's not defined (neither natively or in the code being run). In those cases, the ability to define it only spells trouble; you can't (re)define it without making it, well, defined. Conversely you can redefine `Array.prototype.push` in limitless ways without necessarily breaking it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-09T15:35:57.520",
"Id": "93604",
"Score": "0",
"body": "Maybe you could point out some examples of the runtimes where `undefined` variable is missing, because frankly, I don't know any."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-09T16:43:07.923",
"Id": "93621",
"Score": "0",
"body": "@ReneSaarsoo I'm not about to update an old answer when it's still perfectly valid. [But look at this SO answer](http://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript) and the one below it which argues your case. _In effect_, the `undefined` variable is missing in _all_ runtimes - that's the point. That's what makes it \"not defined\". The difference is whether the variable name `undefined` is _writable_ or not. In modern browsers (ECMAScript 5), it isn't, but in older ones it is. See also [MDN](http://mzl.la/SsajwO)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-10T06:20:37.737",
"Id": "93711",
"Score": "0",
"body": "No, the `undefined` variable is actually defined, just that it's value is `undefined`. It's confusing, but you can easily test it by calling `window.hasOwnProperty('undefined')`. You can also easily declare your own undefined variable by simply declaring `var undefined;` in local scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-10T12:35:47.410",
"Id": "93739",
"Score": "0",
"body": "@ReneSaarsoo Ok, yes, it's defined as being not defined, and yes, confusing. Also irrelevant. If the name's writable, there's no difference between saying `x === undefined` and `x === someRandomVarThatDoesntExist`. I prefer using `typeof x === 'undefined'` over that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-11T06:36:43.487",
"Id": "93928",
"Score": "0",
"body": "No, no. There is a major difference - the latter one doesn't work. If I do `x === someRandomVarThatDoesntExist` I'll get an error because I'm attempting to reference a not existing variable. I however I compare `x === undefined` it will work because variable `undefined` is defined, but hasn't been assigned a value, so it's value is `undefined`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-11T09:44:09.927",
"Id": "93941",
"Score": "0",
"body": "@ReneSaarsoo You're right, my mistake. I was thinking of function arguments that are declared by not passed (no ref error, but still undefined)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T13:42:18.960",
"Id": "18886",
"ParentId": "18879",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18886",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T10:32:21.610",
"Id": "18879",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Making a function which can be called with an object literal"
}
|
18879
|
<p>I am using this code to display the recent post from my subdomain to my main domain. I got it after spending 6-7 hours. Now I need to show the avatar image and username of the user of has posted the questions on questions.admissiontimes.com. Right now, it's coming in green and black.</p>
<pre><code>function print_requested_template_part() {
// Respond only to requests from the same address...
if ( $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
$part = $_GET['load_part'];
$func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
if ( function_exists($func) ) {
// Allow for passing parameters to the function
if ( isset($_GET['params']) ) {
$params = $_GET['params'];
$params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
call_user_func_array($func, $params);
} else {
call_user_func($func);
}
}
exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
}
}
add_action('init', 'print_requested_template_part', 1);
function render_my_recent_posts( $numberposts = 5 ) { ?>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul><?php
}
</code></pre>
|
[] |
[
{
"body": "<p>Take a look at <code>filter_input()</code>. It allows you to sanitize and validate GET/POST variables whether they exist or not. If no variable in that scope exists it will be set to FALSE/NULL which means all you have to do is set it to a variable and ensure it has a value.</p>\n\n<pre><code>$tempPart = filter_input( INPUT_GET, 'including_template_part', FILTER_SANITIZE_STRING );\n$part = filter_input( INPUT_GET, 'load_part', FILTER_SANITIZE_STRING );\nif( $tempPart && $part ) {\n</code></pre>\n\n<p>You should avoid internal comments. Internal comments adds clutter to your code and if overused can make your code difficult to read. If your code is self documenting most comments become unnecessary. Anything else should be limited to doccomments.</p>\n\n<p>Ternary statements are good if used properly, but they can become difficult to read if they get too large or if you nest them. Try to keep your ternary statements short and uncomplicated. Here for instance, it is not even necessary. <code>explode()</code> will return an array with the string as the only element if the delimiter does not exist. So you can just call <code>explode()</code> immediately to the same effect.</p>\n\n<pre><code>$params = explode( ',', $params );\n</code></pre>\n\n<p>You should avoid using <code>exit</code> or <code>die()</code> to force your program to stop. It is inelegant. If you must stop execution use a return or throw an error.</p>\n\n<p>There is a principle called the arrow anti-patern. It dictates that you should avoid having heavy/unnecessary indentation in your code to aid in legibility. To avoid violating it you should return early from your statements or refactor them so that only small portions of code are indented. Returning early sometimes also makes else statements unnecessary. If we reverse that first if statement we can return early allowing us to remove an entire level of indentation from our function.</p>\n\n<pre><code>if( ! $tempPart || ! ! $part ) {\n return FALSE;//or throw error\n}\n\n//rest of function here...\n</code></pre>\n\n<p>Your second function has a <code>$numberposts</code> argument that is unused. You immediately create an array with the same values though. If you need to do something like this you should either immediately inject it that way or you can use <code>compact()</code> to the same effect.</p>\n\n<pre><code>$args = compact( 'numberposts' );\n</code></pre>\n\n<p>Now, as to your problem with the images. Since they are originating on another part of your domain, I would hazard to guess that the path to said images is not being updated for the new domain path. This means that you will need to somehow modify the path you are given to reflect the differences. Seen as none of the code you provided has images in it I have no idea what the culprit is.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T20:55:00.640",
"Id": "19855",
"ParentId": "18882",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T12:06:05.143",
"Id": "18882",
"Score": "2",
"Tags": [
"php"
],
"Title": "Image placed with username in recent post of WordPress"
}
|
18882
|
<p>I've written a hash-table implementation. This is the first time I've written such code. The hash-table uses open-addressing with linear probing. The hash function is still subject to change as I found out some properties of it that make it particulary bad for my application.</p>
<p>Could you please review the code and tell me if there are any problems? You can find the code at <a href="http://goo.gl/jivQn" rel="nofollow">GitHub</a>.</p>
<h2>Code</h2>
<p>The code consists of a <code>Makefile</code>, a source file file <code>ht.c</code> and a header file <code>ht.h</code>. The file main.c is a simple test program that reports the amount of entries moved on average to fill in entries into a hashtable at least twice the size of the entries.</p>
<h3>Makefile</h3>
<pre><code>OUT=main
OBJ=ht.o main.o
$(OUT): $(OBJ)
.PHONY: clean
clean:
$(RM) $(OBJ) $(OUT)
</code></pre>
<h3>ht.c</h3>
<pre><code>/* hash table */
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include "ht.h"
struct ht {
int bits;
uint32_t randoms[256];
ht_value_t table[];
};
/* state for xorshift rng */
static uint32_t xstate = 0;
#define BITMASK(bits) ((bits) == 32 ? 0xffffffff : (1<<(bits))-1)
#define MODINC(bits,index) (((index)+1) & BITMASK(bits))
static void init_xorshift(void) {
if (xstate == 0) xstate = time(NULL);
}
static uint32_t xorshift(void) {
xstate ^= xstate << 13;
xstate ^= xstate >> 17;
xstate ^= xstate << 5;
return xstate;
}
static uint32_t hash(ht_t *ht,ht_key_t key) {
union { ht_key_t key; uint8_t bytes[8]; } ukey;
int i;
uint32_t accum = 0;
ukey.key = key;
for (i=0;i<8;i++) accum ^= ht->randoms[ukey.bytes[i]];
return accum;
}
/* tweakable based on actual way to retrieve key */
static ht_key_t get_key(ht_value_t val) {
return *val;
}
ht_t *ht_new(int bits) {
ht_t *ht;
int i,bitmask;
if (bits < 0 || bits >= 32) return NULL;
ht = malloc(sizeof*ht + (1<<bits)*sizeof*ht->table);
ht->bits = bits;
init_xorshift();
/* initiate hash function */
bitmask = BITMASK(bits);
for (i=255;i>=0;i--) ht->randoms[i] = xorshift()&bitmask;
memset(ht->table,0,1<<bits);
return ht;
}
void ht_free(ht_t *ht) {
free(ht);
}
int ht_put(ht_t *ht,ht_key_t key,ht_value_t value) {
uint32_t index = hash(ht,key);
ht_value_t tmp;
int iters = 0;
while (ht->table[index] != NULL && get_key(ht->table[index]) != key) {
tmp = ht->table[index];
ht->table[index] = value;
index = MODINC(ht->bits,index);
value = tmp;
iters++;
}
ht->table[index] = value;
return iters;
}
int ht_del(ht_t *ht,ht_key_t key) {
uint32_t hkey = hash(ht,key), index, tindex;
ht_key_t ckey;
int iters = 0;
for (index = hkey;;index = MODINC(ht->bits,index)) {
if (ht->table[index] == NULL) return -1;
ckey = get_key(ht->table[index]);
if (hash(ht,ckey) != hkey) return -1;
if (ckey == key) break;
}
ht->table[index] = NULL;
while(ht->table[index]!=NULL&&hash(ht,get_key(ht->table[index]))==hkey){
tindex = index;
index = MODINC(ht->bits,index);
ht->table[tindex] = ht->table[index];
ht->table[index] = NULL;
iters++;
}
return iters;
}
ht_value_t ht_get(ht_t *ht,ht_key_t key) {
uint32_t hkey = hash(ht,key), index = hkey, ckey;
while (ht->table[index] != NULL
&& hash(ht,ckey = get_key(ht->table[index])) == hkey) {
if (ckey == key) return ht->table[index];
index = MODINC(ht->bits,index);
}
return NULL;
}
</code></pre>
<h3>ht.h</h3>
<pre><code>/* hash table */
#ifndef HT_H
#define HT_H
typedef struct ht ht_t;
typedef uint64_t ht_key_t;
typedef ht_key_t *ht_value_t;
ht_t *ht_new(int bits);
/* ht_put and ht_del return number of items moved or -1 if key
* already exists (ht_put) / not found (ht_get).
* ht_value_t must point to the same key we used at insertion */
int ht_put(ht_t*,ht_key_t,ht_value_t);
int ht_del(ht_t*,ht_key_t);
ht_value_t ht_get(ht_t*,ht_key_t);
void ht_free(ht_t*);
#endif /* HT_H */
</code></pre>
<h3>main.c</h3>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include "ht.h"
int main(int argc,char *argv[]) {
int count, i, bits=0;
int misses = 0;
ht_key_t *values;
srandom(time(NULL));
if (argc != 2 || sscanf(argv[1],"%d",&count) != 1) return EXIT_FAILURE;
for (i=count;i;bits++)i>>=1;
ht_t *ht = ht_new(bits);
values = malloc(count*sizeof*values);
for (i=count;i>0;i--) {
values[i] = random();
misses += ht_put(ht,values[i],values+i);
}
printf("%.2f\n",misses/(float)count);
return EXIT_SUCCESS;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T20:02:40.443",
"Id": "30143",
"Score": "1",
"body": "We prefer to review code that is on this site. Then comments here will be useful to future users even if the linked site is no longer available."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T20:20:51.387",
"Id": "30146",
"Score": "0",
"body": "@LokiAstari Thank you for the comment. I am going to post the code here ASAP."
}
] |
[
{
"body": "<h3>1. Bugs</h3>\n\n<ol>\n<li><p>The algorithm in <code>ht_get</code> is incorrect:</p>\n\n<pre><code>while (ht->table[index] != NULL\n && hash(ht,ckey = get_key(ht->table[index])) == hkey) {\n if (ckey == key) return ht->table[index];\n index = MODINC(ht->bits,index);\n}\n</code></pre>\n\n<p>You are assuming here that if you find a key with a different hash in your probe sequence, then this means that the key you are looking for is not there. But that's not right. Try the following test program:</p>\n\n<pre><code>#include <stdint.h>\n#include <stdio.h>\n#include \"ht.h\"\n#define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0]))\nint main(int argc, char *argv[]) {\n uint64_t k[] = {0x12345671, 0x11223344, 0x22334411, 0x33441122};\n ht_t *ht = ht_new(2);\n for (size_t i = 0; i < ARRAY_LENGTH(k); ++i) {\n ht_put(ht, k[i], &k[i]);\n }\n printf(\"%p\\n\", ht_get(ht, k[0]));\n return 0;\n}\n</code></pre>\n\n<p>You'll need to run it a few times (because of the randomization in your hash function), but I find that about half the time this prints <code>0x0</code> because <code>k[0]</code> failed to be found in the hash table (even though it must be there since it was the first key that was added).</p></li>\n<li><p>The algorithm in <code>ht_del</code> is also incorrect. As Knuth writes, \"Many computer programmers have great faith in algorithms, and they are surprised to find that <em>the obvious way to delete records from a hash table doesn't work</em>.\" (<em>The Art of Computer Programming</em> Vol. III, p. 533.)</p>\n\n<p>First, here:</p>\n\n<pre><code>for (index = hkey;;index = MODINC(ht->bits,index)) {\n if (ht->table[index] == NULL) return -1;\n ckey = get_key(ht->table[index]);\n if (hash(ht,ckey) != hkey) return -1; /* <-- UH-OH */\n if (ckey == key) break;\n}\n</code></pre>\n\n<p>On the indicated line you conclude that <code>key</code> can't be in the table because you've found a key with a different hash in your probe sequence. But this isn't right: there might very well be keys with different hashes interleaved in the same probe sequence (this is particularly likely in your case because you use the same probe sequence for every key).</p>\n\n<p>Second, after deleting the key you continue with the probe sequence, shifting the keys along so that there are no gaps. But this is wrong: if any of those keys have different hashes to <code>key</code>, then moving them can cause them not to be findable any more.</p>\n\n<p>If you want to get this right, Knuth gives an algorithm (pp. 533–4) for deletion in a open hash table with linear probing, but since linear probing is itself not a particularly good idea (see 2.3 below), it's better to do what most open hash table implementations do, which is to <em>mark a key as deleted</em> by putting a placeholder (some constant <code>KEY_DELETED</code>) in its place. (Combined with automatic growing and rehashing; see 2.4 below.)</p></li>\n<li><p>If the table gets full, then <code>ht_put</code> will go into an infinite loop.</p>\n\n<p>Also, if the table is full, and if all the keys have the same hash, then <code>ht_get</code> and <code>ht_del</code> will go into infinite loops.</p>\n\n<p>It's best to avoid all these problems by automatically growing and rehashing before the table gets full. See 2.4 below.</p></li>\n</ol>\n\n<h3>2. Other important issues</h3>\n\n<ol>\n<li><p>It's not easy to choose a good general-purpose hash function, so it's a bad sign that you are trying to invent your own. It would be much better to choose a well-known and well-tested function, for example from <a href=\"http://en.wikipedia.org/wiki/List_of_hash_functions\" rel=\"nofollow noreferrer\">Wikipedia's list of hash functions</a>. For general data, <a href=\"http://www.cse.yorku.ca/~oz/hash.html\" rel=\"nofollow noreferrer\">Bernstein's hash</a> is simple and fast; and for integers there's <a href=\"https://cstheory.stackexchange.com/q/9639/2114\">Knuth's multiplicative hash</a>.</p>\n\n<p>In particular, the hash function you have chosen has a couple of undesirable properties:</p>\n\n<ol>\n<li><p>A byte makes the same contribution to the hash wherever it appears in the key, so that all permutations of a sequence of bytes have the same hash. For example, <code>0x11223344</code> has the same hash as <code>0x44332211</code> and <code>0x22441133</code>.</p></li>\n<li><p>Pairs of bytes in the key with the same value do not contribute to the hash (because their hashes cancel). So <code>0x1212</code> has the same hash as <code>0x3434</code> and <code>0x5656</code>, not to mention <code>0x0000</code> and many other keys.</p></li>\n</ol></li>\n<li><p>You base the hash function on a pseudo-random sequence seeded by the current time. Varying the hash function like this has an important downside: it makes the code harder to test because the behaviour changes from run to run. So why are you doing this?</p>\n\n<p>I can only guess that you are doing this because you want your hash table to be robust against the <a href=\"http://www.cs.rice.edu/~scrosby/hash/CrosbyWallach_UsenixSec2003.pdf\" rel=\"nofollow noreferrer\">collision attack</a>. But if so, your remedy won't be effective, because:</p>\n\n<ol>\n<li><p>Your choice of hash function makes it trivial to construct large numbers of colliding keys (see above) regardless of the seed;</p></li>\n<li><p><code>time</code> only has resolution in seconds, so it is likely that an attacker will be able to guess or reconstruct your seed value;</p></li>\n<li><p>32 bits of randomness are well within the scope of a brute force search in any case.</p></li>\n</ol>\n\n<p>If you really need to be robust against the collision attack you need a robust hash function, a secure source of randomness, and substantially more than 32 bits of randomness. See section 5 of <a href=\"http://www.cs.rice.edu/~scrosby/hash/CrosbyWallach_UsenixSec2003.pdf\" rel=\"nofollow noreferrer\">Crosby & Wallach</a>.</p></li>\n<li><p>Linear probing is well known to be bad. Knuth writes, \"Experience with linear probing shows that the algorithm works fine until the table begins to get full; but eventually the process slows down, with long drawn-out searches becoming increasingly frequent.\" (<em>The Art of Computer Programming</em>, vol. III, p. 527).</p>\n\n<p>To avoid this, you should use a different probe sequence for each key. See Knuth pp. 528–531.</p></li>\n<li><p>Your hash table is fixed in size, so it's going to perform worse and worse as it gets full. In a few applications, this might not matter because you know how big your hash table is going to be at the start. But for most applications you don't know this, and so it's important to be able to grow and rehash the table automatically when it gets full enough that its performance degrdes significantly.</p></li>\n<li><p>When you get a collision in <code>ht_put</code>, you store the new value at the location and move the old value to the next location in the probe sequence (possibly shifting a whole sequence of keys along as you go).</p>\n\n<p>If you have a reason for this, you ought to explain it. I suppose it makes the newly inserted value quicker to retrieve, but (a) this seems likely to be bad for cache performance (it unnecessarily dirties all the locations visited by the probe sequence); and (b) if you are getting lots of collisions, it's better to grow the table (see 2.4 above) than to mess about like this.</p></li>\n</ol>\n\n<h3>3. Minor issues</h3>\n\n<ol>\n<li><p>There are very few comments. Someone reading the code would like to know explanations for your design decisions. Here are a few questions I would have liked to be answered by appropriate comments:</p>\n\n<ol>\n<li><p>What is the role of <code>bits</code> in the hash table structure? (Answer: the table size is always a power of two, and <code>bits</code> gives the logarithm of the size.)</p></li>\n<li><p>What is the role of <code>randoms</code> in the hash table structure? (Answer: some of them are exclusive-ored to make the hash.) But why does each hash table need its own set?</p></li>\n<li><p>What is the purpose of seeding the <code>random</code> array from the clock? (Possible answer: because you don't want the hash function to be computable by an attacker?)</p></li>\n<li><p>Why is <code>xstate</code> a global variable? Why does each hash table need to have a different sequence of pseudo-random numbers?</p></li>\n<li><p>Why do you generate the pseudo-random numbers in reverse order?</p></li>\n</ol></li>\n<li><p>There are a few poorly chosen names. Generally it's best to pick a name for a function that describes the <em>purpose</em> of the function. For example, although <code>MODINC</code> does compute a modulus and an increment, that's pretty useless thing to know. What you actually <em>use</em> it for is to generate the probe sequence. So a better name would something like <code>NEXT_INDEX</code>.</p></li>\n<li><p>What are you planning to use this hash table for? It appears to implement a <em>set</em> of unsigned integers (that is, there are unsigned integer keys, but no values). This is fine if that's what you need, but it's not really very general.</p></li>\n<li><p>Each hash table structure stores 1024 bytes of pseudo-random data in addition to the table. This will create a lot of space overhead in applications that use many small tables. (For example, some dynamic programming languages, notably Python, represent objects as a hash table mapping attribute name to attribute value. It would be disastrous to have 1 KiB of overhead on every object.)</p></li>\n<li><p>There are some mysterious integer constants in the code whose purpose would be clearer if you explicitly showed how you computed them.</p>\n\n<ol>\n<li><p>Why 256?</p>\n\n<pre><code>uint32_t randoms[256];\n</code></pre>\n\n<p>This needs one entry for each possible value of a byte, so <code>#include <limits.h></code> and write <code>1 << CHAR_BIT</code>.</p></li>\n<li><p>Why 8?</p>\n\n<pre><code>union { ht_key_t key; uint8_t bytes[8]; } ukey;\n</code></pre>\n\n<p>This needs to be the size of <code>key</code> in bytes, so write <code>sizeof(ht_key_t)</code>.</p></li>\n<li><p>Why 8 here?</p>\n\n<pre><code>for (i=0;i<8;i++) accum ^= ht->randoms[ukey.bytes[i]];\n</code></pre>\n\n<p>This needs to be the number of elements in <code>ukey.bytes</code>, so I suggest defining a macro:</p>\n\n<pre><code>#define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0]))\n</code></pre>\n\n<p>and then writing <code>ARRAY_LENGTH(ukey.bytes)</code>.</p></li>\n<li><p>Why 255 here?</p>\n\n<pre><code>for (i=255;i>=0;i--) ht->randoms[i] = xorshift()&bitmask;\n</code></pre>\n\n<p>This needs to be the number of elements in <code>ht->randoms</code>, less 1, so write <code>ARRAY_LENGTH(ht->randoms) - 1</code>.</p></li>\n</ol></li>\n<li><p>Since <code>ht.h</code> depends on <code>stdint.h</code> (for the definition of <code>uint64_t</code>), it ought to include it.</p></li>\n<li><p>You represent an index into the hash table with a <code>uint32_t</code>. This restricts your hash table to 2<sup>32</sup> entries, even on 64-bit platforms, and means that you need an ugly special case in the <code>BITMASK</code> macro. Why not use <code>size_t</code> for the index into the hash table and drop the special case? A similar remark applies to the hash values: there's no particular reason to restrict these to 32 bits either.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T17:51:55.080",
"Id": "30217",
"Score": "0",
"body": "Thank you for the commentary. I am going to go through all errors and fix them, especially the parts where my code is wrong. The hash table is going to be used in a data-compression program where an upper bound on the number of entries is known beforehand. I am planning to make the hashtable twice the size I need. The hash-function really is problematic, the function I use here was suggested somewhere on Wikipedia. The index to the hashtable is a set of two 32-bit symbols and the value is a pointer to such a set. Thank you really much for this deep review!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T20:44:07.073",
"Id": "30226",
"Score": "0",
"body": "Aha! That's exactly the kind of useful information that explains why you've made some of your design decisions. You might want to copy it into a comment at the head of the source code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T22:54:41.580",
"Id": "30232",
"Score": "1",
"body": "It looks to me as though you were trying to do [tabulation hashing](http://en.wikipedia.org/wiki/Tabulation_hashing), but you missed these bits in bold: \"The initialization phase of the algorithm creates a **two-dimensional** array T of dimensions 2^r **by t**\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T23:16:48.883",
"Id": "30233",
"Score": "0",
"body": "That makes sense. I am sorry for not providing enough information to really answer the question. Do you have a better idea for a hash function? I did also think about using a few iterations of the xorshift random number generator as it yields good distribution without any extra memory needed. Also, one iteration can be calculated in about 6 instructions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T21:08:10.490",
"Id": "30328",
"Score": "0",
"body": "Don't try to invent your own: use a standard hash function. If you need to be robust against the collision attack (and if the space overhead is acceptable) then [tabulation hashing](http://en.wikipedia.org/wiki/Tabulation_hashing) is fine (but you have to fix your implementation, as I pointed out in my comment above; also you only need one set of pseudo-random numbers, not one per hash table). If you don't care about the collision attack, try [MurmurHash](http://en.wikipedia.org/wiki/MurmurHash) — it operates on 32-byte chunks so it's ideal for your case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-10T09:31:31.723",
"Id": "100788",
"Score": "0",
"body": "You need a hash, at least as strong as tabulation hashing, if you want to use open addressing. This problem has been studied extensively, and not understanding this has let many people to dislike open addressing."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T14:24:05.563",
"Id": "18932",
"ParentId": "18883",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18932",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T12:08:56.173",
"Id": "18883",
"Score": "5",
"Tags": [
"c",
"hash-map"
],
"Title": "Hash table using open-addressing with linear probing"
}
|
18883
|
<p>I have a class like this one:</p>
<pre><code>class EmailClass
{
public string MailAdresse { get; set; }
public string MailAdresseCC { get; set; }
}
</code></pre>
<p>Through a JSON deserialization I obtain a <code>List<EmailClass></code> and two other strings <code>anotherMailAddress</code> and <code>justAnotherMailAddress</code>.</p>
<p>I need to join all those adresses in one big string (the separator is ";"). For this purpose I wrote this code:</p>
<pre><code>// this one is populated in another section but it
// is put there for the sake of knowing the variable name
List<EmailClass> splittedList
List<string> listOfAdresses = new List<string>();
string joinedAdresses = String.Empty;
listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresse));
listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresseCC));
listOfAdresses.Add(anotherMailAddress);
listOfAdresses.Add(justAnotherMailAdresses);
joinedAdresses = String.Join(";", listOfAdresses.Distinct().ToArray());
</code></pre>
<p>Now, is there a more polished way to obtain this result?
How much will <code>Distinct()</code> affect the performance on medium result set (~100.000 adresses)? I've read that the complexity of the function should be O(n), is this true?</p>
|
[] |
[
{
"body": "<p>Use a <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\">HashSet</a> then it will only contain unique values, duplicates will be discarded when calling <code>Add</code> based upon the hashcode of the string. This should be far more efficient than calling <code>Distinct</code>.</p>\n\n<pre><code>List<EmailClass> splittedList\n\nHashSet<string> listOfAdresses = new HashSet<string>();\n\n// HashSet does not contain an AddRange method.\nforeach (var emailClass in splittedList)\n{\n listOfAdresses.Add(emailClass.MailAdresse);\n listOfAdresses.Add(emailClass.MailAdresseCC);\n}\n\nlistOfAdresses.Add(anotherMailAddress);\nlistOfAdresses.Add(justAnotherMailAdresses);\n\nstring joinedAdresses = String.Join(\";\", listOfAdresses.ToArray());\n</code></pre>\n\n<p>--</p>\n\n<p>Following the \"feedback\" from Almaz, here's a basic benchmark to show the performance difference (using unique values for each address):</p>\n\n<pre><code>private static void Main(string[] args)\n{\n List<EmailClass> splittedList = Enumerable.Range(1, 100000).Select(i => new EmailClass\n {\n MailAdresse = i.ToString() + \"@email.com\",\n MailAdresseCC = i.ToString() + \"cc@email.com\"\n }).ToList();\n\n OriginalMethod(splittedList);\n HashSetMethod(splittedList);\n LinqMethod(splittedList);\n\n Console.ReadLine();\n}\n\nprivate static void OriginalMethod(List<EmailClass> splittedList)\n{\n var sw = new Stopwatch();\n sw.Start();\n List<string> listOfAdresses = new List<string>();\n\n listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresse));\n listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresseCC));\n listOfAdresses.Add(\"someone@email.com\");\n listOfAdresses.Add(\"someone.else@email.com\");\n var joinedAdresses = String.Join(\";\", listOfAdresses.Distinct().ToArray());\n sw.Stop();\n Console.WriteLine(\"OriginalMethod\");\n Console.WriteLine(sw.Elapsed);\n}\n\nprivate static void HashSetMethod(List<EmailClass> splittedList)\n{\n var sw = new Stopwatch();\n sw.Start();\n HashSet<string> listOfAdresses = new HashSet<string>();\n\n foreach (var emailClass in splittedList)\n {\n listOfAdresses.Add(emailClass.MailAdresse);\n listOfAdresses.Add(emailClass.MailAdresseCC);\n }\n\n listOfAdresses.Add(\"someone@email.com\");\n listOfAdresses.Add(\"someone.else@email.com\");\n\n string joinedAdresses = String.Join(\";\", listOfAdresses.ToArray());\n sw.Stop();\n Console.WriteLine(\"HashSetMethod\");\n Console.WriteLine(sw.Elapsed);\n}\n\nprivate static void LinqMethod(List<EmailClass> splittedList)\n{\n var sw = new Stopwatch();\n sw.Start();\n var emails = splittedList.SelectMany(emailClass => new[] { emailClass.MailAdresse, emailClass.MailAdresseCC })\n .Concat(new[] { \"someone@email.com\", \"someone.else@email.com\" })\n .Distinct();\n\n var joinedAdresses = String.Join(\";\", emails);\n sw.Stop();\n Console.WriteLine(\"LinqMethod\");\n Console.WriteLine(sw.Elapsed);\n}\n</code></pre>\n\n<p>Results run in release mode without debugger attached:</p>\n\n<pre><code>OriginalMethod: 00:00:00.0789540\nHashSetMethod: 00:00:00.0488568\nLinqMethod: 00:00:00.0668056\n</code></pre>\n\n<p>Ramping up to 1,000,000 items</p>\n\n<pre><code>OriginalMethod: 00:00:00.8189667\nHashSetMethod: 00:00:00.6891028\nLinqMethod: 00:00:01.0157357\n</code></pre>\n\n<p>As you can see, the HashSet approach is substantially faster than the OP and significantly faster than the Linq approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T17:26:25.800",
"Id": "30126",
"Score": "0",
"body": "Actually Distinct does almost the same, so your solution won't be faster then pure iteration over \".Distinct\". See my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T11:24:23.617",
"Id": "30303",
"Score": "0",
"body": "Won't the hash set mess up the order of the strings?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T14:11:52.960",
"Id": "18887",
"ParentId": "18884",
"Score": "14"
}
},
{
"body": "<p>Solution can be optimized even further in terms of readability, with the same level of performance as \"manually create a HashSet and populate it with items\":</p>\n\n<pre><code>var emails = splittedList.SelectMany(emailClass => new[] { emailClass.MailAdresse, emailClass.MailAdresseCC})\n .Concat(new[] {anotherMailAddress, justAnotherMailAdress})\n .Distinct();\nvar joinedAdresses = String.Join(\";\", emails);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T18:54:33.843",
"Id": "30137",
"Score": "2",
"body": "You can argue readability either way, fewer lines of code does not necessarily mean more readable. Also, this method will result in creating an array for every item in the source list which is completely unnecessary!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T20:13:48.803",
"Id": "30145",
"Score": "0",
"body": "you can always do .Select(emailClass=>emailList.MailAdresse).Concat(splittedList.Select(emailClass=>emailList.MailAdresseCC)) to avoid creating arrays..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T20:40:12.810",
"Id": "30147",
"Score": "0",
"body": "You could, but then you have to enumerate `splittedList` twice. Once to select the `EmailAddresse` and a second time to select the `EmailAddresseCC` which isn't an optimisation either as you're doing twice as much work! Linq isn't the answer to everything, just because you _can_ use it, doesn't mean you _should_ :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T09:35:44.003",
"Id": "30157",
"Score": "0",
"body": "I suggested another approach that (on my opinion) is more readable, expressive and compact. It declares what you want to do instead of how you want it to be done. Optimizing microseconds here is just a premature optimization, no-one will ever build a string containing a million of emails."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T17:26:03.197",
"Id": "18893",
"ParentId": "18884",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T12:55:15.143",
"Id": "18884",
"Score": "11",
"Tags": [
"c#",
"performance",
"linq",
"strings"
],
"Title": "String join of distinct string"
}
|
18884
|
<p>My alghoritm works and produces good result, but it takes too much time(6 s for 300 input items that is too much for branch and bound alghoritm), so I have maken a mistake somewhere, but really can't find it :( It is supposed to be depth-first branch and bound. Any help would be appreciated!</p>
<pre><code>public void knapsack2(Item[] items, int maxWeight)
{
Item firstNode, secondNode, tempNode;
int weight, bestValue = 0, bestWeight = 0;
Stack stack = new Stack();
firstNode = items[0];
firstNode.setBound(bound(firstNode, maxWeight, items));
stack.push(firstNode);
Item bestNode = firstNode;
while(!stack.isEmpty())
{
tempNode = (Item) stack.pop();
weight = tempNode.getWeight();
if( tempNode.getBound() > bestValue)
{
firstNode = new Item();
firstNode.setLevel(tempNode.getLevel() + 1);
firstNode.setValue(tempNode, items[firstNode.getLevel()].getValue());
firstNode.setWeight(weight + items[firstNode.getLevel()].getWeight());
firstNode.setBound(bound(firstNode, maxWeight, items));
if(firstNode.getValue() > bestValue && firstNode.getWeight() <= maxWeight)
{
bestValue = firstNode.getValue();
bestWeight = firstNode.getWeight();
bestNode = firstNode;
}
if(firstNode.getBound() > bestValue)
{
stack.push(firstNode);
}
secondNode = new Item();
secondNode.setLevel(tempNode.getLevel() + 1);
secondNode.setValue(tempNode, 0);
secondNode.setWeight(weight);
secondNode.setBound(bound(secondNode, maxWeight, items));
if(secondNode.getBound() > bestValue)
{
stack.push(secondNode);
}
}
}
System.out.println("Best value " + bestValue);
}
</code></pre>
<p>Bound function:</p>
<pre><code> public float bound(Item item, int maxWeight, Item[] items)
{
int j, k;
int totalWeight;
float result;
if(item.getWeight() > maxWeight)
{
return 0;
}
else
{
result = item.getValue();
j = item.getLevel() + 1;
totalWeight = item.getWeight();
while(j < items.length && (totalWeight + items[j].getWeight() <= maxWeight))
{
totalWeight += items[j].getWeight();
result += items[j].getValue();
j++;
}
}
k = j;
if(k < items.length)
{
result = result + (maxWeight - totalWeight) * (items[k].getValue() / (float) items[k].getWeight());
return result;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T15:32:59.780",
"Id": "30113",
"Score": "2",
"body": "Out of curiosity -- what does that node object look like?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T17:19:36.337",
"Id": "30125",
"Score": "0",
"body": "Just setters and getters, does nothing actually."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T22:14:54.143",
"Id": "30152",
"Score": "0",
"body": "Could you post a complete example (300 objects) - it could be just a memory allocation problem because b&b needs a lot of objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T18:45:20.260",
"Id": "30222",
"Score": "1",
"body": "profile it and debug it. either with a profiler and debugger, or with print and System.currentTimeMillis() statements."
}
] |
[
{
"body": "<p>Branch&Bounding is not what you have implemented (at least I can't see the classic algorithm in there).</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Branch_and_bound\" rel=\"nofollow\">Branch And Bound is normally implemented</a> as a recursive process. I don't see recursion here. Additionally, even if the recursion is unwound to your while loop, I can't see where the efficient Branching happens.... frankly, it's a bit confusing.</p>\n\n<p>Additionally, as I read your code, I believe there is a bug in that your solution will always contain items[0] (the firstNode is always pushed to the stack, and the code completes when it is popped....).</p>\n\n<p>The general solution for the knapsack algorithm is to try every combination of items and find ones that fit. This is a 'combination' problem. Using recursion to find combinations is quite easy, and it is well defined using the 'branch' part of Branch and Bound.</p>\n\n<p>The Bound part of the problem is that you can eliminate whole branches based on the known state of the knapsack at that branch (i.e. adding anything more from that branch will cause the conditions to fail, so you can 'prune' the whole branch). The Bound part makes the Branch part more efficient.</p>\n\n<p>I believe the Branch-side of your code is broken, so the Bounds-part comes later (when you have revised/reposted the branch side).</p>\n\n<p>Working on the branch side of things, the easiest thing to do is to have recursion in a for-loop......</p>\n\n<p>I recommend passing a 'Branch' Object back from the recursive method, and stipulating a target weight for the branch:</p>\n\n<pre><code>public Branch branch(Item[] items, int fromposition, int target) {\n if (fromposition >= items.length) {\n return null;\n }\n Branch best = null;\n for (int i = fromposition + 1; i < items.length; i++) {\n Branch current = new Branch(items[i]);\n // note that the recursion happens from fromposition+1\n current.addAll(branch(items, i, target - items[i].weight));\n if (current.weight <= target) {\n best = (best == null || current.weight > best.weight) ? current : best;\n }\n }\n return best;\n}\n</code></pre>\n\n<p>With the above code we calculate the 'weight' of the Branch, and we compare that to the capacity remaining in the knapsack. If we compare every combination with our knapsack we would find the solution, but not in the most efficient way. This does the <strong>Branch</strong> but nothing about <strong>Bounds</strong>.</p>\n\n<p>To compute the bounds there are a few solutions.... but, <strong>starting off with sorted items</strong> leads to the most efficient solutions.... so, sort your items in ascending order.</p>\n\n<p>Then, your Bounds solution becomes the simple addition of a couple of constraints:</p>\n\n<p>change:</p>\n\n<pre><code>for (int i = fromposition + 1; i < items.length; i++) {\n</code></pre>\n\n<p>to</p>\n\n<pre><code>for (int i = fromposition + 1; i < items.length && items[i].weight <= target; i++) {\n</code></pre>\n\n<p>Now we stop checking our branches the moment we find that the next option is too large, and we can skip processing anything after that item because our data is sorted, and we know that the rest of the stuff is even heavier.</p>\n\n<p>Another bound we can add is to stop checking when we find a perfect solution:</p>\n\n<pre><code> if (current.weight <= target) {\n best = (best == null || current.weight > best.weight) ? current : best;\n }\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code> if (current.weight == target) {\n return current;\n } else if (current.weight < target) {\n best = (best == null || current.weight > best.weight) ? current : best;\n }\n</code></pre>\n\n<p>I have just typed this in, I have not verified any of the code, but, as you can see, the solution would be:</p>\n\n<pre><code>public void knapsack2(Item[] inputitems, int maxWeight) {\n // take a copy because we will sort the items...\n Item[] items = Arrays.copyOf(inputitems, inputitems.length);\n Arrays.sort(items, new Comparator<Item>() { ... sorts by weight...});\n Branch best = branchAndBound(items, 0, maxWeight);\n\n}\n\npublic Branch branchAndBound(Item[] items, int fromposition, int target) {\n if (fromposition >= items.length) {\n return null;\n }\n Branch best = null;\n for (int i = fromposition + 1; i < items.length; i++) {\n Branch current = new Branch(items[i]);\n // note that the recursion happens from fromposition+1\n current.addAll(branch(items, i, target - items[i].weight));\n if (current.weight <= target) {\n best = (best == null || current.weight > best.weight) ? current : best;\n }\n }\n return best;\n}\n</code></pre>\n\n<p>The Code for the Branch class will need to allow you to track the branch weight, and to add Items to the branch. Then, at the end, return the Items too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-03T00:29:05.027",
"Id": "36541",
"ParentId": "18890",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T15:23:20.557",
"Id": "18890",
"Score": "5",
"Tags": [
"java",
"algorithm",
"performance"
],
"Title": "What is wrong with my knapsack alghoritm?"
}
|
18890
|
<p>(<code>getProperty</code> is the <code>deepCss</code> function from <a href="http://www.webdeveloper.com/forum/showthread.php?166053-Check-if-element-is-visible-when-style-not-set-in-the-tag&p=825130#post825130" rel="nofollow">here</a> and retrieves the current (computed) style of an element).</p>
<pre><code>function toggleElements()
{
for (var i = 0; i < arguments.length; i++) {
$(arguments[i])[0].style.display = (
getProperty($(arguments[i])[0], "display") !== "none"
? "none"
: "inline-block");
}
}
</code></pre>
<p>I use it like this:</p>
<pre><code><div id="searchdiv" onclick="toggleElements('#searchoplus',
'#searchominus',
'#search_simple',
'#search_extended');">
</code></pre>
<p>which will switch on those elements in the list that weren't visible, and switch off those that were.</p>
<p>I guess I can get rid of the for loop and use jQuery's idiomatic chained-expression syntax, but I don't know how.</p>
|
[] |
[
{
"body": "<p>I have found that there are two possibilities.</p>\n\n<h3>1. The literal translation:</h3>\n\n<pre><code>function toggleElements()\n{\n $(arguments).each(function (index, element) {\n $(element)[0].style.display = (\n getProperty($(element)[0], \"display\") !== \"none\"\n ? \"none\"\n : \"inline-block\");\n });\n}\n</code></pre>\n\n<h3>2. Using <code>toggle()</code>:</h3>\n\n<pre><code>function toggleElements()\n{\n $(arguments).each(function (index, element) {\n $(element).toggle();\n });\n}\n</code></pre>\n\n<p>This second version needs a workaround to use the <code>display: inline-block</code> attribute correctly. You need to specify this attribute in your CSS file even for elements which are hidden when the page is loaded, and hide them by setting <code>display: none</code> in the <code>style</code> attribute of the element itself to get the correct behaviour with the jQuery <code>toggle</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T18:50:04.403",
"Id": "30136",
"Score": "1",
"body": "Be careful using [`each()`](http://api.jquery.com/each/), it's only meant for iterating over jQuery objects and can cause problems when used on anything else. [`jQuery.each()`](http://api.jquery.com/jQuery.each/) is the safe alternative :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T18:46:09.910",
"Id": "18894",
"ParentId": "18891",
"Score": "1"
}
},
{
"body": "<p>My jQuery's a bit rusty but if <code>#searchoplus</code>, <code>#searchominus</code>, etc. initially have a display value of <code>inline-block</code> you should be able to get your code down to:</p>\n\n<pre><code>function toggleElements() {\n $.each(arguments, function(index, id) {\n $(id).toggle();\n });\n}\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/toggle/\" rel=\"nofollow\"><code>toggle()</code></a> saves the initial value of the display and puts it back in place when it's re-toggled.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T18:49:54.770",
"Id": "30135",
"Score": "0",
"body": "`searchoplus` and `search_simple` have `display: inline-block` while `searchominus` and `search_extended` initially have `display: none`. See my answer for a workaround."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T18:46:22.830",
"Id": "18895",
"ParentId": "18891",
"Score": "2"
}
},
{
"body": "<p>I'm not certain I understood what you want, but this should at least be a starting point.</p>\n\n<p>I have assumed that \"idiomatic chained-expression syntax\" is referring to chainable methods. In other words you could write this:</p>\n\n<pre><code>setElements('#searchoplus', \n '#searchominus', \n '#search_simple', \n '#search_extended').toggle().doSomethingElse();\n</code></pre>\n\n<p>To accomplish this, you need to create a <strong>function</strong> that <strong>returns an object</strong> that has a <strong>method that also returns the object</strong>.</p>\n\n<pre><code>function setElements(){\n\n //This is the class for creating the object\n function elObj(argumentz){\n\n //This method toggles and then returns the 'elObj' object\n this.toggle=function(){\n for (var i = 0; i < argumentz.length; i++) {\n $(argumentz[i])[0].style.display = (\n document.getProperty($(argumentz[i])[0], \"display\") !== \"none\"\n ? \"none\"\n : \"inline-block\");\n }\n return this;\n }\n\n //This is another method that also returns the object\n this.doSomethingElse=function(){\n console.log(\"Something else\");\n return this; \n }\n }\n\n\n //Create the new object and return it\n return new elObj(arguments);\n\n}\n</code></pre>\n\n<p>Here is the full code:\n<a href=\"http://jsfiddle.net/4Mpcs/7/\" rel=\"nofollow\">http://jsfiddle.net/4Mpcs/7/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T18:57:57.443",
"Id": "30138",
"Score": "0",
"body": "I definitely misunderstood. I was thinking you wanted a non-jQuery solution..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T21:40:56.877",
"Id": "30150",
"Score": "0",
"body": "Just making sure, you don't want to just use `$('#searchoplus,#searchominus,#search_simple,#search_extended')`, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T05:35:47.833",
"Id": "30155",
"Score": "0",
"body": "+1 Well, this is still a valuable answer, even though I was looking for a way to utilize the *existing* power of jQuery."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T18:56:07.683",
"Id": "18896",
"ParentId": "18891",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18895",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T17:07:10.360",
"Id": "18891",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "JS element toggling"
}
|
18891
|
<p>In <em>Cracking the Coding Interview</em> by Gayle Laakmann McDowell, there's a question that asks you to write code for the following:</p>
<blockquote>
<p>Given two sorted arrays, A and B. Write a method merging the elements
of B into A in sorted order. Assume A has a large enough buffer at the
end to hold all of B's elements.</p>
</blockquote>
<p>Though the problem isn't very hard, I've been striving to increase the readability of my code in general. As such, I wrote two versions of my solution, and am looking for input on which version is most readable.</p>
<p><strong>Version 1:</strong></p>
<pre><code>// Given two sorted arrays, adds the elements of the second array into
// the first, while maintaining ordering property.
// XXX: Assumes first array has enough buffer space to hold all elements
public static <Type extends Comparable<Type>> Type[]
mergeIntoFirstArray(Type[] first_array, Type[] second_array) {
int first_idx = numElementsInArray(first_array) - 1;
int second_idx = second_array.length - 1;
int merge_idx = numElementsInArray(first_array) + second_array.length - 1; //
// merge largest values first, until either array is exhausted
while (first_idx >= 0 && second_idx >= 0) {
Type first_value = first_array[first_idx];
Type second_value = second_array[second_idx];
// add the largest value
if (first_value.compareTo(second_value) > 0){
first_array[merge_idx] = first_value ;
first_idx--;
} else {
first_array[merge_idx] = second_value ;
second_idx--;
}
merge_idx-- ;
}
// if second_array still has values, merge them in
while (second_idx >=0) {
first_array[merge_idx] = second_array[second_idx] ;
merge_idx-- ;
second_idx--;
}
return first_array ;
}
</code></pre>
<p><strong>Version 2:</strong></p>
<pre><code>public static <Type extends Comparable<Type>> Type[]
mergeIntoFirstArrayV2(Type[] first_array, Type[] second_array) {
int f = numElementsInArray(first_array)-1;
int s = second_array.length - 1;
// merge in largest values first
for (int merge_idx = f + s + 1 ; merge_idx >= 0 ; merge_idx--) {
Type fvalue = f >= 0 ? first_array[f] : null;
Type svalue = s >= 0 ? second_array[s] : null;
// first value exists, and is greater than second value
if (fvalue != null &&
(svalue == null || fvalue.compareTo(svalue) > 0)) {
first_array[merge_idx] = svalue ;
s_idx--;
}
else {
first_array[merge_idx] = svalue ;
s_idx--;
}
}
return first_array ;
}
</code></pre>
<p>Any meaningful input on improving the readability of either method would also be appreciated. For one, I think my variable names might be unclear or too long in some cases. For version 2, I suspect that though the code is more concise, it is harder to understand at a glance.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T23:12:16.720",
"Id": "30153",
"Score": "1",
"body": "In-place modification is silly though. A whole new array / list should be created instead. If only Java had a yield keyword ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T01:07:04.420",
"Id": "30173",
"Score": "0",
"body": "I thought it was a pain too, and only reused the parameter array because of the problem description. I'm not sure how yield would help in this scenario, though. Knowing a little bit about python, having a 'yield' feature would allow you to make a generator function that could return the merged values (one value returned after each function call?). If you don't mind explaining, how would this be advantageous for this particular problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T13:45:19.403",
"Id": "30196",
"Score": "0",
"body": "I am all about splitting a problem into as small chunks as possible. Sometimes it is more convenient to yield in one function and collect that into a real data structure later than to mix the generation and the collection of the output in one. Obviously, it is not a major factor. However, if Java had a `yield` as well as a look-ahead iterator (something that allows to peek cheaply), then this problem would have a beautiful solution. Otherwise, it feels kind of ugly at the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T19:26:54.583",
"Id": "30225",
"Score": "0",
"body": "I am not sure, but I do not think that you can find a good implementation for numElementsInArray if you use generics. Because there is no good way to know an \"empty\" element."
}
] |
[
{
"body": "<p>Both are equivalently readable, I'll nitpick on some details though :)</p>\n\n<p>Both solutions will fail with null elements.</p>\n\n<p>The generic type would be better named T instead of Type, as Type has another definition already.</p>\n\n<p>numElementsInArray() as a function looks a little odd because it is undefined, instead consider passing in the information you need as part of the method definition.</p>\n\n<p>When modifying in place you do not want to return the array because presumably you are trying to skimp on memory allocations and are just going to look for the result in the first array that was passed in.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T01:02:13.303",
"Id": "30172",
"Score": "0",
"body": "As soon as you said it, I realized I hadn't taken null values into account. Actually, I frequently forget to check or validate input. And I hadn't noticed Type had another definition, either. The last two suggestions are something I couldn't decide either way when coding: I have both versions of mergeIntoFirstArray() returning Type[] to save myself a line of code when testing the methods. I used numElementsInArray() because I wasn't certain whether I should have the user enter the number of elements in the first array. Anyway, thanks, I appreciate your assessment. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T01:56:34.510",
"Id": "18902",
"ParentId": "18892",
"Score": "6"
}
},
{
"body": "<p><strong>Edit:</strong> OK, fine, in Java:</p>\n\n<pre><code>// Precondition: dest[0..n-1] and source[] are both sorted increasing.\n// Postcondition: dest[0..n+source.length-1] is the sorted merge of\n// the original dest[0..n-1] and source[], and source[] is unchanged.\npublic static <Type extends Comparable<Type>>\nvoid mergeInto(Type[] dest, int n, Type[] source) {\n int s = source.length; // reading from source\n int d = n; // reading from dest\n int w = n + s; // writing to dest\n while (0 < s) {\n while (0 < d && source[s-1].compareTo(dest[d-1]) < 0) {\n dest[--w] = dest[--d];\n }\n dest[--w] = source[--s];\n }\n}\n</code></pre>\n\n<p>Untested. (<strong>edit:</strong> tested by @climmunk, yay!) That was why my original answer, below, was in Python, so I wouldn't be foisting untested code on you. Note that this code provides a slightly different interface than the questioner's, which is intentional: it's part of the code review.</p>\n\n<p><strong>Original answer:</strong> Here's the algorithm I'd use (coded in Python since I don't know C#):</p>\n\n<pre><code>def merge_into(A, n, B):\n \"\"\"Pre: A[:n] and B are both sorted.\n Post: B is unaltered, and A_post[:n+len(B)] == sorted(A_pre[:n]+B)\"\"\"\n j, k = n, n + len(B)\n for b in reversed(B):\n while 0 < j and b < A[j-1]:\n j -= 1\n k -= 1\n A[k] = A[j]\n k -= 1\n A[k] = b\n</code></pre>\n\n<p>Trying it out:</p>\n\n<pre><code>>>> A = [3, 4, 5, 9, None, None, None]\n>>> B = [1, 1, 4]\n>>> merge_into(A, 4, B)\n>>> A\n[1, 1, 3, 4, 4, 5, 9]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T03:36:30.383",
"Id": "30175",
"Score": "2",
"body": "Do you know Java? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:13:19.353",
"Id": "30375",
"Score": "0",
"body": "Not since before generics were added. Sorry for the trivial confusion. The point, though, is the simpler algorithm: just a loop within a loop, with no ifs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T17:33:08.850",
"Id": "89095",
"Score": "1",
"body": "This is a nice algorithm, cleaner than OP's. I tested the Java code, and it works. Not sure why it's getting downvoted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T18:06:36.043",
"Id": "89098",
"Score": "0",
"body": "You have a case of the [Yoda conditions](http://en.wikipedia.org/wiki/Yoda_conditions) :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T22:59:31.477",
"Id": "89137",
"Score": "0",
"body": "I consistently use < instead of >, most of the time, because you can visualize `a<b`: a is to the left of b on the number line. Then more complex conditions like `a <= b && b < c` become easier to think about."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T03:21:27.380",
"Id": "18921",
"ParentId": "18892",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p>Given two sorted arrays, A and B. Write a method merging the elements of B into A in sorted order. Assume A has a large enough buffer at the end to hold all of B's elements.</p>\n</blockquote>\n\n<p>This is my approach:</p>\n\n<pre><code>public static <T extends Comparable<T>> void mergeSecondArrayInFirstArrayOrdered(final T[] array1, final T[] array2) {\n // we could (should!) add checks for the given contract. Do not trust the world\n for (int i = 1; i <= array2.length; ++i)\n array1[array1.length - i] = array2[array2.length - i];\n Arrays.sort(array1);\n}\n// edit: got a hint for a small change. One could discuss which version should be used\n// System.arraycopy uses a native implementation, which should be faster, but you lose\n// readability (and type safety)\npublic static <T extends Comparable<T>> void mergeSecondArrayInFirstArrayOrdered2(final T[] array1, final T[] array2) {\n System.arraycopy(array2, 0, array1, array1.length - array2.length, array2.length);\n Arrays.sort(array1);\n}\n</code></pre>\n\n<p>Ok, you can say now this is not expected. But, well, it confirms to the question and it is a good solution because you use a well known, good tested and designed Java method. So for your employer the benefits are reduced time instead of doing this rather long merge by hand, and reduced support costs because this code is very easy to check and understand. If your employer is clever, he will get the point.<br>\nKeep in mind, that this works only for <code>Object</code> arrays. For arrays of primitive array types, you have to implement it for all 8 types.</p>\n\n<p>(One could have an argument about speed because of the sort. I advice you to not trust this argument before profiling.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T19:23:46.150",
"Id": "18949",
"ParentId": "18892",
"Score": "1"
}
},
{
"body": "<p>Clearly the crux of the question was that you have to fill the array from the end, and you got that right.</p>\n\n<p>In the second version, the fact that all elements of an array has been handled is represented in the program state by assigning null to the value variables. And when reading the following if statement you have to go back to lines where the values are assigned to see how they can be null. You should just check if <code>firstIdx < 0</code> in simpler cases like this or use a private method or local variable with a meaningful name if it is not clear what the boolean expression means. In that way first version is clearly superior. (It also doesn't have the ternary operator ?:, which always helps.)</p>\n\n<pre><code>firstArrayFinished = firstIdx < 0;\n// ..................\n// ..................\n// ..................\n// ..................\nif (firstArrayFinished || s.compareTo(f) > 0) {\n // ..................\n}\n</code></pre>\n\n<p>I agree totally with Timothy Pratley, on his remarks. Even if there is no question of confusion with another identifier, you should still use single capital letters or similar short identifiers as type variables, so that it is <strong>instantly</strong> clear for the reader of the code that it is not an actual class or interface. When you browse code in an IDE or grep some source folder you never see the imports section and it becomes an effort to check the method signature every time just to be sure becomes a burden. (Also lose the underscores, if you are a java programmer.)</p>\n\n<p>Although the standard library has similar methods, a method doing anything in place means its modifying something and should return void.\nThe library methods that do both in place modification and return arrays do that because they do array allocation if some parameters are null. I do not know if return type was in the problem specification.</p>\n\n<p><code>numElementsInArray(first_array)</code> is also problematic. If an array is passed as a parameter and it's empty after some index, you pass another parameter <code>int len</code> to indicate the number of elements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-13T08:14:15.380",
"Id": "19565",
"ParentId": "18892",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T17:16:12.070",
"Id": "18892",
"Score": "8",
"Tags": [
"java",
"interview-questions",
"mergesort",
"comparative-review"
],
"Title": "Given two sorted arrays, add the elements of the second array into the first"
}
|
18892
|
<p>I've created my first jQuery plugin, so please try to understand :)</p>
<p>My plugin code looks like so:</p>
<pre><code>(function($) {
$.fn.ajaxSelect = function(options) {
var $this = this;
//options
var settings = $.extend({}, defaults, options);
//disable select
if ($.ui.selectmenu && settings.selectmenu && settings.disableOnLoad) {
$this.selectmenu('disable');
}
//ajax call
$.ajax({
type: settings.type,
contentType: settings.contentType,
url: settings.url,
dataType: settings.dataType,
data: settings.data
}).done(function(data) {
var n = data.d || data;
var list = "";
$.each(n, function(i) {
list += '<option value=' + n[i].Id + '>' + n[i].Nazwa + '</option>';
});
$this.filter("select").each(function() {
$(this).empty();
$(this).append(list);
if ($.ui.selectmenu && settings.selectmenu) {
$this.selectmenu();
}
});
settings.success.call(this);
}).fail(function() {
settings.error.call(this);
});
return this;
};
var defaults = {
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/echo/json/',
dataType: 'json',
data: null,
async: true,
selectmenu: true,
disableOnLoad: true,
success: function() {},
error: function() {}
};
})(jQuery);
</code></pre>
<p>Demo of usage is available at <a href="http://jsfiddle.net/Misiu/ncWEw/12/" rel="nofollow">http://jsfiddle.net/Misiu/ncWEw/</a> </p>
<p>What I was trying to accomplish:</p>
<ul>
<li>Select multiple elements at one time</li>
<li>Filter only selects from selected items (in case selector would select other elemnts)</li>
<li>Makes only ONE request to server</li>
<li>First build option string and then append it instead of adding items in loop</li>
<li>Specify 2 callbacks: one for error and second for success</li>
</ul>
<p>I think that it would be better to use more of deferred objects, but I don't have idea how.
Any improvements and hints are welcome :)</p>
|
[] |
[
{
"body": "<p>Your demo throws errors in console, something about <code>uniqueId</code> in ui.selectmenu.</p>\n\n<p>Anyway:</p>\n\n<ol>\n<li>You can expose <code>$.ajax</code> deferred so someone may use all features of <code>jQuery.Deferred</code> which is already there.</li>\n<li><p>Call success callback with data as argument.</p>\n\n<pre><code>settings.success.call(this, n);\n</code></pre></li>\n<li><p>If you do not want to do anything special in case of failure, and just want to provide <code>this</code> to error callback, you do not have to create closure there.</p>\n\n<pre><code>.fail( settings.error );\n</code></pre>\n\n<p>..., unless you want to hide other rejection arguments.</p></li>\n<li><p>Do not use <code>each</code> if <code>for</code> do the same (for performance reason):</p>\n\n<pre><code>for( var index = 0; index < n.length; index ++){\n list += '<option value=' + n[index].Id + '>' + n[index].Nazwa + '</option>';\n}\n</code></pre></li>\n<li>Personally I don't like single char variable names, as they are really painful for future development</li>\n</ol>\n\n<hr>\n\n<ol>\n<li><p>Instead of <code>$(this).empty();$(this).append(list);</code> you can simply use <code>$(this).html(list);</code></p></li>\n<li><p>You can expose jQuery.Deffered, for example as <code>this.promise = $.ajax(...</code>, example in here <a href=\"http://jsfiddle.net/dhRRN/5/\" rel=\"nofollow\">http://jsfiddle.net/dhRRN/5/</a></p></li>\n<li><p>I would suggest also applying received options to ajax call, so your plugin's user could also alter request itself.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T08:02:54.693",
"Id": "38880",
"Score": "0",
"body": "Thanks for all the tips :) I've updated my demo to remove all errors, and I changed `each` to `for`. Could You please show how should I change my code to use `Deferred`? I suppose I could add data to success callback, but in my case I wont need it later. Could You take a look at it again?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T18:04:47.183",
"Id": "38904",
"Score": "0",
"body": "Regarding adding/hiding data for callback, I have added new #3.\n\n@Misiu: I'm not exactly sure how are you going to use your plugin. [Here](http://jsfiddle.net/tomalec/dhRRN/) you have quick example how to expose `jQuery.Deferred` promise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-17T06:51:10.923",
"Id": "38933",
"Score": "0",
"body": "I'll be using this mostly in reports. For example I need to filter some data based on employees. I have 4 places to specify employee (employee that took order, one that collect all items in order, one that shipped etc) and the list I can choose is the same for every select. So my main idea was to fill multiple selects with same data that comes from ajax request and to do only one request for all selects. This is just a scratch rather than full working plugin, but I would like to create something usefull not only for me :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T23:44:14.593",
"Id": "24780",
"ParentId": "18897",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24780",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T20:37:13.453",
"Id": "18897",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery plugin for ajax select fill"
}
|
18897
|
<p>In current project I'm using a lot <code>ReaderWriterLockSlim</code> for synchronizing reading and writing values. Handling <code>try { EnterReadLock(); .... } finaly { ExitReadLock(); }</code> every time I need access value seems to me as copying code. So I created extension methods for <code>ReaderWriterLockSlim</code> which makes me coding much easer and faster (and reusable i think).</p>
<p>However I would like know, if you found some disadvantages in the extension methods I missed or forgot.
There are three extension methods:</p>
<ul>
<li><code>ReadOnly<T>(this ReaderWriterLockSlim self, Func<T> readFunc) // calls EnterReadLock()</code></li>
<li><code>Read<T>(this ReaderWriterLockSlim self, Func<T> readFunc) // calls EnterUpgradeableReadLock()</code></li>
<li><code>Write(this ReaderWriterLockSlim self, Action writeAction) // calls EnterWriteLock()</code></li>
<li><code>Write<T>(this ReaderWriterLockSlim self, Func<T> writeAction) // calls EnterWriteLock()</code></li>
</ul>
<p>There is code of <code>ReadOnly<T>(...)</code> method. All methods looks similar.</p>
<pre><code>public static T ReadOnly<T>(this ReaderWriterLockSlim self, Func<T> readFunc) {
if (object.ReferenceEquals(self, null)) { throw new ArgumentNullException("self"); }
if (object.ReferenceEquals(readFunc, null)) { throw new ArgumentNullException("readFunc"); }
T result;
// flag, if lock was entered
bool lockEntered = false;
try {
// I don't want the ThreadAbortException during claiming the lock
Thread.BeginCriticalRegion();
try {
self.EnterReadLock();
lockEntered = true;
}
finally {
Thread.EndCriticalRegion();
}
result = readFunc();
}
finally {
// I don't want the ThreadAbortException during releasing the lock
Thread.BeginCriticalRegion();
try {
if (lockEntered) {
self.ExitReadLock();
}
}
finally {
Thread.EndCriticalRegion();
}
}
return result;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T17:29:32.457",
"Id": "30548",
"Score": "0",
"body": "In cases like this, I prefer methods that work with `using`, instead of taking a delegate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T00:17:17.410",
"Id": "30572",
"Score": "0",
"body": "@svick, but working with using is not fully thread-safe :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T00:31:19.560",
"Id": "30573",
"Score": "0",
"body": "What do you mean? I don't see any reason why it shouldn't be thread-safe (assuming you don't use it incorrectly)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-14T18:02:52.773",
"Id": "31405",
"Score": "0",
"body": "@svick: its because the using(var x = SomeFunc()){...} is only syntax sugar, when ThreadAbortException is thrown before object is passed from return value of \"SomeFunc()\" to local variable \"x\", the \"finally{...}\" block will not handle passed object, because in \"x\" is nothing (null)."
}
] |
[
{
"body": "<p>It looks pretty good. I can't see anything less than great.<br>\nI'd just add that to your code:</p>\n\n<pre><code> private static void Critical(Action criticalAction)\n {\n try\n {\n Thread.BeginCriticalRegion();\n criticalAction();\n }\n finally\n {\n Thread.EndCriticalRegion();\n }\n }\n</code></pre>\n\n<p>And i used the <code>IsWriteLockHeld</code>, <code>IsReadLockHeld</code>, etc, before exiting the lock.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-14T18:03:50.370",
"Id": "31406",
"Score": "0",
"body": "Good point. Didn't you mean the \"Thread.BeginCriticalRegion()\" should be before \"criticalAction()\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-14T18:49:40.300",
"Id": "31408",
"Score": "0",
"body": "You got a point, there!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-14T17:34:13.083",
"Id": "19618",
"ParentId": "18908",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T10:45:41.787",
"Id": "18908",
"Score": "4",
"Tags": [
"c#",
"multithreading"
],
"Title": "Extension methods for ReaderWriterLockSlim"
}
|
18908
|
<p>I have the following code for my coupon system. It should work but I'm sure I can optimize it. </p>
<p>Any suggestions would be welcome.</p>
<pre><code>@price_to_pay = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - @price_to_pay
if @remaining > 0
@coupon.current_amount = @remaining
@price_to_pay = 0
elsif @remaining = 0
@coupon.current_amount = 0
@price_to_pay = 0
elsif @remaining < 0
@coupon.current_amount = @remaining
@price_to_pay = @remaining * -1
end
coupon.save
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T15:58:12.887",
"Id": "30168",
"Score": "2",
"body": "is this Rails? a lot of instance variables being used here, and some even updated (`@price_to_pay`), why is that? are they AR attributes?"
}
] |
[
{
"body": "<p>I think this replicates the logic:</p>\n\n<pre><code>price = @booking_request.guests * @table_offer.price_cents / 100\n@remaining = @coupon.current_amount - price\n@coupon.current_amount = @remaining\n@price_to_play = @remaining >= 0 ? 0 : -@remaining\ncoupon.save\n</code></pre>\n\n<p>Note that I avoid setting <code>@price_to_play</code> to a value and changing it afterwards, that kind of variable re-using makes code harder to understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T15:56:54.323",
"Id": "18914",
"ParentId": "18913",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18914",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T15:23:33.390",
"Id": "18913",
"Score": "3",
"Tags": [
"performance",
"algorithm",
"ruby",
"e-commerce"
],
"Title": "Coupon system optimization"
}
|
18913
|
<p>Is there a better way of writing this? I feel like there's a lot of lines for such a small thing. Can it be optimized?</p>
<pre><code>$j('#hideShowBtn').toggle(function() {
$j('.playlist-bar-tray').slideUp();
$j(this).attr("title","Show Playlist");
$j(this).children("div").html('Show Playlist');
$j(this).children("span").html('&#9660;');
}, function() {
$j('.playlist-bar-tray').slideDown();
$j(this).attr("title","Hide Playlist");
$j(this).children("div").html('Hide Playlist');
$j(this).children("span").html('&#9650;');
});
</code></pre>
|
[] |
[
{
"body": "<p>Well, it can be written <em>differently</em> with less repetition, but it's readable as it is. There are 4 things that need to happen when the toggling occurs; your code does exactly that. It's the simplest way to write it, really.</p>\n\n<p>My only real suggestion would be to cache <code>$j(this)</code> in a variable to avoid recreating it.</p>\n\n<p>Regardless, here's a funky rewrite, just for the sake of it</p>\n\n<pre><code>function toggle(hiding) {\n var title = (hiding ? \"Show Playlist\" : \"Hide Playlist\"),\n symbol = (hiding ? \"&#9960\" : \"&#9650\"),\n method = (hiding ? \"slideUp\" : \"slideDown\");\n\n return function () {\n var element = $j(this);\n element.attr(\"title\", title).children(\"div\").html(title);\n element.children(\"span\").html(symbol);\n $j(\".playlist-bar-tray\")[method]();\n };\n}\n\n$j('#hideShowBtn').toggle( toggle(true), toggle(false) );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T13:33:06.387",
"Id": "30195",
"Score": "0",
"body": "I actually really like that solution, thanks a lot!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T17:35:03.763",
"Id": "30213",
"Score": "0",
"body": "@Lelly Glad you found it useful. But do check out ZeroOne's answer too, and read its comments. There's a lot to gain by keeping the content in the markup, and only the behavior in the JS"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T22:05:07.453",
"Id": "18918",
"ParentId": "18917",
"Score": "5"
}
},
{
"body": "<p>How about \"cheating\" a bit by creating two copies of those elements whose values should change and then just alternate between which element to show. Something like this:</p>\n\n\n\n<pre><code><div class=\"toggleable\">\n <span>&#9660;</span> Show playlist\n</div>\n<div class=\"toggleable\" style=\"display: none;\">\n <span>&#9650;</span> Hide playlist\n</div>\n</code></pre>\n\n<p>And then somewhere in your JavaScript you call the <a href=\"http://jqueryui.com/toggle/\">.toggle() function from the jQuery UI</a>:</p>\n\n<pre><code>$(\".toggleable\").toggle();\n</code></pre>\n\n<p>Now it would look as though the texts changed, while actually you are hiding one element and displaying another.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T09:03:17.910",
"Id": "30184",
"Score": "0",
"body": "I think this is the neater approach. In the original code there is a lot of html/content embedded in the code, so anyone reading the .html would be unable to see what is going on. This approach means the javascript is just the action."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T09:13:00.657",
"Id": "30185",
"Score": "1",
"body": "I agree with @Quango - keep content and behavior separate. Other alternatives would be to use a class and some CSS so show/hide elements (and simply use `.toggleClass()`), or store the hide/show strings in `data-*` attributes so they're in the HTML and not the JS."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T22:28:50.903",
"Id": "18919",
"ParentId": "18917",
"Score": "7"
}
},
{
"body": "<p>Another option (though I have to say that I like @ZeroOne's solution in this case):</p>\n\n<pre><code>var getToggleHandler = function (opts) {\n return function () {\n var $this = $j(this);\n $j('.playlist-bar-tray')[opts.method]();\n $this.attr(\"title\", opts.title);\n $this.children(\"div\").html(opts.title);\n $this.children(\"span\").html(opts.spanContent);\n };\n}\n\n$j('#hideShowBtn').toggle(getToggleHandler({\n method: 'slideUp',\n title: 'Show Playlist',\n spanContent: '&#9660;'\n}), getToggleHandler({\n method: 'slideDown',\n title: 'Hide Playlist',\n spanContent: '&#9650;'\n}));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T20:04:22.813",
"Id": "18953",
"ParentId": "18917",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18918",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T20:33:43.483",
"Id": "18917",
"Score": "5",
"Tags": [
"javascript",
"jquery"
],
"Title": "Revealing and hiding a playlist"
}
|
18917
|
<p>I am a Java beginner and I am looking for an idiomatic way of writing a function that involves generics. I wrote this helper class (below) that pushes items into a sorted generic collection and I wanted to ask for your feedback. Should I perhaps extends some base class of some collection? Or maybe there is some better approach that follows the Java philosophy?</p>
<pre><code>import java.util.Comparator;
import java.util.List;
public abstract class ListExtensions {
public static <T> void addOnCompare(List<T> collection, T item,
Comparator<T> comparator) {
synchronized(collection) {
int i = 0;
int size = collection.size();
if (size == 1) {
int diff = comparator.compare(item, collection.get(0));
switch(diff) {
case 1: i++; break;
default: break;
}
} else {
int range = size - 1;
i = size / 2;
int left = 0;
int right = range;
while(true) {
if (i <= 0) { i = 0; break; }
if (i > range) { i = range; break; }
int diff = comparator.compare(item, collection.get(i));
if (diff == 0) break;
else {
if (diff == -1) right = i;
if (diff == 1) left = i;
int near = i + diff;
if (near < 0) { i = 0; break; }
if (near > range) { i = range + 1; break; }
int diff_near = comparator.compare(item, collection.get(near));
if (diff_near == 0) { i = diff_near; break; }
if (diff_near == diff) {
int step = (right-left)/2;
if (step == 0) step = 1;
switch(diff){
case -1:
right = i;
i = i - step; break;
case 1:
left = i;
i = i + step; break;
}
} else if (diff > diff_near) {
i = near; break;
} else { break; }
}
}
}
collection.add(i, item);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T16:55:47.093",
"Id": "30212",
"Score": "1",
"body": "Have you seen Collections#binarySearch? [link to javadoc (Java 6)](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20T,%20java.util.Comparator%29)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T14:50:57.407",
"Id": "30535",
"Score": "0",
"body": "A javadoc and/or some comments explaining the method's purpose would be very helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T18:48:49.240",
"Id": "31959",
"Score": "0",
"body": "Sorry, but that `synchronized` will only work if _all_ references to the passed-in collection are _also_ locked. Also, it won't stop people from modifying the _contents_ of the collection, if it contains mutable classes. If you really want threadsafety, you have to copy the collections, **and** the contents (or make things immutable). Otherwise, I'd remove the synchronization, and document that the method isn't threadsafe."
}
] |
[
{
"body": "<p>Parts this question have already been answered on StackOverflow - <a href=\"https://stackoverflow.com/a/13529644/139985\">https://stackoverflow.com/a/13529644/139985</a> So I'm going to treat this as a simple request for a code review.</p>\n\n<ol>\n<li><p>The method name is opaque ... <code>addOnCompare</code> does not clearly imply a particular action ... and there is no javadoc for the method. This immediately makes code-review hard ... because I have to try and figure out what the code is trying to do before I can comment on whether it is doing that well.</p></li>\n<li><p>The parameter name <code>collection</code> is poor. It is a list, not a collection.</p></li>\n<li><p>The local variable <code>diff_near</code> should be <code>diffNear</code>.</p></li>\n<li><p>This is convoluted:</p>\n\n<pre><code> switch(diff) {\n case 1: i++; break;\n default: break;\n }\n</code></pre>\n\n<p>Write it as:</p>\n\n<pre><code> if (diff == 1) { i = 1; }\n</code></pre></li>\n<li><p>I don't know what these lines are trying to do, but they are definitely wrong:</p>\n\n<pre><code> int near = i + diff; \n if (near < 0) { i = 0; break; }\n if (near > range) { i = range + 1; break; }\n int diff_near = comparator.compare(item, collection.get(near));\n</code></pre>\n\n<p>The value returned by a comparator has no meaning beyond being -ve, zero, or +ve. So adding it to the index <code>i</code> is going to have an unpredictable effect. Indeed, since <code>range</code> never changes, this code makes the behaviour of the entire algorithm too difficult to understand.</p></li>\n<li><p>I'm going to hazard a guess that the method is intended to insert <code>item</code> at the correct position in a previously sorted list. But given the above, I have grave doubts that it will actually work for all possible (valid) comparators and all possible (sorted) input lists.</p></li>\n<li><p>Even if this code did work, the performance for a linked list would be poor. The <code>List.get(int)</code> method for a linked list is <code>O(N)</code>, so even an optimal binary search pattern would result in <code>O(Nlog(N))</code> operations to insert one element into the linked list. A simple traversal of the list followed by an insert would be <code>O(N)</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T12:17:54.807",
"Id": "19055",
"ParentId": "18931",
"Score": "3"
}
},
{
"body": "<p>Just use <code>java.util.TreeSet</code>. \nIf and only if it needs to be threadsafe, use <code>Collections.synchronizedSortedSet()</code> to get a synchronized wrapper.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T09:08:34.207",
"Id": "31949",
"Score": "0",
"body": "http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html\n\nyour version, if it works correctly, has O(n) complexity. (as Stephen C already noted)\n\nTreeSet has remove and contains, as well as add, all with O(log n)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T09:05:35.047",
"Id": "19989",
"ParentId": "18931",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T13:11:39.983",
"Id": "18931",
"Score": "3",
"Tags": [
"java",
"generics"
],
"Title": "how to write generic extensions for standard collection types in java?"
}
|
18931
|
<p>I have this <code>GenericDataAccess</code> class to interact with database from my school. I want to ask for some suggestions and advice in how to to improve it and add new methods to it for future use and reference</p>
<pre><code>public static class GenericDataAccess
{
static GenericDataAccess()
{
}
/// <summary>
/// creates and prepares a new DbCommand object on a new connection
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public static DataTable ExecuteSelectCommand(DbCommand command)
{
// The DataTable to be returned
DataTable table;
try
{
//open connection
command.Connection.Open();
//execute command & save the result in DataTable
DbDataReader reader = command.ExecuteReader();
table = new DataTable();
table.Load(reader);
}
catch (Exception ex)
{
Utilities.LogError(ex);
throw;
}
finally
{
command.Connection.Close();
}
return table;
}
/// <summary>
/// creates and prepares a new DbCommand object on a new connection
/// </summary>
/// <returns></returns>
public static DbCommand CreateCommand()
{
//obtaine the database provider name
string dataProviderName = CompuData_ProjectManagerConfiguration.DbProviderName;
//Obtain database connection string
string connectionString = CompuData_ProjectManagerConfiguration.DbconnctionString;
//Create new Data Provider Factory
DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);
//obtain a database specific connection object
DbConnection conn = factory.CreateConnection();
//set the connection string
conn.ConnectionString = connectionString;
//create a database specific command object
DbCommand comn = conn.CreateCommand();
//set the command type to store proc
comn.CommandType = CommandType.StoredProcedure;
//return the initialized command object
return comn;
}
/// <summary>
/// execute an update, delete, or insert command and return the number of affected rows
/// </summary>
/// <param name="command"></param>
public static int ExecuteNonQuery(DbCommand command)
{
//the number of affected rows
int affectedRows = -1;
// Execute the command making sure the connection gets closed in the end
try
{
//open connction
command.Connection.Open();
affectedRows = command.ExecuteNonQuery();
}
catch (Exception ex)
{
Utilities.LogError(ex);
throw;
}
finally
{
command.Connection.Close();
}
return affectedRows;
}
// execute a select command and return a single result as a string
public static string ExecuteScaler(DbCommand command)
{
// the value to be retuned
string value = "";
// Execute the command making sure the connection gets closed in the end
try
{
//open the connection of command
command.Connection.Open();
//execute the command and get the number of affected rows
value = command.ExecuteScalar().ToString();
}
catch (Exception ex)
{
Utilities.LogError(ex);
throw;
}
finally
{
command.Connection.Close();
}
return value;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T16:29:41.967",
"Id": "30254",
"Score": "0",
"body": "IMO: too much code, too little functionality. I have written one of these before because I had to use an older way to connect to a database. I do not remember typing so much repetitive code though."
}
] |
[
{
"body": "<p>First of all, there is no need to write a generic data access class. Use the <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=15104\" rel=\"nofollow noreferrer\">Data Access Application Block</a>. It gives you everything you need to access a database. Why reinvent the wheel. You can even download the source code to this if you want to see how Microsoft does it.</p>\n\n<p>Having said that, if you are doing this just as an exercise then I see a couple things...</p>\n\n<p>I am not a big fan of static classes (except for possibly simple \"function\" classes, classes which provide generic functions such as a function to convert unix timestamp to datetime). Making classes static makes it more difficult to unit test. </p>\n\n<p>Along these lines of unit testing I would also recommend you implement an interface so you could can make unit testing easier through <a href=\"https://stackoverflow.com/questions/3058/what-is-inversion-of-control\">IOC / dependency injection</a></p>\n\n<p>Your methods should only do one thing. Adding too much functionality into each method limits the flexibility of the caller. You should have a method that creates a connection, another that creates a command, and another that executes the command. Example, I would not open and close my connections within the \"Execute...\" methods because what if the caller wants to open the connection so they can execute multiple commands in the same connection. If you want to add methods that do multiple things then they should be separate from your generic data access class, and they should call your generic data access methods.</p>\n\n<p>I do not see anything to handle transactions. This would be something you would want to add.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T14:36:48.920",
"Id": "18963",
"ParentId": "18933",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18963",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T14:51:20.907",
"Id": "18933",
"Score": "2",
"Tags": [
"c#",
".net",
"database"
],
"Title": "Adding new methods to GenericDataAccess"
}
|
18933
|
<p>The basic idea is for users of these classes to create derived polymorphic protocol specific messages. There is no protocol type in the interface, it is all hidden behind the scenes. But the serialised messages can be retrieved with the <code>getMessage</code> functions.</p>
<p>Does this look a logical approach? Any suggestions?</p>
<pre><code>//base protocol class - interface only
//ref_type is a smart pointers class - not really so relevant to my question
class BaseMessage : public ref_type
{
public:
virtual ~BaseMessage() {}
virtual const char* ProtocolName() const = 0;
virtual bool Encode() = 0;
virtual bool Decode() = 0;
//for binary protocols
virtual void getMessage(unsigned char*& serialised, size_t& length) {};
//for text/xml protocols
virtual void getMessage(std::string& serialised) {}
};
</code></pre>
<p>A specific protocol might then be implemented like this:</p>
<pre><code>class ABCMessage : public BaseMessage {
public:
ABCMessage(ABC* msg) : m_msg(msg), m_data(0), m_length(0) {}
ABCMessage(unsigned char* data, int length) : m_length(length), m_msg(0)
{
m_data = new unsigned char[length]();
memcpy(m_data, data, length);
}
virtual ~ABCMessage();
virtual const char* ProtocolName() const;
virtual bool Encode();
virtual bool Decode();
virtual void getMessage(unsigned char*& serialised, size_t& length);
protected:
ABC* m_msg;
unsigned char* m_data;
size_t m_length;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T14:52:00.370",
"Id": "30201",
"Score": "0",
"body": "It's perhaps not clear who allocates, owns, handles memory in calls to getMessage and constructor. Usable, but error-prone."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T14:56:01.163",
"Id": "30202",
"Score": "0",
"body": "Decode() should probably return 'size_t'. If the intention is to return -1 in case of error, then it should be documented. But better to throw an exception (and document it, too)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:00:11.040",
"Id": "30203",
"Score": "0",
"body": "@BjörnPollex - how can I migrate it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:00:41.150",
"Id": "30204",
"Score": "0",
"body": "getMessage() could return a bool, and ProtocolName() could return a std::string, or const std:string&."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:00:46.657",
"Id": "30205",
"Score": "0",
"body": "@user619818: Flag it."
}
] |
[
{
"body": "<p>OK. I doubt it is irrelevant.</p>\n\n<pre><code>//ref_type is a smart pointers class - not really so relevant to my question\n</code></pre>\n\n<p>Also smart pointers are very hard to get perfectly correct. The standard ones took years and thousands of people looking at them to get correct. So It is usually preferable to use one of the standard smart pointers rather than a home grown one (especially one that is not being reviewed).</p>\n\n<p>So who owns this pointer?</p>\n\n<pre><code> virtual const char* ProtocolName() const = 0;\n</code></pre>\n\n<p>There are no ownership semantics associated with pointers. So After I call this I am not sure who is responsible for deleting it. Use a std::string internally and return a const reference to the string.</p>\n\n<p>Not sure why you would want two methods that look like they do the same thing.</p>\n\n<pre><code> //for binary protocols\n virtual void getMessage(unsigned char*& serialised, size_t& length) {}; \n //for text/xml protocols\n virtual void getMessage(std::string& serialised) {}\n</code></pre>\n\n<p>Both are going to be inefficient as you are copying across multiple buffers (input stream buffer into this buffer which is then returned and read again to build an object). What you really want is a getMessage() method that returns a fully constructed object from the stream.</p>\n\n<p>This calss:</p>\n\n<pre><code>class ABCMessage : public BaseMessage {\n</code></pre>\n\n<p>Is totally broken as it contains an owned RAW pointer but does not implement the rule of three.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-24T12:25:54.160",
"Id": "31801",
"Score": "0",
"body": "As far as I know `const char *` is often used to denote fact that no one should take owner ship on that poitner (i.e. someone who made that from `char *` is owner)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-24T16:26:38.337",
"Id": "31808",
"Score": "0",
"body": "@ony: No. `const char*` is just the same as `chat const*` and indicates absolutely no ownership. The only thing it indicates is that the content can not be modified (this has nothing to do with ownership). This is why C++ has std::string. You can return by value (thus returning ownership) or return by reference (indicating that ownership is retained by the source object)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-24T21:12:16.020",
"Id": "31819",
"Score": "0",
"body": "I said \"is often used to denote\" but not \"it denotes\". I refer to some guidelines in code writing. Often fact that you can't modify content results in inability to destroy object correctly (ex. decrement amount of refs etc)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-24T21:34:24.120",
"Id": "31820",
"Score": "0",
"body": "@ony: No. It is never used this way in C++. In C or \"C with struct\" (people who write C who think they write C++) may do this. But in C++ this concept was moved to the rubish pile of bad techniques over a decade ago. In good program ownership is explicitly expressed by the objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-25T08:57:49.770",
"Id": "31838",
"Score": "0",
"body": "anyway, I hope you've got idea. Even that this thing never used this way and in the same time it moved to the rubish pile of bad techniques in favor of smart pointers."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:52:11.313",
"Id": "18935",
"ParentId": "18934",
"Score": "1"
}
},
{
"body": "<p>There is very good approach which works almost always: \"Look for existing solutions\". Consider looking into <a href=\"http://www.boost.org/doc/libs/1_52_0/libs/serialization/doc/index.html\" rel=\"nofollow\">boost serialization</a> as model for your implementation. I.e. I'd have some buffered streams to serialize in/out content and expose methods that can serialize to that stream and from it (or construct from it).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-24T12:28:50.440",
"Id": "19892",
"ParentId": "18934",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T14:48:42.260",
"Id": "18934",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Encoding/decoding protocol messages to/from various bits of hardware"
}
|
18934
|
<p>I want to search through an array of n numbers and find the numbers that are repeated. So far I have this code, which does the job, but I find it to be a rather cumbersome method, but I can't seem to find another method of doing it. </p>
<pre><code>class Checknumber{
int [] numbers = new int [5];
Scanner inn = new Scanner(System.in);
boolean b = true;
int temp = -1;
void sjekk(){
System.out.println("Write five numbers");
for(int i = 0; i < numbers.length; i++){
numbers [i] = inn.nextInt();
}
//sjekker om det er like tall i arrayen
System.out.print("\nNumbers that are repeated: ");
for(int i = 0; i < numbers.length; i++){
if(!b){
System.out.print(temp + " ");
}
b = true;
temp = numbers[i];
for(int j = 0; j < numbers.length; j++){
if(i != j && temp == numbers[j] && numbers[j] != -2){
b = false;
numbers[j] = -2;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:19:26.537",
"Id": "30206",
"Score": "0",
"body": "You should tag the language you're using."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:27:06.080",
"Id": "30207",
"Score": "0",
"body": "Do you mean dupplicate numbers, or a set of identical numbers in a series? Should that eliminate the last \"1\" in \"1231\", or the \"3\" in \"12333333456\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:28:15.923",
"Id": "30208",
"Score": "1",
"body": "Another possibility is to sort the array first, for example using [`Arrays.sort()`](http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5B%5D%29). This would bring any repeated numbers next to each other, simplifying the logic needed to find and print them out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T00:44:06.147",
"Id": "30239",
"Score": "0",
"body": "I should have been more clear. If I have a set \"1 2 3 2 1\" then I want the program to print out: \"These numbers are repeating: 1 and 2\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T15:18:33.940",
"Id": "47858",
"Score": "0",
"body": "Please, everybody here, use for-each; this is 2013, not 2003.\n\n for(int i: numbers) {\n }\n\nPlease, eliminate one trivial source of error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:34:36.337",
"Id": "64172",
"Score": "0",
"body": "If you're facing a big data situation, cardinality estimation (http://blog.notdot.net/2012/09/Dam-Cool-Algorithms-Cardinality-Estimation) is a probabilistic way of figuring out how many unique (or repeated) items are in a dataset."
}
] |
[
{
"body": "<p>Create a <code>Map<Integer, Integer></code> (first number is the number you are looking, second is the number of appearences).</p>\n\n<p>Run through your array. Each time you find a number, do <code>map.get(numberFound)</code> to see if you had already found it. If you had not, put the number with a counter of 1. If you had, retrieve the counter, increase it and put it back into the map.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:28:13.490",
"Id": "18937",
"ParentId": "18936",
"Score": "5"
}
},
{
"body": "<p>you may use google collection framework Guava's <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multiset.html\" rel=\"nofollow\"><code>Multiset<Integer></code></a> to find repetating number.</p>\n\n<blockquote>\n <p>Elements of a multiset that are equal to one another (see \"Note on element\n equivalence\", below) are referred to as occurrences of the same single element. \n The total number of occurrences of an element in a multiset is called the count \n of that element (the terms \"frequency\" and \"multiplicity\" are equivalent, but \n not used in this API). Since the count of an element is represented as an int, \n a multiset may never contain more than Integer.MAX_VALUE occurrences of any one element.</p>\n</blockquote>\n\n<pre><code>Multiset<Integer> set = HashMultiset.create();\nvoid sjekk(){\n System.out.println(\"Write five numbers\");\n for(int i = 0; i < numbers.length; i++){\n set.add(inn.nextInt());\n }\n...\nfor(Multiset.Entry<Integer> entry : set.entrySet()){ \n System.out.println(\"Element :-> \"+entry.getElement()+\" Repeat Cnt :-> \"+entry.getCount());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:29:24.473",
"Id": "18938",
"ParentId": "18936",
"Score": "0"
}
},
{
"body": "<pre><code>int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 };\nArrays.sort(numbers);\n\nfor(int i = 1; i < numbers.length; i++) {\n if(numbers[i] == numbers[i - 1]) {\n System.out.println(\"Duplicate: \" + numbers[i]);\n }\n}\n</code></pre>\n\n<p>This sorts the array numerically, then begins iterating the array. It checks the previous element in the array and if it equals the current element, then you have a duplicate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T17:48:25.740",
"Id": "30215",
"Score": "4",
"body": "Best readable. A small suggestion: Add a `while(i < numbers.length && numbers[i] == numbers[i - 1]) ++i;` behind the if statement in the loop to prevent multiple output (according to original behavior)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T00:39:55.517",
"Id": "30237",
"Score": "1",
"body": "Thank you all for answering! I'm very new to programming, so I haven't learned such functions as sort yet, so I see now that there are much easier ways of doing it. I tried this code and it works, however if there are more than two numbers in the array that are similar, it will print that number n-2 times times the number of repetitions within the array. I didn't manage to incorporate the small suggestion below."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T08:42:32.560",
"Id": "30246",
"Score": "0",
"body": "This isn't the most optimal, but it's fast enough. Also, there should probably be a check for multiple duplicates. I would expect [1, 1, 1, 2, 3] to only output \"Duplicate: 1\". This is trivial to implement: `if (numbers[i] == numbers[i - 1] && numbers[i] != lastDup)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T14:54:07.627",
"Id": "47857",
"Score": "0",
"body": "You've modified the original array, which might not have been wanted. Creating a sorted copy would be polite."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:51:59.207",
"Id": "75312",
"Score": "0",
"body": "The biggest problem I have with this solution is that it won't scale to very large n (because you have to hold the entire array in memory at once). But it's an elegant solution for relatively small n (< 1,000,000?)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:35:36.757",
"Id": "18939",
"ParentId": "18936",
"Score": "12"
}
},
{
"body": "<p>I'm gonna throw my 2 cents in aswell :)</p>\n\n<p>If you're allowed to used objects I'd do it like this.</p>\n\n<p>Sets automatically holds non-duplicates so if it contains it it's no chance of the value going in a again.</p>\n\n<pre><code>int[] arrayOfInt = { 1, 2, 3, 5, 1, 2, 7, 8, 9, 10 };\nSet<Integer> notDupes = new HashSet<Integer>();\nSet<Integer> duplicates = new HashSet<Integer>();\nfor (int i = 0; i < arrayOfInt.length; i++) {\n if (!notDupes.contains(arrayOfInt[i])) {\n notDupes .add(arrayOfInt[i]);\n continue;\n }\n duplicates.add(arrayOfInt[i]);\n}\nSystem.out.println(\"num of dups:\" + duplicates.size());\nSystem.out.println(\"num of norls:\" + notDupes.size());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T16:20:50.990",
"Id": "30209",
"Score": "1",
"body": "+1, but you don not know how duplicate you have for a number, so use `Map<Integer,Integer> duplicates; = ..` and `int nbDuplicat = (int) duplicates.get(xNumber)` and `duplicates.put( nbDuplicat == 0 ? 1 : nbDuplicat++)` - You can also `if (!notDupes .add(arrayOfInt[i]);) {\n continue;\n }\n duplicates.add(arrayOfInt[i]);` becaus it it cannot add it, it return `false`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T16:50:05.093",
"Id": "30211",
"Score": "0",
"body": "That was not apart of the question, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T16:43:49.837",
"Id": "30256",
"Score": "1",
"body": "you are right! but my experience in true life have guessed than it will be asked soon,"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:39:41.197",
"Id": "18940",
"ParentId": "18936",
"Score": "7"
}
},
{
"body": "<p>I would use <code>Set</code> for this logic:</p>\n\n<ol>\n<li><p>Create an empty <code>Set</code> <code>MySet</code>, and another empty <code>Set</code> <code>ResultSet</code>.</p></li>\n<li><p>Read each number and perform this on it:</p>\n\n<ol>\n<li>Check if it is in <code>MySet</code>.</li>\n<li>If it's in <code>MySet</code>, then put it in <code>ResultSet</code>.</li>\n<li>If it's not in <code>MySet</code>, then put it in <code>Myset</code>.</li>\n</ol></li>\n<li><p><code>ResultSet</code> contains the required numbers.</p></li>\n</ol>\n\n<p>The benefit of this approach is that the complexity would reduce from O(n<sup>2</sup>) to O(nlog(n)).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T00:41:15.783",
"Id": "30238",
"Score": "1",
"body": "I'd rather just use one set or array as I like to make programs that use as little memory as possible, but I will try this for fun!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T01:17:22.017",
"Id": "30240",
"Score": "0",
"body": "The space complexity is still N :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T04:39:30.287",
"Id": "30296",
"Score": "1",
"body": "@HatoriSanso \"I'd rather just use one set or array as I like to make programs that use as little memory as possible\" Please be careful about [Premature Optimiation](http://en.wikipedia.org/wiki/Program_optimization)! It is good that you are trying to be efficient but realize that 'efficient' in computer terms could mean many things (memory is just the tip of the iceberg). When in doubt: 1. Make it work 2. Make it right 3. Make it fast (aka optimize) -[Kent Beck](http://c2.com/cgi/wiki?MakeItWorkMakeItRightMakeItFast)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T05:12:11.903",
"Id": "30298",
"Score": "0",
"body": "and just to add my 2 cents, if you want to optimise, always calculate the space and time complexity, not just how many copies it uses. In my solution, two copies will be used for n elements( 2n ), and in your solution 1 copy will used (1n) , but the space complexity is same N , so it wont matter much. It is only a issue when you increase the complexity to NlogN or N^2. Also your solution has time complexity of N^2, and the one I wrote has worst case NlogN , so it is more efficient. Two copies of data dont affect space complexity/efficiency."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T00:22:52.630",
"Id": "18957",
"ParentId": "18936",
"Score": "3"
}
},
{
"body": "<p>Others have given alternate solutions. However, since this is Code Review, I'll offer a critique instead, because I think you will learn more from that than by just seeing the answer.</p>\n\n<h3>Interfaces</h3>\n\n<ul>\n<li><code>Checknumber</code> is too vague. I suggest <code>DuplicateNumberDetector</code>.</li>\n<li>In your interfaces (class and method names), pick either English or Norwegian and stick with it. For your comments, use whatever language works for you.</li>\n<li><code>sjekk()</code> (meaning \"check\") is actually responsible for receiving input rather than performing the checking. How misleading!</li>\n</ul>\n\n<h3>Variables</h3>\n\n<ul>\n<li><code>b</code> is very poorly named. I suggest <code>unique</code> instead.</li>\n<li><code>temp</code> is somewhat poorly named. I suggest <code>num</code> instead.</li>\n<li>Only older dialects of C require you to declare all variables at the top. Java lets you declare variables near the point of first use. You should take advantage of that. <code>int temp</code> should be declared inside the <code>for (i)</code> loop, since it is never used outside the loop.</li>\n<li>You might try to pull the declaration of <code>b</code> inside the <code>for (i)</code> loop too. But then you will realize that <code>b</code> refers to the uniqueness of the <em>previous</em> <code>numbers[i]</code>. That reveals a bug: what if the last two numbers are identical (<code>numbers[3] == numbers[4]</code>, but <code>numbers[2] != numbers[3]</code>)? You haven't handled the termination case correctly. Hint: Move your <code>print</code> statement. The lesson to be learned here is that declaring temporary variables far from the point of use is almost as evil and dangerous as using global variables.</li>\n</ul>\n\n<h3>Logic</h3>\n\n<ul>\n<li>You are using <code>-2</code> as a special value to indicate that an array element has already been detected as a duplicate. That's bad because your code will fail if <code>-2</code> happens to be one of the inputs.</li>\n<li>Overwriting the input array is a surprising side effect. That's as unforgivable as sending your computer to a repair shop to install a video card and getting it back with the hard drive reformatted. If you <em>really</em> need to overwrite the input, state so clearly in a comment. You should be able to find a solution to this problem that does not require overwriting.</li>\n<li>Your inner loop has <code>j</code> going from <code>0</code> to the end of the array. That means you are handling every pair twice. You should probably be able to start from <code>i + 1</code> instead, to reduce your processing in half. Handling each pair only once should simplify your logic as well.</li>\n</ul>\n\n<h3>Efficiency</h3>\n\n<ul>\n<li>You have two <code>for</code> loops, each iterating over the entire array. If the array has <em>n</em> elements, then the run time for your algorithm is O(<em>n</em><sup>2</sup>). (Even with the inner-loop optimization mentioned in the previous point, it would still be O(<em>n</em><sup>2</sup>).) For a small homework problem like this, that is perfectly acceptable, because simplicity is the main goal. If you wanted to handle very large arrays, though, it would be more efficient to sort the input first or use a <code>HashMap</code>.</li>\n</ul>\n\n<h3>Separation of concerns</h3>\n\n<ul>\n<li>Your input, processing, and output code are all intertwined. Get into the habit of separating them. Your code will be more reusable and easier to understand.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>public class DuplicateNumberDetector { \n int[] promptInputs(int numberOfInputs) { ... }\n\n // If the order doesn't matter, use Set<Integer> instead\n List<Integer> findDuplicates(int[] numbers) { ... }\n\n void printDuplicates(List<Integer> dups) { ... }\n\n public static void main(String[] args) {\n printDuplicates(findDuplicates(promptInputs(5)));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T18:19:59.750",
"Id": "30149",
"ParentId": "18936",
"Score": "13"
}
},
{
"body": "<p>This is almost the easiest way! <code>hashSet</code> returns false whenever a duplicate number is added to it.</p>\n\n<pre><code>private static void findDuplicateNumber() {\n Set<Integer> hashSet = new HashSet<Integer>();\n\n for(int i=0; i < arr.length; i++){\n boolean unique = hashSet.add(arr[i]);\n if(unique == false)\n System.out.println(\"duplication \" + arr[i]);\n } \n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T14:36:22.303",
"Id": "78754",
"Score": "1",
"body": "You should use `if (!unique) {... }` instead of `if(unique == false)`. Good spotting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T16:02:48.053",
"Id": "78783",
"Score": "0",
"body": "`int[] arr` should be a parameter to this function. (Surely it's not a static member of the class, right?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T16:03:29.737",
"Id": "78784",
"Score": "0",
"body": "It would be better to use new-style for loops: `for (int a : arr) { ... }`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T14:14:42.860",
"Id": "45218",
"ParentId": "18936",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18939",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T15:18:24.963",
"Id": "18936",
"Score": "17",
"Tags": [
"java",
"homework",
"interview-questions",
"sorting",
"search"
],
"Title": "Finding repeating numbers in an array"
}
|
18936
|
<p>Ok, so given the string:</p>
<pre><code>s = "Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School"
</code></pre>
<p>I want to retrieve:</p>
<pre><code>[ ["Born"], ["Honolulu", "Hawaii", "Obama"], ["Columbia", "University"] ...]
</code></pre>
<p>Assuming that we have successfully tokenised the original string, my first psuedocodish attempt was: </p>
<pre><code>def retrieve(tokens):
results = []
i = 0
while i < len(tokens):
if tokens[i][0].isupper():
group = [tokens[i]]
j = i + 1
while i + j < len(tokens):
if tokens[i + j][0].isupper():
group.append(tokens[i + j])
j += 1
else:
break
i += 1
return results
</code></pre>
<p>This is actually quite fast (well compared to some of my trying-to-be-pythonic attempts):</p>
<blockquote>
<p>Timeit: 0.0160551071167 (1000 cycles)</p>
</blockquote>
<p>Playing around with it, the quickest I can get is:</p>
<pre><code>def retrive(tokens):
results = []
group = []
for i in xrange(len(tokens)):
if tokens[i][0].isupper():
group.append(tokens[i])
else:
results.append(group)
group = []
results.append(group)
return filter(None, results)
</code></pre>
<blockquote>
<p>Timeit 0.0116229057312</p>
</blockquote>
<p>Are there any more concise, pythonic ways to go about this (with similar execution times)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T18:47:53.930",
"Id": "30257",
"Score": "0",
"body": "What is your question exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T18:53:24.190",
"Id": "30258",
"Score": "0",
"body": "Yea, I forgot the last line ;) Are there any more concise, pythonic ways to go about this (with similar execution times)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T23:12:12.580",
"Id": "30333",
"Score": "0",
"body": "Your optimized retrive() function doesn't seem to work as expected. I get: ``[['B'], ['H'], ['H'], ['O'], ['C'], ['U'], ['H'], ['L'], ['S']]`` when I run it verbatim."
}
] |
[
{
"body": "<p>Here is a solution using regular expressions</p>\n\n<pre><code>import re\n\ndef reMethod(pat, s):\n return [m.group().split() for m in re.finditer(pat, s)]\n\nif __name__=='__main__':\n from timeit import Timer\n s = \"Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School\"\n pat = re.compile(r\"([A-Z][a-z]*)(\\s[A-Z][a-z]*)*\")\n t1 = Timer(lambda: reMethod(pat, s))\n print \"time:\", t1.timeit(number=1000)\n print \"returns:\", reMethod(pat, s)\n</code></pre>\n\n<p>Ouptut:</p>\n\n<pre><code>time: 0.0183469604187\nreturns: [['Born'], ['Honolulu', 'Hawaii', 'Obama'], ['Columbia', 'University'], ['Harvard', 'Law', 'School']]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:31:37.290",
"Id": "30263",
"Score": "0",
"body": "I never thought about using regexs actually, this is a good alternative and the performance is around the same"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:55:47.747",
"Id": "30266",
"Score": "0",
"body": "Yeah, it didn't turn out to be quite as fast, but it felt a waste not to post it once I had it coded up."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:16:15.740",
"Id": "18968",
"ParentId": "18965",
"Score": "3"
}
},
{
"body": "<p>A trivial optimisation that iterates on the tokens instead of by index (remember that in Python lists are iterables, it's unPythonic to iterate a list by index):</p>\n\n<pre><code>def retrieve(tokens):\n results = []\n group = []\n for token in tokens:\n if token[0].isupper():\n group.append(token)\n else:\n if group: # group is not empty\n results.append(group)\n group = [] # reset group\n return results\n</code></pre>\n\n<p>A solution like @JeremyK's with a list comprehension and regular expressions is always going to be more compact. I am only giving this answer to point out how lists should be iterated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:27:43.923",
"Id": "30262",
"Score": "0",
"body": "Thanks - this is an improvement alright. I thought that using `xrange` would be faster as it doesn't return items, just index values, but thinking about it if you are using the values of what's being iterated it's faster"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:18:27.160",
"Id": "18969",
"ParentId": "18965",
"Score": "4"
}
},
{
"body": "<p>If you asked me, a pythonic solution would be the most readable solution. However in general, readable solutions are not always going to be the fastest. You can't have both, these are conflicting goals.</p>\n\n<p>Pedro has covered what changes you can do to make it bit more pythonic so I won't repeat that. I can't think of anything else you can do to optimize that any further. However if you want a more purely pythonic solution (IMO), you can do this.</p>\n\n<p>Use <a href=\"http://docs.python.org/2/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby</code></a>. It groups consecutive items together with a common key into groups. Group them by whether they are capitalized and filter out the non-capitalized words.</p>\n\n<p>This could be done as a one-liner but for readability, I'd write it like this:</p>\n\n<pre><code>from itertools import groupby\n\ninput_str = 'Born in Honolulu Hawaii Obama is a graduate of ' +\n 'Columbia University and Harvard Law School'\nwords = input_str.split()\ndef is_capitalized(word):\n return bool(word) and word[0].isupper()\nquery = groupby(words, key=is_capitalized)\nresult = [list(g) for k, g in query if k]\n</code></pre>\n\n<p>This would run roughly twice as slow as your implementation, based on my tests on 1000 iterations.</p>\n\n<pre>\n0.0130150737235 # my implementation\n0.0052368790507 # your implementation\n</pre>\n\n<p>You decide what your goals are.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T03:57:27.140",
"Id": "30295",
"Score": "0",
"body": "I think `isCapitalized` could be written more simply as `word[:1].isupper()`. (Although I think `is_capitalized` would be a more standard name.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T04:54:33.437",
"Id": "30297",
"Score": "0",
"body": "Ah you're right about the name, I've been doing too much Java work lately. ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:25:07.473",
"Id": "18972",
"ParentId": "18965",
"Score": "3"
}
},
{
"body": "<p>I get a slight improvement by tweaking your <code>retrive()</code> function:</p>\n\n<pre><code>def retrieve1(tokens):\n results = []\n group = []\n for i in xrange(len(tokens)):\n if tokens[i][0].isupper():\n group.append(tokens[i])\n else:\n results.append(group)\n group = []\n results.append(group)\n return filter(None, results)\n\ndef retrieve2(tokens):\n results = []\n group = []\n for token in tokens:\n if token[0].isupper():\n group.append(token)\n elif group:\n results.append(group)\n group = []\n if group:\n results.append(group)\n return results\n\ns = \"Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School\"\n\nif __name__ == \"__main__\":\n import timeit\n print timeit.timeit('retrieve1(s.split(\" \"))', setup=\"from __main__ import (retrieve1, s)\", number=100000)\n print timeit.timeit('retrieve2(s.split(\" \"))', setup=\"from __main__ import (retrieve2, s)\", number=100000)\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>1.00138902664 (retrieve1)\n0.744722127914 (retrieve2)\n</code></pre>\n\n<p>It's not necessary to iterate via <code>xrange()</code> as you can iterate <code>tokens</code> directly, and you need only append <code>group</code> to <code>results</code> if <code>group</code> is not an empty list -- no need to <code>filter()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T00:15:22.910",
"Id": "19006",
"ParentId": "18965",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18969",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T17:34:43.633",
"Id": "18965",
"Score": "3",
"Tags": [
"python",
"algorithm"
],
"Title": "Retrieving lists of consecutive capitalised words from a list"
}
|
18965
|
<p><a href="http://projecteuler.net/problem=81" rel="nofollow">Project Euler problem 81</a> asks:</p>
<blockquote>
<p>In the 5 by 5 matrix below,</p>
<pre><code>131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
</code></pre>
<p>the minimal path sum from the top left to
the bottom right, by only moving to the right and down, is </p>
<pre><code>131 → 201 → 96 → 342 → 746 → 422 → 121 → 37 → 331
</code></pre>
<p>and is equal to 2427.</p>
<p>Find the minimal path sum, in <a href="http://projecteuler.net/project/matrix.txt" rel="nofollow"><code>matrix.txt</code></a> (right click and 'Save
Link/Target As...'), a 31K text file containing a 80 by 80 matrix,
from the top left to the bottom right by only moving right and down.</p>
</blockquote>
<p>Below is a Go solution using <a href="http://en.wikipedia.org/wiki/Uniform-cost_search" rel="nofollow">uniform-cost search</a> to build a search tree. It works on the toy small problem but on the 80x80 matrix it runs out of space. Could anyone that is up for a challenge help improve this still using this solution? By the way, this is the first program of any consequence I have written in Go and I am try to learn the language.</p>
<pre><code>package main
import (
"bufio"
"container/heap"
"fmt"
"io"
"os"
"strconv"
"strings"
)
var matrix [][]int = make([][]int, 0, 80)
func main() {
f, _ := os.Open("matrix.txt")
r := bufio.NewReader(f)
defer f.Close()
for {
s, ok := r.ReadString('\n')
if ok == io.EOF {
break
}
s = strings.Trim(s, "\n")
stringArr := strings.Split(s, ",")
tmp := make([]int, 0)
for i := 0; i < 80; i++ {
v, _ := strconv.Atoi(stringArr[i])
tmp = append(tmp, v)
}
matrix = append(matrix, tmp)
}
//fmt.Println(matrix)
fmt.Println(uniformCostSearch(treeNode{0, 0, 4445, 0}))
}
func (node treeNode) getPriority(y, x int) int {
return matrix[y][x]
}
type Node interface {
// Neighbors returns a slice of vertices that are adjacent to v.
Neighbors(v Node) []Node
}
// An treeNode is something we manage in a priority queue.
type treeNode struct {
X int
Y int
priority int // The priority of the item in the queue.
Index int // The index of the item in the heap.
}
func (node treeNode) Neighbors() []*treeNode {
tmp := []*treeNode{ //&treeNode{X: node.X - 1, Y: node.Y},
&treeNode{X: node.X + 1, Y: node.Y},
//&treeNode{X: node.X, Y: node.Y - 1},
&treeNode{X: node.X, Y: node.Y + 1}}
childNodes := make([]*treeNode, 0)
for _, n := range tmp {
if n.X >= 0 && n.Y >= 0 && n.X <= 80 && n.Y <= 80 {
n.priority = node.priority + n.getPriority(n.Y, n.X)
childNodes = append(childNodes, n)
}
}
return childNodes
}
func uniformCostSearch(startNode treeNode) int {
frontier := make(PriorityQueue, 0, 10000)
closedSet := make([]*treeNode, 0)
heap.Push(&frontier, &startNode)
for frontier.Len() > 0 {
fmt.Println(frontier.Len())
currentNode := heap.Pop(&frontier).(*treeNode)
if currentNode.X == 79 && currentNode.Y == 79 {
return currentNode.priority
} else {
closedSet = append(closedSet, currentNode)
}
possibleMoves := currentNode.Neighbors()
for _, move := range possibleMoves {
explored := false
for _, seen := range closedSet {
if seen.X == move.X && seen.Y == move.Y {
explored = true
break
}
}
if explored {
continue
}
// check that frontier does not contain this node and
// if it does then compare the cost so far
for index, node := range frontier {
if node.X == move.X && node.Y == move.Y && move.priority < node.priority {
fmt.Println("removing")
heap.Remove(&frontier, index)
break
}
}
heap.Push(&frontier, move)
}
}
return -1
}
// A PriorityQueue implements heap.Interface and holds treeNodes.
type PriorityQueue []*treeNode
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the lowest priority so we use greater than here.
return pq[i].priority < pq[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].Index = i
pq[j].Index = j
}
func (pq *PriorityQueue) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
// To simplify indexing expressions in these methods, we save a copy of the
// slice object. We could instead write (*pq)[i].
a := *pq
n := len(a)
a = a[0 : n+1]
item := x.(*treeNode)
item.Index = n
a[n] = item
*pq = a
}
func (pq *PriorityQueue) Pop() interface{} {
a := *pq
n := len(a)
item := a[n-1]
item.Index = -1 // for safety
*pq = a[0 : n-1]
return item
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code could be less fragile and more idiomatic. For example,</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"container/heap\"\n \"errors\"\n \"fmt\"\n \"io\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype Matrix [][]int\n\ntype Node struct {\n x, y int\n}\n\ntype Item struct {\n value Node\n priority int\n index int\n}\n\ntype PriorityQueue []*Item\n\nfunc (pq PriorityQueue) Len() int { return len(pq) }\n\nfunc (pq PriorityQueue) Less(i, j int) bool {\n return pq[i].priority < pq[j].priority\n}\n\nfunc (pq PriorityQueue) Swap(i, j int) {\n pq[i], pq[j] = pq[j], pq[i]\n pq[i].index = i\n pq[j].index = j\n}\n\nfunc (pq *PriorityQueue) Push(x interface{}) {\n a := *pq\n n := len(a)\n item := x.(*Item)\n item.index = n\n a = append(a, item)\n *pq = a\n}\n\nfunc (pq *PriorityQueue) Pop() interface{} {\n a := *pq\n n := len(a)\n item := a[n-1]\n item.index = -1\n *pq = a[0 : n-1]\n return item\n}\n\nfunc (pq *PriorityQueue) changePriority(item *Item, priority int) {\n heap.Remove(pq, item.index)\n item.priority = priority\n heap.Push(pq, item)\n}\n\nfunc readMatrix() (Matrix, error) {\n var matrix Matrix\n file, err := os.Open(`matrix.txt`)\n if err != nil {\n return nil, err\n }\n defer file.Close()\n rdr := bufio.NewReader(file)\n for {\n line, err := rdr.ReadString('\\n')\n if err != nil {\n if err == io.EOF && len(line) == 0 {\n break\n }\n return nil, err\n }\n var row []int\n for _, s := range strings.Split(line[:len(line)-1], \",\") {\n n, err := strconv.Atoi(s)\n if err != nil {\n return nil, err\n }\n row = append(row, n)\n }\n matrix = append(matrix, row)\n }\n return matrix, nil\n}\n\nfunc (i Item) neighbors(matrix Matrix) []*Item {\n items := make([]*Item, 0, 2)\n x, y, p := i.value.x, i.value.y, i.priority\n if x := x + 1; x < len(matrix[y]) {\n items = append(items, &Item{value: Node{x, y}, priority: p + matrix[y][x]})\n }\n if y := y + 1; y < len(matrix) {\n items = append(items, &Item{value: Node{x, y}, priority: p + matrix[y][x]})\n }\n return items\n}\n\nfunc UniformCostSearch(matrix Matrix) (int, error) {\n if len(matrix) < 0 || len(matrix[0]) < 0 {\n return 0, errors.New(\"UniformCostSearch: invalid root\")\n }\n root := Item{value: Node{0, 0}, priority: matrix[0][0]}\n if len(matrix) < 0 || len(matrix[len(matrix)-1]) < 0 {\n return 0, errors.New(\"UniformCostSearch: invalid goal\")\n }\n goal := Node{len(matrix[len(matrix)-1]) - 1, len(matrix) - 1}\n frontier := make(PriorityQueue, 0, len(matrix)*len(matrix[len(matrix)-1]))\n heap.Push(&frontier, &root)\n explored := make(map[Node]bool)\n for {\n if len(frontier) == 0 {\n return 0, errors.New(\"UniformCostSearch: frontier is empty\")\n }\n item := heap.Pop(&frontier).(*Item)\n if item.value == goal {\n return item.priority, nil\n }\n explored[item.value] = true\n neighbor:\n for _, n := range item.neighbors(matrix) {\n if explored[n.value] {\n continue neighbor\n }\n for _, f := range frontier {\n if f.value == n.value {\n if f.priority > n.priority {\n frontier.changePriority(f, n.priority)\n }\n continue neighbor\n }\n }\n heap.Push(&frontier, n)\n }\n }\n return 0, errors.New(\"UniformCostSearch: unreachable\")\n}\n\nfunc main() {\n matrix, err := readMatrix()\n if err != nil {\n fmt.Println(err)\n os.Exit(1)\n }\n minPathSum, err := UniformCostSearch(matrix)\n if err != nil {\n fmt.Println(err)\n os.Exit(1)\n }\n fmt.Println(minPathSum)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T08:44:56.250",
"Id": "34712",
"Score": "6",
"body": "Thanks you for this answer, but it would have been nice to explain the main changes that you did: it avoids the need to compare the two versions and trying to figure out the reasons of the changes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T02:49:17.460",
"Id": "19374",
"ParentId": "18967",
"Score": "1"
}
},
{
"body": "<p>The uniform-cost search, an algorithm based on graph theory, is unnecessarily complex for this problem. You should be able to use a dynamic programming algorithm instead, which requires just a matrix for storage.</p>\n\n<p>Consider how you can reduce the problem to a base case. Let's take the 5×5 example in the question, and consider just the bottom-right 2×2 submatrix:</p>\n\n<pre><code> 121 956\n 37 331\n</code></pre>\n\n<p>Starting at 331, the minimal path to the bottom-right is 331. Starting at 37, the minimum distance is 37 + 331 = 368, because you must go right. Starting at 956, the minimum distance is 956 + 331 = 1287, because you must go down. Starting at 121, what do you do? Since 368 < 1287, it's cheaper to go down and join the 37 → 331 path, for a distance of 489. Let's store all of that information as a matrix, where each element is the minimum distance from that element to the bottom-right corner:</p>\n\n<pre><code> 489 1287\n 368 331\n</code></pre>\n\n<p>Expanding that matrix to 2×5 for the bottom two rows:</p>\n\n<pre><code>2222 1685 986 489 1287\n2429 1624 892 368 331\n</code></pre>\n\n<p>Continuing all the way,</p>\n\n<pre><code>2427 2576 1903 1669 1566\n2296 2095 1999 1876 1548\n2852 2460 1657 911 1398\n2222 1685 986 489 1287\n2429 1624 892 368 331\n</code></pre>\n\n<p>Simply read out the answer from the top-left, which is 2427.</p>\n\n<p>For an input matrix of dimensions <em>m</em> × <em>n</em>, the memory required is <em>m</em> × <em>n</em>. Each element can be filled in O(1) time (\"Is it cheaper to go right or go down?\") for a total running time of O(<em>m</em> × <em>n</em>). Any computer should be able to fill an 80 × 80 matrix effortlessly. (The only concern might be overflow, but it turns out that the answer fits comfortably within 31 bits.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T20:32:57.453",
"Id": "35716",
"ParentId": "18967",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T19:05:42.233",
"Id": "18967",
"Score": "5",
"Tags": [
"algorithm",
"programming-challenge",
"matrix",
"search",
"go"
],
"Title": "Golang solution to Project Euler #81 (min path through a matrix)"
}
|
18967
|
<p>I have a method that contains a bunch of NSDictionaries (in fact, the only reason I have that method is to create those NSDictionaries). While I don't believe there are enough NSDictionaries initialized to visibly slow the code down as of yet, that is a good possibility in the future. I am currently just creating all the NSDictionaries separately, but is there a better way to do it while keeping its readability?</p>
<pre><code>- (void)items {
NSDictionary *item1 = @{
@"label" : @"item1",
@"icon" : [UIImage imageNamed:@"item1-Icon"],
@"identifier": @"item1"};
NSDictionary *item2 = @{
@"label" : @"item2",
@"icon" : [UIImage imageNamed:@"item2-Icon"],
@"identifier": @"item2"};
NSDictionary *item3 = @{
@"label" : @"item3",
@"icon" : [UIImage imageNamed:@"item3-Icon"],
@"identifier": @"item3"};
NSDictionary *item4 = @{
@"label" : @"item4",
@"icon" : [UIImage imageNamed:@"item4-Icon"],
@"identifier": @"item4"};
items = [ @[item1, item2, item3, item4] mutableCopy];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T22:55:10.783",
"Id": "39204",
"Score": "0",
"body": "Maybe this is sort of artificial (as perhaps you've simplified the code to show it here), but you have an ivar named `items` and a method named `items`. I would normally consider that a getter. Here, though, you're setting the `items` ivar, but not returning it (this method is `void`). If you want *lazy initialization*, then I'd make it `-(NSMutableArray*) items;`, and if the content is not dynamic, then check whether the *ivar* `items` is initialized yet, and if so, don't do it again."
}
] |
[
{
"body": "<blockquote>\n <p>«Two or more, use a for»<br>\n — Edsger W. Dijkstra</p>\n</blockquote>\n\n<p>Okay, I am not using a for-loop, but an enumeration</p>\n\n<pre><code>NSArray *itemArray = @[\n @[@\"item1\",@\"item1-Icon\",@\"item1\"],\n @[@\"item2\",@\"item2-Icon\",@\"item2\"],\n @[@\"item3\",@\"item3-Icon\",@\"item3\"],\n @[@\"item4\",@\"item4-Icon\",@\"item4\"]\n];\n\nNSMutableArray *items = [NSMutableArray array];\n[itemArray enumerateObjectsUsingBlock:^(NSArray *itemProperties, NSUInteger idx, BOOL *stop) {\n [items addObject: @{ @\"label\": itemProperties[0],\n @\"icon\": [UIImage imageNamed:itemProperties[1]],\n @\"identifier\": itemProperties[2]\n }];\n}];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T22:46:10.503",
"Id": "39202",
"Score": "0",
"body": "This declaration of `itemArray` is still prone to cut and paste errors, especially as the list grows. Better to use a loop as [in the other answer](http://codereview.stackexchange.com/a/20319/16775)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T23:53:19.067",
"Id": "39205",
"Score": "0",
"body": "in the end we dont know where the names come from. if they are as regular as in the example, they can be created as in the other answer. it they must be read for some source it wont work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-21T01:26:54.713",
"Id": "39208",
"Score": "0",
"body": "You can only review the code you're given, and the code provided used a repeating pattern. If you're going to recommend a solution that's more brittle, requires more code to grow the array (relative to the other answer, that just involves changing the loop's end index), and is more verbose, *in order to accomodate a different use case*, that's not presented in the question, then you should document that in your answer. Otherwise, the answer is encouraging code cut-n-pasting."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T21:15:46.433",
"Id": "19004",
"ParentId": "18971",
"Score": "3"
}
},
{
"body": "<p>To avoid code redundancy, its better to put this within a loop like the one below:</p>\n\n<pre><code>for (int i = 0; i < 4; i++) {\n NSDictionary *item = @{\n @\"label\" : [NSString stringWithFormat:@\"item%d\",i+1],\n @\"icon\" : [UIImage imageNamed:[NSString stringWithFormat:@\"item%d-Icon\",i+1]],\n @\"identifier\": [NSString stringWithFormat:@\"item%d\",i+1]};\n [items addObject:item];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T22:48:44.390",
"Id": "39203",
"Score": "0",
"body": "+1 for the loop, but in general, I'd advise against naming loop variables `i` when something more meaningful is available. `itemIdx` or `index` seems better to me. More important, though, is if the index is looping from 1 to 4, then loop from 1 to 4. Don't loop from 0 to 3, and then have to add 1 to the index every time you use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T08:45:20.053",
"Id": "39253",
"Score": "0",
"body": "Hi @Nate, I am defiantly agree with u, that loop have to be 1 to 4. But this answer saws only concept of add different NSDictionary objects to NSMutableArray. Naming convention and 1 to 4 things are besides of that, Thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T11:11:06.877",
"Id": "20319",
"ParentId": "18971",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:02:54.537",
"Id": "18971",
"Score": "2",
"Tags": [
"objective-c",
"hash-map"
],
"Title": "Is there a better way of showing multiple NSDictionaries?"
}
|
18971
|
<p>JavaScript doesn't offer a module system. There are many third-party solutions, like <code>require.js</code> or jQuery's <code>$.getScript</code>. Most, while good, they bring dependencies, extra kbs and/or limit your folder structures. Sometimes it's necessary to make a .js file self-sufficient. This said, what is the smallest snippet that can be inserted at the top of a .js file, which will emulate "import", so it can load other scripts before running itself?</p>
<p>The .js file should look like this, for example. Notice the addition is just a small one-liner:</p>
<pre><code>(function(i,m,p,o,r,t){for(p=i.length,o=0;o<p;++o){r=(t=document).createElement('script');r.src=i[o];r.onload=function(){!--p&&m()};t.head.appendChild(r); }; })
(['http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js','http://underscorejs.org/underscore-min.js'],
function main(){
console.log('jQuery loaded:',$);
console.log('underscore.js loaded:',_);
});
</code></pre>
<p>For clarity, the top function above, expanded, is equivalent to:</p>
<pre><code>(function (u, f, l, i, a, d) {
for (l = u.length, i = 0; i < l; ++i) {
a = (d = document).createElement('script');
a.src = u[i];
a.onload = function () {
!--l && f()
};
d.head.appendChild(a);
};
})
</code></pre>
<p>Can this be minimized even further?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:04:14.460",
"Id": "30269",
"Score": "1",
"body": "Awful and should't be done, but http://www.phpied.com/javascript-include/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:11:11.040",
"Id": "30270",
"Score": "0",
"body": "@jacktheripper care to explain?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:11:33.733",
"Id": "30271",
"Score": "6",
"body": "@Dokkat If you wish for people to make suggestions about how this could be improved, it's best not to minify it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:12:27.220",
"Id": "30272",
"Score": "0",
"body": "@JonathanSampson I don't want to improve upon my code, it's just to show the concept. I was expecting there to be something much better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:13:05.447",
"Id": "30273",
"Score": "4",
"body": "@Dokkat Fine, if you want people to understand *the concept*, don't make it more difficult by providing minified code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:13:25.670",
"Id": "30274",
"Score": "0",
"body": "Smallest as in smallest footprint? Would that include ugly and slow packers that obfuscates?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:14:50.513",
"Id": "30275",
"Score": "0",
"body": "@JonathanSampson but the code is not 'minified', I have already coded it small for the purpose... I can increase it if you want to - do you? But that's nothing complicated, it just takes an array of strings (argument 1), adds every string to document.head as a <script> tag and runs the callback (argument 2) when those are all loaded. The other arguments are internal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:15:51.970",
"Id": "30276",
"Score": "0",
"body": "Are you using all of those initial args as a way to avoid using var to define them in your block?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:16:50.280",
"Id": "30277",
"Score": "0",
"body": "Yes, p, o, r and t are for avoiding var, as it is 4 chars long."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:18:13.553",
"Id": "30278",
"Score": "0",
"body": "@Dokkat I've taken the liberty of improving the code's readability. When much of it is on one line, and full of single-char variables, it doesn't lend itself to being easily understood."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:18:31.073",
"Id": "30279",
"Score": "0",
"body": "`document.head` is not avail in IE8-. Care to add browser compat and other \"rules\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:19:12.840",
"Id": "30280",
"Score": "3",
"body": "@Dokkat Jesus, stop minifying your code. I'm trying to read it! `:P`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:19:36.727",
"Id": "30281",
"Score": "0",
"body": "@JonathanSampson thank you very much for the edit, but sorry, I had to rollback. The whole idea is to using a compact one liner on the top of the file. Expanding it makes the idea unclear. We could add the function expanded after the snippet. What do you think?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:20:49.757",
"Id": "30282",
"Score": "0",
"body": "@Dokkat You can minify whenever you go to use in production. Don't minify it here - it is here to be read and understood. You are not helping the community by insisting upon hard-to-read formatting. I'm asking again, please leave it legible or remove the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:24:56.203",
"Id": "30283",
"Score": "0",
"body": "@JonathanSampson again, it does not demonstrate the idea if the function is huge with many lines. The idea is to have a compact, minified code to include on the top of a .js file, that will not distract a reader from the actual code. Please try to understand what I'm saying!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:25:42.537",
"Id": "30284",
"Score": "0",
"body": "@Dokkat are you writing software for consumption by 28.8bps modems?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:31:40.317",
"Id": "30292",
"Score": "1",
"body": "http://dean.edwards.name/packer/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T02:07:47.463",
"Id": "30339",
"Score": "0",
"body": "This was my most misunderstood question. Thank you all anyway."
}
] |
[
{
"body": "<p>Here is what I do:</p>\n\n<pre><code>var a_script= document.createElement('script');\na_script.src = 'http://www.blah.com/some_script.js';\ndocument.head.appendChild(a_script);\n</code></pre>\n\n<p>I should mention that in production I pretty much always combine all javascript files into one larger, minified, and google <a href=\"https://developers.google.com/closure/compiler/docs/gettingstarted_ui\" rel=\"nofollow\">closure compiled file</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:19:39.623",
"Id": "30285",
"Score": "1",
"body": "He's actually doing the same thing, but his fires off on the load event so it's a little more precise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T05:20:24.667",
"Id": "30299",
"Score": "0",
"body": "I do almost the same thing, I usually append to the `body` though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:12:43.393",
"Id": "18974",
"ParentId": "18973",
"Score": "2"
}
},
{
"body": "<p>Most JavaScript libraries add properties to the window object so one alternative would be to test for those properties. For example</p>\n\n<pre><code>m = [ \"$\", //jQuery\n \"_\" // underscore.js\n ];\ntries = 5000;\n(function loaded( ) {\n var i = m.length;\n\n while( i-- ) {\n if( !window[m[i]] ) { \n return --tries ? setTimeout( loaded, 1 ) : failed();\n }\n }\n done(); \n}())\n</code></pre>\n\n<p>And in one line it looks like this</p>\n\n<pre><code>m=[\"$\",\"_\"];tries=5e3;(function e(){var t=m.length;while(t--){if(!window[m[t]]){return--tries?setTimeout(e,1):failed()}}done()})()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T13:12:00.667",
"Id": "30312",
"Score": "0",
"body": "I don't think this is really relevant. The question is not how to detect the all of the external dependencies have been loaded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T02:06:24.877",
"Id": "30338",
"Score": "0",
"body": "To be honest, while this doesn't answer, it's better than the other answers as it (almost) does what I asked. I'll stay with my own snippet this time. );"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T23:16:10.790",
"Id": "18980",
"ParentId": "18973",
"Score": "1"
}
},
{
"body": "<p>I normally wouldn't suggest to compress this specific JavaScript file. The reason is because it's really powerful technique what you are trying to achieve, and it's on the included files where you need to put the effort on the compression, as they will tend to be longer than such a script as you are describing.</p>\n\n<p>I personally use the following snippet, which I consider short because I have seen that it's unobtrusive, not sure if it's shorter than the one you are suggesting.</p>\n\n<pre><code>//JP_js-css_request.js\n\n<!-- Append js and css to the <head> of the document on demand based on the page -->\n\nfunction loadjscssfile(filename, filetype){\n\n switch (filetype)\n {\n case \"js\":\n {\n var fileref=document.createElement('script')\n\n fileref.setAttribute(\"type\",\"text/javascript\");\n fileref.setAttribute(\"src\", filename);\n }\n break;\n\n case \"css\":\n {\n var fileref=document.createElement(\"link\")\n fileref.setAttribute(\"rel\", \"stylesheet\");\n fileref.setAttribute(\"type\", \"text/css\");\n fileref.setAttribute(\"href\", filename);\n }\n break;\n\n default: break;\n }\n\n\n if (typeof fileref!=\"undefined\") document.getElementsByTagName(\"head\")[0].appendChild(fileref)\n}\n\nvar filesadded=\"\" //list of files already added\n\nfunction checkloadjscssfile(filename, filetype){\n if (filesadded.indexOf(\"[\"+filename+\"]\")==-1){\n loadjscssfile(filename, filetype)\n filesadded+=\"[\"+filename+\"]\" //add to list of files already added, in the form of \"[filename1],[filename2],etc\"\n }\n}\n</code></pre>\n\n<p>I place this script in the head as and when I want to call a CSS or JS to be re-used but I want to check if it's been included already at the head we call <code>loadjscssfile( [path_to_file/filename.extension]</code>, js or css.</p>\n\n<p>That for me takes care of it. Also keeping this file editable (as it kind of short) allows you to do modifications that can affect many files and centralizing the process. Or for example if you want to add import for CSS, etc. One thing to mention is that if you are including jQuery libraries or Prototype, or Scriptaculous etc, you need to be careful to call this file at the end <code></head></code>. The reason is that if it appends the file after a library can affect the bindings of functions related by another library.</p>\n\n<p>So in short if you have</p>\n\n<pre><code>jQuery\njQuery UI v-xxx\nMootools\nScriptaculous\nPrototype\n</code></pre>\n\n<p>libraries, you need to not only avoid conflict between libraries but to ensure that all JS framework or heavy stuff are loaded firstly. That ensures that you can call files to append to the head just after the JavaScript file is included. So far, it has heavily helped me out because I use <a href=\"http://jscompress.com\" rel=\"nofollow\">http://jscompress.com</a> and after checking a JS works good on a project, I compress the file and call <code>loadjscssfile()</code> as a function over that one. Although sometimes it takes some time to load depending on how big the resource is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T01:44:32.613",
"Id": "62842",
"Score": "0",
"body": "Also, you should look into this framework, might be just what you are looking for. EnhanceJS version 1.1 - Test-Driven Progressive Enhancement * http://enhancejs.googlecode.com/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T01:41:48.157",
"Id": "18984",
"ParentId": "18973",
"Score": "2"
}
},
{
"body": "<p>I advise against your \"smallest\" approach, I think you set your priorities wrong.</p>\n\n<p>IMO you should avoid:</p>\n\n<ul>\n<li>Minifying non-production code, as processing time is cheaper than developer time;</li>\n<li>Premature optimization, such as declaring extra arguments to save 4 characters by avoiding using var (for 3 variables, that is 1.3 characters saved per variable);</li>\n<li>Using variables with 3 or less characters, 1-char variables being the Megazord of this flaw.</li>\n</ul>\n\n<p>All these things will reduce the readability and maintainability of your code. And <strong>what for?</strong> The gain is infinitesimal, and the risk is large.</p>\n\n<p>Just including the minified JQuery you give as an example increases the code by <strong>93 thousand</strong> characters. What is the use of worrying about saving 50 characters out of 100k?</p>\n\n<p>You can implement your JS normally and then minify in production, you can reduce image sizes, you can use CSS sprites... there are a lot of better ways to save bandwidth.<br>\n(YMMV)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:35:19.077",
"Id": "19026",
"ParentId": "18973",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "18980",
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:01:29.067",
"Id": "18973",
"Score": "4",
"Tags": [
"javascript",
"dom",
"http",
"modules"
],
"Title": "What is the shortest snippet that emulates `include` in JavaScript without third-party scripts?"
}
|
18973
|
<p>This implementation of range() is very fast:</p>
<pre><code>RANGE = []; for (var i=0; i<65536; ++i) RANGE.push(i-32768);
range = function(a,b){ return RANGE.slice(a+32768,b+32768); };
</code></pre>
<p>Are there downsides in using this approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T00:45:39.243",
"Id": "30286",
"Score": "0",
"body": "Why are you subtracting `32k`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T00:46:33.843",
"Id": "30287",
"Score": "0",
"body": "@ŠimeVidas To allow for negative ranges"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T02:05:31.217",
"Id": "30288",
"Score": "2",
"body": "@Dokkat: It might be more intuitive to run the loop from `-32k` to `+32k`"
}
] |
[
{
"body": "<p>relatively speaking-</p>\n\n<p>1) its a bit heavy on the memory use, requiring the memory for a property + mem of a number for each integer in the possible range</p>\n\n<p>2) always consumes the memory and cpu needed to intialize, even if the script never has use for it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T00:50:43.843",
"Id": "30289",
"Score": "0",
"body": "Interesting. 2 can be solved initializing the array only after the first use of range(); this would aggravate 1, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T00:56:31.897",
"Id": "30290",
"Score": "1",
"body": "I don't think lazy loading it would have any significant effect on #1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T02:04:26.213",
"Id": "30291",
"Score": "0",
"body": "+1. Lazy loading would just make the first invocation of `range` slower than the average implementation :-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T00:49:01.940",
"Id": "18976",
"ParentId": "18975",
"Score": "2"
}
},
{
"body": "<p>Range could be declared as an <a href=\"http://www.khronos.org/registry/typedarray/specs/latest/#6\" rel=\"nofollow\">Arraybuffer</a>, which supports both method slice and an arrayview of just a part of the buffer without copying the data. Returning an arrayview would mitigate the problem of memory consumption and using typed array would use ~128k memory instead of 512k.</p>\n\n<p>Also the function could possibly be self-modifying doing the initialization at the first call.</p>\n\n<pre><code>range = function(a,b) { initialize_range;\n range = function(a,b) { return RANGE.slice(a,b) };\n return RANGE.slice(a,b); }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T11:59:56.953",
"Id": "18977",
"ParentId": "18975",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T00:39:35.270",
"Id": "18975",
"Score": "0",
"Tags": [
"javascript",
"optimization"
],
"Title": "This JavaScript implementation of range is fast. What are it's downsides?"
}
|
18975
|
<p>In SQL there is no way to do an "INSERT... SELECT". If you want to do it without using raw SQL in several places of your code you can create custom SQL compilation.</p>
<p>There is an example about how to do "INSERT...SELECT" in <a href="http://docs.sqlalchemy.org/en/rel_0_7/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct" rel="nofollow">SA documentation</a>. This example doesn't support column in the INSERT part of the sentence, some thing like: INSERT into table(col1, col2)...".</p>
<p>I've modified the example to that, this support table ("INSERT INTO table (SELECT...)") or columns ("INSERT INTO table (col1, col2) (SELECT...)".</p>
<p>Please, have a look an comment :)</p>
<pre><code>from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.ext.compiler import compiles
class InsertFromSelect(Executable, ClauseElement):
def __init__(self, insert_spec, select):
self.insert_spec = insert_spec
self.select = select
@compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
if type(element.insert_spec) == list:
columns = []
for column in element.insert_spec:
if element.insert_spec[0].table != column.table:
raise Exception("Insert columns must belong to the same table")
columns.append(compiler.process(column, asfrom=True))
table = compiler.process(element.insert_spec[0].table)
columns = ", ".join(columns)
sql = "INSERT INTO %s (%s) (%s)" % (
table, columns,
compiler.process(element.select))
else:
sql = "INSERT INTO %s (%s)" % (
compiler.process(element.insert_spec, asfrom=True),
compiler.process(element.select))
return sql
</code></pre>
<p>Example of its use with columns:</p>
<pre><code>InsertFromSelect([dst_table.c.col2, dst_table.c.col1], select([src_table.c.col1, src_table.c.col1]))
</code></pre>
<p>Example of its use only with a table:</p>
<pre><code>InsertFromSelect(dst_table, select(src_table]))
</code></pre>
<p>This works for me, but I want to hear other opinions.</p>
|
[] |
[
{
"body": "<pre><code>columns.append(compiler.process(column, asfrom=True))\n</code></pre>\n\n<p>should be simply</p>\n\n<pre><code>columns.append(column.name)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>table = compiler.process(element.insert_spec[0].table)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>table = compiler.process(element.insert_spec[0].table, asfrom=True)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-27T17:44:58.473",
"Id": "26675",
"ParentId": "18978",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T22:55:26.473",
"Id": "18978",
"Score": "1",
"Tags": [
"python",
"sql"
],
"Title": "SQLAlchemy - InsertFromSelect with columns support"
}
|
18978
|
<p>Here is a little interpreter I wrote for a simple stack-based language. It is my first attempt at a complete Haskell program, beyond glorified calculator use.</p>
<p>I'd like very much to get an expert's opinon on stylistic matters.</p>
<p>Also, although the thing runs fine, on a test program it seems to suffer from a space leak: I see an increasing amount of Map objects in Drag state, at one particular spot in the code (where the SCC "store1" directive is). I don't understand why the insert step would not free the old Map version. Also, retainer profiling blames the "arry" lens, which is not even used in this piece of code, and uses an IntMap, not a Map. I don't understand what is going on...</p>
<p>EDIT: whoops. I was using the sieve of Eratosthenes as a test program for my interpreter, so it is probably normal that the IntMap usage grows linearily in time..</p>
<pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TemplateHaskell #-}
module Mango where
import Control.Applicative ((<$>), (<$), (<*>), (<*))
import Control.Category
import Control.Monad.Error
import Control.Monad.IO.Class
import Control.Monad.State.Strict
import Data.Bits
import Data.Char (chr,ord)
import Data.IntMap.Strict as IM hiding (null)
import Data.Lens
import Data.Lens.Template
import Data.Map.Strict as M hiding (null)
import Data.Maybe
import Prelude hiding ((.))
import Text.Parsec hiding (label)
import Text.Parsec.Char
---------------
-- Utility code
(??) t _ True = t
(??) _ f False = f
io = liftIO
a !!= b = (a != b) >> return ()
-- Lens for array items
item :: Integer -> Lens (IntMap v) v
item idx = lens (IM.! (fromInteger idx)) (IM.insert (fromInteger idx))
----------
-- PARSING
type ProgPtr = [Tok]
data Tok = Label String
| Number Integer
| Keyword String
deriving Show
comment = (string "/*" >> in_comment) <?> "comment"
voidChar = () <$ anyChar
in_comment = (try (string "*/") >> return ())
<|> ((comment <|> voidChar) >> in_comment)
<?> "end of comment"
whitespace = many1 (() <$ space <|> comment )
tchar = oneOf $ '_' : ['a'..'z']
tok = Number . read <$> many1 digit
<|> do
ident <- many1 tchar
(char ':' >> return (Label ident))
<|> return (Keyword ident)
<?> "token"
-- eof here chokes on trailing garbage, but prevents single-pass parsing
program = optional whitespace >> (tok `sepEndBy1` whitespace) <* eof
------------
-- Compiling
-- find all labels, will use them as variables later
allLabels = M.fromList . allLabels' where
allLabels' [] = []
allLabels' (Label l : xs) = (l, PtrVal xs) : allLabels' xs
allLabels' (_ : xs) = allLabels' xs
------------
-- Execution
data Value = IntVal Integer | PtrVal ProgPtr
{- Stack values contain both a value and an optional variable symbol.
- This is to get around a language quirk, the "magical" semantics
- of 'store' which operates on the name of the last variable pushed
- instead of on its content. This seemed a more robust approach
- than looking ahead for a 'store' token in the parser to distinguish
- symbols from values.
-}
newtype Stack = Stack { unStack :: (Maybe String, Value) }
instance Show Stack where
show (Stack (Nothing, v)) = show v
show (Stack (Just var, v)) = "<" ++ var ++ ">" ++ show v
instance Show Value where
show (IntVal n) = show n
show (PtrVal _) = "<pointer>"
data ProgState = ProgState {
_stack :: [Stack],
_vars :: Map String Value,
_arry :: IntMap Value,
_ip :: ProgPtr
} deriving Show
$( makeLenses [''ProgState] )
type MangoT m a = StateT ProgState (ErrorT String m) a
initProg p = ProgState
[] -- empty stack at startup
(allLabels p) -- first convert all labels as pointer variables
IM.empty -- empty array
p -- full program as initial IP
exit = (ip !!= [])
dump :: MangoT IO ()
dump = (get >>= io.print)
crash reason = (io.print) reason >> dump >> exit
m <!> r = catchError m (const $ throwError r)
push = (>> return ()) . (stack %=) . (:) . Stack
pushi x = push (Nothing, IntVal x)
ucons (h:t) = (h,t)
pop = unStack <$> (stack !%%= ucons)
popi = do { (_, IntVal v) <- pop; return v } <!> "Cannot pop required int"
popp = do { (_, PtrVal p) <- pop; return p } <!> "Cannot pop required ptr"
pops = do { (Just s, _) <- pop; return s } <!> "Cannot pop symbol"
binop f = do { y <- popi; x <- popi; pushi (x `f` y) }
cjump test = do
no <- popp
yes <- popp
x <- popi
if test x
then ip !!= yes
else ip !!= no
-- Execution of a single operand
exec (Label _) = return ()
exec (Number n) = pushi n
exec (Keyword "add") = binop (+)
exec (Keyword "call") = do
tgt <- popp
cur <- access ip
push (Nothing, PtrVal cur)
ip !!= tgt
exec (Keyword "dup") = do { x <- pop; push x; push x }
exec (Keyword "exit") = exit
exec (Keyword "ifz") = cjump (== 0)
exec (Keyword "ifg") = cjump (> 0)
exec (Keyword "jump") = popp >>= (ip !!=)
exec (Keyword "mod") = binop mod
exec (Keyword "print_byte") = popi >>= io.putChar.chr.fromInteger
exec (Keyword "print_num") = popi >>= io.putStr.show
exec (Keyword "read_num") = io readLn >>= pushi
exec (Keyword "read_byte") = io getChar >>= pushi.toInteger.ord
exec (Keyword "store") = {-# SCC "store1" #-} do
addr <- pops
(_, n) <- pop
vars !%= M.insert addr n
return ()
exec (Keyword "sub") = binop (-)
exec (Keyword "vload") = do
i <- popi
x <- access (item i . arry)
push (Nothing,x)
return ()
exec (Keyword "vstore") = do
(_,x) <- pop
idx <- popi
(item idx . arry) !!= x
exec (Keyword "xor") = binop xor
exec (Keyword k) = do
vs <- access vars
push (Just k, fromMaybe (IntVal 0) (M.lookup k vs))
fetch = ip !%%= ucons
step = catchError (fetch >>= exec) crash
dumpLens l = access l >>= (io . print)
terminated = null <$> access ip
loop step = step >> (terminated >>= (return () ?? loop step))
runProgWith step p = evalStateT (loop step) (initProg p)
runProgram = runProgWith step
onLeft _ (Right x) = Right x
onLeft f (Left x) = Left (f x)
wrapError = mapErrorT (fmap (onLeft show))
withErrors m = do
r <- runErrorT m
case r of
Right _ -> return ()
Left err -> fail err
decodeArgs [file] = return (file, runProgram)
decodeArgs ["-d",file] = return (file, debugProgram)
decodeArgs _ = fail "Usage: hango [-d] file.mango"
main = withErrors $ do
(file,run) <- io getArgs >>= decodeArgs
prog <- wrapError . ErrorT $ parseFromFile program file
run prog
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Name of <code>Stack</code> type is misleading, you mean <em>Stack element</em>\n(<code>StackElt</code>), not a whole stack.</li>\n<li>Same for <code>withErrors</code>. <em>withX</em> is\nusually reserved for two or more argument function, such that the\nlast argument is function taking argument of type<code>X</code>, e.g. <code>\\x :: X\n-> ...</code> Did you mean <code>handleErrors</code>?</li>\n<li>Did you really mean that value of an error is an error message? Or did you<br>\nrather intend to display\nerror and go on with execution? (This is not clear from code. One\nshould insert comment whenever intention of code is not apparent, or\njust complicated.)</li>\n<li>Did you use <code>hlint</code> on this code?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T19:12:36.933",
"Id": "79431",
"Score": "0",
"body": "Further, there is a lack of types on functions. They often help a new reader understand things."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T12:55:40.323",
"Id": "39548",
"ParentId": "18981",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T23:17:22.297",
"Id": "18981",
"Score": "7",
"Tags": [
"haskell",
"interpreter"
],
"Title": "A stack-based language interpreter in Haskell"
}
|
18981
|
<p>I've updated this question to be about code style only, as all of it's answered focused on this aspect. For the codes function, see <a href="https://codereview.stackexchange.com/questions/19153/review-c-algo-function">Randomizing and mutating algo class - functionality</a></p>
<p><code>algo</code> is an algorithm that's dynamic. <code>algo</code> instances can be created, asked to become random, mutated and also run. They can be set to remember changes they make to themselves between runs or not. They also output values, these could be used for anything from value sequences such as mathematical number sequences to controls for a bot in a game. It's straightforward to specify limits on memory or computation steps for each as well and needless to say are entirely sandboxed.</p>
<p>By sandboxed I mean that they only compute and produce output as described, they cannot for example use local or global variables, print to the console, <code>#include</code> or write to files.</p>
<p><code>algo</code>s can be used where algorithms need to be portable and must be only able to calculate/compute. There is no distinction between data and instructions in an <code>algo</code>.</p>
<p>A use is as values for directed search for algorithms such as with evolutionary algorithms, MCTS or others.</p>
<p>Another is in a data file that includes algorithms, like an image that includes its own way to decompress itself, that can therefore be constructed using the specific image that is to be decompresed.</p>
<p>They are deliberately general, being a component that could be used in many contexts and conceptually simple, as a number is.</p>
<p>Can this code be reviewed?</p>
<pre><code>// by Alan Tennant
#include <iostream>
#include <vector>
#include <string>
#include <time.h> // for rand
class algo
{
public:
std::vector<unsigned short> code;
std::vector<unsigned int> output;
bool debug_info;
algo()
{
reset1(false);
instructions_p = 11;
}
void random(unsigned int size)
{
code.clear();
output.clear();
for(unsigned int n = 0; n < size; n++) {
code.push_back(rand() % instructions_p);}
reset1(true);
}
void run(
unsigned long most_run_time,
unsigned int largest_program,
unsigned int largest_output_size,
bool reset)
{
if (reset && !is_reset_p)
{
reset1(true);
output.clear();
code2 = code;
code_pos = 0;
}
is_reset_p = false;
size_t code_size = code2.size();
if (debug_info && !can_resume_p)
std::cout<<"can't resume, reset first"<<std::endl;
if(code_size == 0 || most_run_time == 0)
{
out_of_time_p = true;
out_of_space_p = false;
run_time_p = most_run_time;
}
else if (can_resume_p)
{
unsigned short instruction;
bool cont = true;
if(debug_info) {
std::cout<<"size: "<<code_size<<std::endl<<std::endl;}
while(cont)
{
instruction = code2[code_pos] % instructions_p;
if(debug_info) {std::cout<<code_pos<<", ";}
code_pos = (code_pos + 1) % code_size;
switch(instruction)
{
case 0:
if(debug_info) {std::cout<<"end";}
cont = false;
can_resume_p = false;
break;
case 1:
if(debug_info) {
std::cout<<"goto p1";}
code_pos = code2[(code_pos + 1) % code_size];
break;
case 2:
if(debug_info) {
std::cout<<"if value at p1 % 2 = 0 then goto p2";}
if(code2[code2[code_pos] % code_size] % 2 == 0) {
code_pos = code2[(code_pos + 1) % code_size];}
else {
code_pos += 2;}
break;
case 3:
if(debug_info) {std::cout<<"value at p1 = value at p2";}
code2[code2[code_pos] % code_size] =
code2[code2[(code_pos + 1) % code_size] % code_size];
code_pos += 2;
break;
case 4:
if(debug_info) {
std::cout<<"value at p1 = value at p2 + value at p3";}
code2[code2[code_pos] % code_size] = (
code2[code2[(code_pos + 1) % code_size] % code_size] +
code2[code2[(code_pos + 2) % code_size] % code_size]
) % USHRT_MAX;
code_pos += 3;
break;
case 5:
{
if(debug_info)
{std::cout<<"value at p1 = value at p2 - value at p3";}
long v1 =
(long)code2[code2[(code_pos + 1) % code_size] % code_size] -
code2[code2[(code_pos + 2) % code_size] % code_size];
code2[code2[code_pos] % code_size] = abs(v1) % USHRT_MAX;
code_pos += 3;
}
break;
case 6:
{
if(debug_info) {std::cout<<"toggle value at p1";}
size_t v1 = code2[code_pos] % code_size;
unsigned short v2 = code2[v1];
if(v2 == 0) {code2[v1] = 1;}
else {code2[v1] = 0;}
code_pos++;
}
break;
case 7:
if(debug_info) {
std::cout<<"output value at p1";}
output.push_back(code2[code2[code_pos] % code_size]);
code_pos++;
break;
case 8:
if(debug_info) {std::cout<<"increase size";}
code2.push_back(0);
break;
case 9:
{
if(debug_info) {std::cout<<"increment value at p1";}
size_t v1 = code2[code_pos] % code_size;
code2[v1] = (code2[v1] + 1) % USHRT_MAX;
code_pos++;
}
break;
case 10:
{
if(debug_info) {std::cout<<"decrement value at p1";}
size_t v1 = code2[code_pos] % code_size;
code2[v1] = abs((code2[v1] - 1) % USHRT_MAX);
code_pos++;
}
break;
}
if(debug_info) {std::cout<<std::endl;}
run_time_p++;
code_size = code2.size();
code_pos = code_pos % code_size;
if(run_time_p == most_run_time) {
cont = false; out_of_time_p = true;}
if(code_size > largest_program)
{
cont = false;
can_resume_p = false;
out_of_space_p = true;
if (debug_info)
std::cout<<"became too large"<<std::endl;
}
if(output.size() > largest_output_size)
{
cont = false;
can_resume_p = false;
output.pop_back();
if (debug_info)
std::cout<<"too much output"<<std::endl;
}
}
if (debug_info)
{
std::cout<<std::endl<<"size: "<<code_size<<std::endl<<
std::endl<<"output: "<<std::endl;
size_t output_size = output.size();
for (size_t t = 0; t < output_size; t++)
std::cout<<output[t]<<std::endl;
}
}
}
void mutate(unsigned int largest_program)
{
output.clear();
size_t size;
// special mutations
while(rand() % 4 != 0) // 3/4 chance
{
size = code.size();
if(rand() % 2 == 0) // 1/2 chance
{
// a bit of code is added to the end (would prefer inserted anywhere)
if(size < largest_program) {
code.push_back(rand() % instructions_p);}
}
else
{
// a bit of code is removed from the end (would prefer removed from anywhere)
if(size != 0)
code.pop_back();
}
// a section of code is moved, not yet implemented.
}
// mutate bits of the code
size = code.size();
if (size > 0)
{
unsigned int most_mutation = unsigned int(size * 0.1f);
if(most_mutation < 9)
most_mutation = 8;
unsigned int mutation = rand() % most_mutation;
for(unsigned int n = 0; n < mutation; n++)
code[rand() % size] = rand() % instructions_p;
}
reset1(true);
}
#pragma region
unsigned long run_time()
{
return run_time_p;
}
bool out_of_time()
{
return out_of_time_p;
}
bool out_of_space()
{
return out_of_space_p;
}
bool can_resume()
{
return can_resume_p;
}
bool is_reset()
{
return is_reset_p;
}
private:
bool can_resume_p, is_reset_p,
out_of_time_p, out_of_space_p;
unsigned int code_pos;
unsigned short instructions_p;
unsigned long run_time_p;
std::vector<unsigned short> code2;
void reset1(bool say)
{
out_of_time_p = false;
out_of_space_p = false;
run_time_p = 0;
code2 = code;
code_pos = 0;
can_resume_p = true;
is_reset_p = true;
if (say && debug_info)
std::cout<<"reset"<<std::endl;
}
#pragma endregion
};
void main()
{
srand((unsigned int)time(NULL));
algo a = algo();
a.random(50);
std::cout<<std::endl<<std::endl;
a.run(10, 100, 10, false);
std::cout<<std::endl<<std::endl;
a.run(10, 100, 10, false);
}
</code></pre>
<hr>
<p>I've improved the code in some of the ways described, above is the original code.</p>
<p>It's usual for me to prioritize in this way, but I'm avoiding function calls in the main loop of run because I've found in this program they made a big difference to performance. Apart from that I like HostileFork and Anders K idea of using <code>numeric_limits<unsigned short>::max()</code> over <code>USHRT_MAX</code>.</p>
<p>I'm not keen on <code>int main()</code>, but in the interests of conformity it's been changed from <code>void main()</code>.</p>
<p><code><cstdlib></code> and <code><ctime></code> have replaced <code><time.h></code>.</p>
<p>From the answers, GCC doesn't seem that good, but to support it I have changed <code>unsigned int(size * 0.1)</code> to <code>static_cast<unsigned int>(size * 0.1)</code>.</p>
|
[] |
[
{
"body": "<p>For starters, code as written won't compile in GCC. :-(</p>\n\n<p><em>\"void main() is explicitly prohibited by the C++ standard and shouldn't be used\"</em></p>\n\n<p><a href=\"https://stackoverflow.com/questions/204476/what-should-main-return-in-c-c\">https://stackoverflow.com/questions/204476/what-should-main-return-in-c-c</a></p>\n\n<p>Rather than <code>#include <time.h></code>, <code>#include <cstdlib></code>. That will correctly give you <code>rand</code> and <code>abs</code>. There used to be some flak about including anything that ends in \".h\" out of the standard library and instead use the \"c-prefixed-and-non-suffixed\" versions, but last I checked it didn't actually make a difference. Still, some people think it does, so best not to upset them.</p>\n\n<p>Read this post of mine about <code>numeric_limits</code>, and replace your <code>USHRT_MAX</code> and \n<code>UINT_MAX</code> appropriately.</p>\n\n<p><a href=\"http://hostilefork.com/2009/03/31/modern_cpp_or_modern_art/\" rel=\"nofollow noreferrer\">http://hostilefork.com/2009/03/31/modern_cpp_or_modern_art/</a></p>\n\n<p>GCC doesn't like this line:</p>\n\n<pre><code>unsigned int most_mutation = unsigned int(size * 0.1);\n</code></pre>\n\n<p>I'm not sure what the point of that is supposed to be. If you want to static cast it for clarity, I guess that's fine:</p>\n\n<pre><code>unsigned int most_mutation = static_cast<unsigned int>(size * 0.1);\n</code></pre>\n\n<p>With those changes, it compiles in GCC. Speaking of which: whatever compiler you are using...it can be helpful to have a virtual machine around to use some different ones on your code (Clang, GCC, MSVC) and see what they report.</p>\n\n<hr>\n\n<p>The next best-practices step is to bump the warnings all-the-way-up. I'm now using settings I got from <a href=\"https://stackoverflow.com/questions/5088460/flags-to-enable-thorough-and-verbose-g-warnings/9862800#9862800\">an answer by David Stone</a>. Here's what that gives us:</p>\n\n<pre><code>test.cpp:226:0: error: ignoring #pragma region [-Werror=unknown-pragmas]\ntest.cpp:272:0: error: ignoring #pragma endregion [-Werror=unknown-pragmas]\ntest.cpp: In member function ‘void algo::run(long unsigned int, unsigned int, unsigned int, bool)’:\ntest.cpp:107:86: error: use of old-style cast [-Werror=old-style-cast]\ntest.cpp:67:27: error: switch missing default case [-Werror=switch-default]\ntest.cpp: In member function ‘void algo::mutate(unsigned int)’:\ntest.cpp:212:40: error: conversion to ‘unsigned int’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]\ntest.cpp:215:77: error: conversion to ‘unsigned int’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]\ntest.cpp:218:50: error: conversion to ‘unsigned int’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]\ntest.cpp:220:35: error: conversion to ‘size_t {aka unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]\ntest.cpp: In function ‘int main()’:\ntest.cpp:277:34: error: use of old-style cast [-Werror=old-style-cast]\n</code></pre>\n\n<p>You can address those on your own, but I'll cover the pragma philosophy. Firstly: I never indent preprocessor directives--it calls them out more clearly. But even better: don't use 'em, especially not for a fluffy IDE feature (why doesn't it use a certain comment to cue that?) Pragmas are \"implementation defined\", and putting little bits of dirt in your program like this is a slippery slope. GCC used to discourage this:</p>\n\n<blockquote>\n <p>In some languages (including C), even the compiler is not bound to behave in a sensible manner once undefined behavior has been invoked. One instance of undefined behavior acting as an Easter egg is the behavior of early versions of the GCC C compiler when given a program containing the #pragma directive, which has implementation-defined behavior according to the C standard. In practice, many C implementations recognize, for example, #pragma once as a rough equivalent of #include guards — but GCC 1.17, upon finding a #pragma directive, would instead attempt to launch commonly distributed Unix games such as NetHack and Rogue, or start Emacs running a simulation of the Towers of Hanoi.</p>\n</blockquote>\n\n<hr>\n\n<p>Now I'll just ramble about formatting and style, without trying to grok the \"big picture\" of what your code is for. :)</p>\n\n<p>This is a matter of taste, but in implementation files <code>using namespace std;</code> can make your code less wordy. <em>(Doing it in headers is not considered a good practice, as it would then be inherited by all implementation files that used the headers...giving them less control over potential name collisions.)</em></p>\n\n<p>Also, it's generally considered a bad idea to make data members in your classes public. Narrowing the interface through methods gives you more wiggle room to modify the implementation without clients of the class to be rewritten. So:</p>\n\n<pre><code>using namespace std;\n\nclass algo\n{\n private:\n vector<unsigned short> code;\n vector<unsigned int> output;\n bool debug_info;\n\n public:\n algo()\n {\n /* stuff... */\n</code></pre>\n\n<p>I personally like to see spaces between things and logical breaks in output. So following on that I'd turn:</p>\n\n<pre><code>std::cout<<std::endl<<\"size: \"<<code_size<<std::endl<<\n std::endl<<\"output: \"<<std::endl;\nsize_t output_size = output.size();\nfor (size_t t = 0; t < output_size; t++)\n std::cout<<output[t]<<std::endl;\n</code></pre>\n\n<p>...into the much-less-claustrophobic:</p>\n\n<pre><code>cout << endl;\ncout << \"size: \" << code_size << endl;\ncout << endl;\ncout << \"output: \" << endl;\nfor (size_t t = 0; t < output_size; t++) {\n cout << output[t] << endl;\n}\n</code></pre>\n\n<p>Again in the \"matter of taste\" department, I prefer to use the C++ keywords for logical operations, so I would write:</p>\n\n<pre><code>if (reset && !is_reset_p)\n</code></pre>\n\n<p>...as:</p>\n\n<pre><code>if (reset and (not is_reset_p))\n</code></pre>\n\n<p>But that's just me, since I never try to write C++ code that will still compile in C...so I figure the keywords are there, why not use 'em for readability. Plus I use a proportional font to edit, and the <code>!</code> for not can be hard to see...e.g. <code>!list.isNull()</code>.</p>\n\n<p>Also, I indent the breaks in my switch statements and not the cases. It makes it more parallel to an \"if\" by putting the case at the same level as the switch, and makes the cases stand out better. You also don't chew up screen space as rapidly:</p>\n\n<pre><code>switch(instruction)\n{\ncase 0:\n if (debug_info) {\n cout << \"end\";\n }\n cont = false;\n can_resume_p = false;\n break;\n case 1:\n</code></pre>\n\n<p>I also would suggest always putting braces around code in <code>if</code> statements, and not putting code on the same line as the condition. Beyond aesthetics, this makes editing the condition and editing the code edits to different lines in version control systems. (And always using braces means you don't have to generate a diff on the condition line when you go from one-line of code to multiple-lines of code or vice-versa.)</p>\n\n<p>The use of unsigned types is verbose and of questionable advantage. I never really thought that reclaiming half the numeric range mattered much (most of the time). But once I believed it was better for quantities that were always supposed to be unsigned to be labeled thusly, for type correctness. It isn't really the win you'd think, and probably obscures as many bugs as it prevents. </p>\n\n<p>I won't rehash the pros and cons here...I'll just say that if you want a <em>real</em> type-safe solution <em>(e.g. in computer security code)</em> you need something like SafeInt:</p>\n\n<p><a href=\"http://safeint.codeplex.com/\" rel=\"nofollow noreferrer\">http://safeint.codeplex.com/</a></p>\n\n<hr>\n\n<p>Regarding the big picture I won't invest that time. I'll just say that if you're trying to write generalized algorithms for C++, then be sure to spend a little while looking at <code><algorithm></code>:</p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">http://en.cppreference.com/w/cpp/algorithm</a></p>\n\n<p>It may provide inspiration for your design. Perhaps what you really want is a templated class with some kind of iteration interface?</p>\n\n<p>You might consider asking a StackOverflow question that doesn't include your code above, but rather establishes a clear usage scenario. Then ask for suggestions on what methodology to use to meet the need. Your description is too vague, and suffers from the problem that you don't clearly define what it <em>doesn't</em> do...and while terms \"sandboxed\" might be meaningful in your mind it doesn't convey a clear requirement for this code to me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T22:51:32.773",
"Id": "30331",
"Score": "4",
"body": "There is a difference between <X.h> and <cX> in the namespace that identifiers are guaranteed to be in. <X.h> identifiers guaranteed to be in :: (global) may optionally be in std::. <cX> identifiers guaranteed to be in std:: may optionally also be in :: (global). Because of the optionally part any code that makes an assumption is well defined for the current compiler (if it compiles) but is non portable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T14:08:18.230",
"Id": "30351",
"Score": "0",
"body": "@LokiAstari Ah. Perhaps what I was remembering was that if you say `using namespace std;` in your file and use the global scoped variants it doesn't matter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:02:21.843",
"Id": "30355",
"Score": "2",
"body": "Probably. If you do that (and import std into global) then it makes no difference. But please don't use `using namespace std;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:04:34.167",
"Id": "30357",
"Score": "0",
"body": "@LokiAstari in a .cpp file, why not? No one is `#include`-ing it. Isn't it all right to just address ambiguities if and when they crop up in that particular file, and keep things brief otherwise? The alternative would be either to get verbose with `using std::vector; using std::list;` ad nauseum or completely qualify everything. I don't see the harm in going with the gentle slope of convenience for starters, and backing off if-and-when there's a collision."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:30:20.173",
"Id": "30359",
"Score": "1",
"body": "When you have a sizable (anything bigger than a toy) project it starts to get a lot of conflicts that you need to resolve. It is just easier to write `std::list` or std::vector` I very rarely use `using` in any context. If you have a namespace with a large namespace then you can use namespace alias to shorten the prefix: `namespace bfs = boost::filesystem;` Then just use `bfs::Path`. The reason its `std` and not `standard` is so that it is not a burden to type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:40:59.417",
"Id": "30360",
"Score": "0",
"body": "@LokiAstari Hmm. While some things I do are toys, not *everything* is...and I haven't collided with the standard namespace in a case where I thought the best resolution wasn't to rename my classes. Can you give a compelling example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T19:23:35.713",
"Id": "30364",
"Score": "0",
"body": "Thanks, this looks interesting. I will action many of thease points later and update the code. I've added more description to the question to show uses and decribe the sandboxing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T23:23:49.297",
"Id": "30394",
"Score": "1",
"body": "Happened more than I liked so I stopped doing it. Now I no longer have the problem. http://stackoverflow.com/q/1452721/14065 Technically there is nothing to stop you and then resolve the problems manually (but not all issues are caught by the compiler. There are problems that can happen that are non detectable See http://stackoverflow.com/a/1453605/14065). I just don't care to have to resolve the problem so I always make it explicit. Its just a bad habit that is hard to break so I don't get into the habit anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T22:58:21.420",
"Id": "30651",
"Score": "0",
"body": "Would you mind replacing the cplusplus.com link with a [cppreference](http://en.cppreference.com/w/cpp/algorithm) one? cplusplus.com is... not very good."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T19:19:50.110",
"Id": "19001",
"ParentId": "18982",
"Score": "10"
}
},
{
"body": "<p>My 2c:</p>\n\n<hr>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <string>\n#include <time.h> \n</code></pre>\n\n<p>use cpp version of headers i.e. cstdlib and ctime</p>\n\n<hr>\n\n<p>in general split your class in a header and cpp, it makes it easier to get an overview of the contents of the class.</p>\n\n<hr>\n\n<pre><code> algo()\n {\n reset1(false);\n instructions_p = 11;\n }\n</code></pre>\n\n<p>initialize your member variables in the ctor i.e <code>algo() : debug_info(false) ... {}</code> normally it is also a good habit to have a dtor, default copy ctor and assignment, if for nothing else to disallow them.</p>\n\n<hr>\n\n<pre><code> void random(unsigned int size)\n {\n code.clear();\n output.clear();\n for(unsigned int n = 0; n < size; n++) {\n code.push_back(rand() % instructions_p);\n }\n reset1(true);\n }\n</code></pre>\n\n<p>i would like a bit more descriptive method names - random what?</p>\n\n<hr>\n\n<pre><code> void run(\n unsigned long most_run_time,\n unsigned int largest_program,\n unsigned int largest_output_size,\n bool reset)\n {...\n</code></pre>\n\n<p>when you start to have many parameters it helps having comments to describe what they mean and what <em>unit</em> they are expecting (kb? bytes?). Also it is good to have an assert or two inside each method to catch any unexpected values a programmer may toss to your function.</p>\n\n<hr>\n\n<pre><code> if (debug_info && !can_resume_p)\n std::cout<<\"can't resume, reset first\"<<std::endl;\n</code></pre>\n\n<p>arguable it may be a bit cleaner to have a debug output function to print the debug information so that you can redirect the output easier or have a stream member variable:</p>\n\n<hr>\n\n<pre><code> if (debug_info && !can_resume_p)\n _err <<\"can't resume, reset first\"<<std::endl;\n</code></pre>\n\n<p>or wrap in a debug function which does nothing when debug_info is false:</p>\n\n<hr>\n\n<pre><code> if (!can_resume_p)\n debug(\"can't resume, reset first\");\n</code></pre>\n\n<hr>\n\n<p>switch statement:</p>\n\n<pre><code> switch(instruction)\n {\n case 0:\n</code></pre>\n\n<p>use an enum for constants to make case statement clearer:</p>\n\n<pre><code> case IncreaseSize:\n debug(\"increase size\");\n code2.push_back(0);\n break;\n</code></pre>\n\n<hr>\n\n<pre><code> code2[v1] = (code2[v1] + 1) % USHRT_MAX;\n</code></pre>\n\n<p>use the <code>std::numeric_limits</code> (include climits) instead:</p>\n\n<pre><code>code2[v1] = (code2[v1] + 1) % numeric_limits<unsigned short>::max()\n</code></pre>\n\n<p>always have a <code>default:</code> case in the case statement to catch weird values</p>\n\n<hr>\n\n<pre><code> if (debug_info)\n {\n std::cout<<std::endl<<\"size: \"<<code_size<<std::endl<<\n std::endl<<\"output: \"<<std::endl;\n size_t output_size = output.size();\n for (size_t t = 0; t < output_size; t++)\n std::cout<<output[t]<<std::endl;\n }\n</code></pre>\n\n<p>in the above it would be more clearer to move the code into a separate function which does nothing if debug_info is false </p>\n\n<p>finally since you use index of vector a lot you want to use at(n) on the vector instead of [n] to catch if you go outside the index. at(n) will then throw an exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T12:36:12.357",
"Id": "19059",
"ParentId": "18982",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "19001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T00:26:23.190",
"Id": "18982",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"search",
"random",
"simulation"
],
"Title": "Randomizing and mutating algo class - style"
}
|
18982
|
<p>This is <a href="http://www.ict.kth.se/courses/IS1500/2012/nios2int/index.html" rel="nofollow">homework</a> for which we have prepared Nios 2 assembly:</p>
<pre><code>########################################
# Definitions of device-addresses
# and important constants.
#
# de2_pio_keys4 - 0x840
.equ keys4base,0x840
.equ TRAPCODE, 0x003B683A
# uart_0 - 0x860
.equ uart0base,0x860
# timer_1 - 0x920
.equ timer1base,0x920
#
# Timer 1 time-out definition.
# The clock frequency at the lab session is 50 MHz.
# For simulation, use a 0.1-second time-out.
# At the lab session, use a 1-second time-out.
#
.equ timer1count,5000000 # Change this value at the lab session
#
# End of definitions of device-addresses
# and important constants.
########################################
########################################
# Macro definitions begin here
#
#
# PUSH reg - push a single register on the stack
#
.macro PUSH reg
subi sp,sp,4 # reserve space on stack
stw \reg,0(sp) # store register
.endm
#
# POP reg - pop a single register from the stack
#
.macro POP reg
ldw \reg,0(sp) # fetch top of stack contents
addi sp,sp,4 # return previously reserved space
.endm
#
# PUSHMOST - push all caller-save registers plus ra
#
.set noat # required since we push r1
.macro PUSHMOST
PUSH at # push assembler-temporary register r1
PUSH r2
PUSH r3
PUSH r4
PUSH r5
PUSH r6
PUSH r7
PUSH r8
PUSH r9
PUSH r10
PUSH r11
PUSH r12
PUSH r13
PUSH r14
PUSH r15
PUSH ra # push return address register r31
.endm
#
# POPMOST - pop ra plus all caller-save registers
# POPMOST is the reverse of PUSHMOST
#
# .set noat is already done above - no need to repeat that
.macro POPMOST
POP ra
POP r15
POP r14
POP r13
POP r12
POP r11
POP r10
POP r9
POP r8
POP r7
POP r6
POP r5
POP r4
POP r3
POP r2
POP at
.endm
#for use in trap inside of interuptions
.macro POPINT
POP r29
POP r24
POP r4
POP r5
.endm
#for use in trap inside of interuptions
.macro PUSHINT
PUSH r5
PUSH r4
PUSH r24
PUSH r29
.endm
.macro SysCall index
movia r4, \index
trap
.endm
#
# Macro definitions end here
########################################
.text
.align 2
########################################
# Stub/trampoline
# Three machine instructions (remember,
# movia is expanded into two instructions).
# The stub/trampoline-code must be copied
# to the exception-address
# (0x800020 in the current system).
#
# Stub/trampoline explanation:
# move address of exception handler
# into exception-temporary register et
# Use JMP to jump to the interrupt handler
# (whose address is now in et)
stub:
movia et,exchand
jmp et
#
# End of stub/trampoline.
########################################
########################################
# The following section replaces the
# Altera-supplied initialization code.
#
.global alt_main
alt_main:
nop
wrctl status,r0
br main
nop
nop
# Those NOPs are really not necessary,
# but may help when you debug the program.
# Without the NOPs, the branch instruction
# would just jump to the next address
# sequentially, which can be confusing.
#
# End of replacement for Altera-supplied
# initialization code.
########################################
########################################
# Main program follows.
#
.data
.align 2
mytime: .word 0x5957
.text
.align 2
#
# The label main
# must be declared global
#
.global main
main:
# Always disable interupts before
# initializing any devices
wrctl status,r0
#
# Add your code here to copy the stub
# to address 0x800020 and on.
# Remember to copy all three instructions
# (movia is expanded to two instructions).
#
movia r5, stub
movia r6, 0x800020
#copy movia del 1
ldw r7, 0(r5)
stw r7, 0(r6)
#copy movia del 2
ldw r7, 4(r5)
stw r7, 4(r6)
#copy jmp
ldw r7, 8(r5)
stw r7, 8(r6)
#
# Add your code here to initialize timer_1 for
# continuous interrupts every 100 ms (0.1 s)
#
movia r8, timer1base # basadressen till timern
movia r9, timer1count
srli r10, r9, 16 #flytta h�ga bitar till h�gerkant
stwio r10,12(r8) # periodh
stwio r9, 8(r8) # periodl
movi r9, 0b0111 # R9 = 0b0111 (continuous=1 start=1, ITO=1)
stwio r9, 4(r8) # skriv till control
#
# For Assignment 4 (but not earlier!),
# add code here to initialize de2_pio_keys4
# for interrupts from KEY0
#
movia r8, keys4base # basadress till keys.
movi r9, 0b0001 #interrupt enable key0 only
stwio r9, 8(r8) #interrupt mask raden förskjuten med 8 bytes i minnet.
#
# Add your code here to initialize the CPU for
# interrupts from timer_1 (index 10) only.
# For Assignment 4 (but not earlier!),
# add code here to also initialize the CPU for
# interrupts from de2_pio_keys4 (index 2)
#
movia r5, 0x0404 #index 2 & 10 ienable
wrctl ctl3, r5
movia r6, 0b1 #PIE status bit
wrctl ctl0, r6
#
# Add your code here to enable interrupts
# by writing 1 to the status register
#
movia r5, 1
wrctl ctl1,r5 #status reg == ctl1
#
# Set start value for prime-space exploration.
movia r4,987654
#
# Main loop starts here.
mainloop:
call primesearch
PUSH r4
movi r4,33
trap
POP r4
mov r4,r2
#
# This is the end of the main loop.
# We jump back to the beginning.
br mainloop
#
# End of main program.
########################################
########################################
# Exception handler.
#
# This exception handler is extremely simplified.
# You will expand and improve the handler.
# When you do this, you must add comments -
# and change this comment - to reflect your changes.
#
exchand:
nop
nop
# Those NOPs are not really necessary.
# However, in this particular program,
# they may help you setting a breakpoint
# at the beginning of the handler
# when you debug the program.
# Here we should check the contents of estatus
# to see if interrupts were enabled (Condition 1).
#movia r5, 0b1 #comparebit
#rdctl r6, ctl1 #PIE status bit
#andi r7, r6, 0b1 #maska fram PIE status bit
#bne r5, r7, noint #if not, check if trap
rdctl r24, ctl1 # läs estatus
andi r24, r24, 1 # kolla EPIE-biten
beq r24, r0, noint # hopp om EPIE=0
rdctl r24, ctl4 # read from ipending
beq r24, r0, noint # branch to noint if no pending interrupts
# Then we should check if ipending is nonzero
# (Condition 2).
#rdctl r24, ctl14 #ipending
#bne r24, r0, noint #if not, check if trap
# If Conditions 1 and 2 are both true, the cause of
# exception must have been an interrupt. In this case,
# we should jump to the interrupt-handling code
# at label exc_was_interrupt.
movia r24, exc_was_interrupt
jmp r24
# Label noint - branch here (or fall-through) if you
# are sure that the exception was NOT an interrupt.
noint:
# Now, we should check if the instruction at the
# exception location is a TRAP instruction.
mov r24, r29
subi r24, r24, 4
ldw r24, 0(r24)
PUSH r8
movia r8, TRAPCODE
cmpeq r24, r24, r8 #if instruktion at ea-4 is trap
POP r8
bne r24, r0, exc_was_trap #om trap, hoppa till exc_was_trap
# If it was a TRAP instruction,
# we should jump to label exc_was_trap.
# Then we should perhaps check if the bit-pattern,
# at the exception location, is that of
# an unimplemented instruction
# that we handle by software emulation. However,
# this would be beyond the scope of this course.
# In this extremely simplified handler, we check nothing.
# The following label is a place to jump to,
# after making sure that the cause of exception
# really was an interrupt.
exc_was_interrupt:
# Since we had an interrupt, and not a TRAP,
# we must subtract 4 from the contents of the
# exception-address register (ea), so that
# the interrupted instruction gets restarted
# when we return from the interrupt.
# This requirement is Nios2-specific.
subi ea,ea,4
# This is the place to check if the interrupt
# came from timer_1 or from another source.
# If the interrupt came from another source,
# we must jump to a handler for that source.
# Since we have only one source right now,
# we omit the check (until Assignment 4).
rdctl r24, ipending
PUSH r8
PUSH r9
movi r8, 0x0400 #timer
and r9, r24, r8 #maska fram
beq r8, r9, timer1int
movi r8, 0x0004 #keys
and r9, r24, r8 #maska fram
beq r8, r9, key0int
#POP r8 & POP r9 need to be first in every interrupt handler. :)
#om koden kommer hit har vi misslyckats epicly. odefinierat beteende
jmpi -1
#crashar förhoppningsvis och antagligen programmet...
key0int:
POP r8
POP r9
# check if key0 is down (0) or up (1) and write 'D' or 'U' respectively to uart0.
PUSH r8
PUSH r9
movi r8, 0b0001 #maska fram key0.
movia r9, keys4base
ldwio r9, 0(r9)
and r9, r9, r8
beq r9, r0, keydown #if 0, key down
keyup:
PUSHMOST
# Print character in R4 using out_char_uart_0.
movia r4, 'U'
call out_char_uart_0
# Restore the saved registers.
POPMOST
br acknowledgekeyint
keydown:
PUSHMOST
# Print character in R4 using out_char_uart_0.
movia r4, 'D'
call out_char_uart_0
# Restore the saved registers.
POPMOST
acknowledgekeyint:
POP r9
POP r8
# Acknowledge the interrupt
movia et,keys4base
PUSH r8
movi r8,1
stwio r8,12(et) # clears int bits
POP r8
# Branch to the end of the exception handler.
br excend
# The following code is specific for
# interrupts from timer_1
timer1int:
POP r8
POP r9
# Acknowledge the interrupt
movia et,timer1base
PUSH r8
movi r8,1
stwio r8,0(et) # clears timeout bit
POP r8
# This is a first, simple handler.
# All we do when we get a timer interrupt
# is print a T on the console.
# Since the JTAG UART uses interrupts itself,
# this program must be compiled with a special
# system library using another UART for the console:
# We use uart_0.
# Before calling a subroutine, push r1 through r15, and r31.
PUSHMOST
movia r4,mytime
call puttime
movia r4,mytime
call tick
# pushint pushes ea, r4, r5 on stack
PUSHINT
# read control register estatus to r5 so we can push it.
rdctl r5, estatus
PUSH r5
movi r4,'T'
trap
# restore control register estatus from r5 after we pop r5.
POP r5
wrctl estatus, r5
# popint restores ea, r4, r5 from stack
POPINT
# Add code here for Assignment 3
POPMOST
# Afterwards, restore saved register values.
# Branch to the end of the exception handler.
br excend
# The following label is a place to jump to,
# after making sure that the cause of exception
# really was the result of a trap instruction.
exc_was_trap:
# Our trap handler will call a subroutine.
# We save all caller-saved registers here,
# to avoid problems for the code containing
# the trap instruction.
PUSHMOST
# Print character in R4 using out_char_uart_0.
#movia r4, 33
call out_char_uart_0
# Restore the saved registers.
POPMOST
# Fall-through to the end of the handler.
# No branch needed (right now at least).
# This is the end of the exception handler.
excend:
eret
#
########################################
########################################
# Helper functions and support code.
# You do not need to study the following code.
#
# out_char_uart_0 - send byte on uart0
# one parameter, in r4: byte to send
# no return value
#
.global out_char_uart_0
out_char_uart_0:
movia r8,uart0base
ldwio r8,8(r8) # get uart0 status
andi r8,r8,0x40 # check TxRDY bit
beq r8,r0,out_char_uart_0 # loop if not ready
andi r4,r4,0xff # sanitize argument
movia r8,uart0base
stwio r4,4(r8) # write to uart0 TX data
ret
################################################################
#
# A simplified printf() replacement.
# Implements the following conversions: %c, %d, %s and %x.
# No format-width specifications are allowed,
# for example "%08x" is not implemented.
# Up to four arguments are accepted, i.e. the format string
# and three more. Any extra arguments are silently ignored.
#
# The printf() replacement relies on routines
# out_char_uart_0, out_hex_uart_0,
# out_number_uart_0 and out_string_uart_0
# in file oslab_lowlevel_c.c
#
# We need the macros PUSH and POP (defined previously).
#
.text
.global nios2int_printf
nios2int_printf:
PUSH ra # PUSH return address register r31.
PUSH r16 # R16 will point into format string.
PUSH r17 # R17 will contain the argument number.
PUSH r18 # R18 will contain a copy of r5.
PUSH r19 # R19 will contain a copy of r6.
PUSH r20 # R20 will contain a copy of r7.
mov r16,r4 # Get format string argument
movi r17,0 # Clear argument number.
mov r18,r5 # Copy r5 to safe place.
mov r19,r6 # Copy r6 to safe place.
mov r20,r7 # Copy r7 to safe place.
asm_printf_loop:
ldb r4,0(r16) # Get a byte of format string.
addi r16,r16,1 # Point to next byte
# End of format string is marked by a zero-byte.
beq r4,r0,asm_printf_end
cmpeqi r9,r4,92 # Check for backslash escape.
bne r9,r0,asm_printf_backslash
cmpeqi r9,r4,'%' # Check for percent-sign escape.
bne r9,r0,asm_printf_percentsign
asm_printf_doprint:
# No escapes present, just print the character.
movia r8,out_char_uart_0
callr r8
br asm_printf_loop
asm_printf_backslash:
# Preload address to out_char_uart_0 into r8.
movia r8,out_char_uart_0
ldb r4,0(r16) # Get byte after backslash
addi r16,r16,1 # Increase byte count.
# Having a backslash at the end of the format string
# is illegal, but must not crash our printf code.
beq r4,r0,asm_printf_end
cmpeqi r9,r4,'n' # Newline
beq r9,r0,asm_printf_backslash_not_newline
movi r4,10 # Newline
callr r8
br asm_printf_loop
asm_printf_backslash_not_newline:
cmpeqi r9,r4,'r' # Return
beq r9,r0,asm_printf_backslash_not_return
movi r4,13 # Return
callr r8
br asm_printf_loop
asm_printf_backslash_not_return:
# Unknown character after backslash - ignore.
br asm_printf_loop
asm_printf_percentsign:
addi r17,r17,1 # Increase argument count.
cmpgei r8,r17,4 # Check against maximum argument count.
# If maximum argument count exceeded, print format string.
bne r8,r0,asm_printf_doprint
cmpeqi r9,r17,1 # Is argument number equal to 1?
beq r9,r0,asm_printf_not_r5 # beq jumps if cmpeqi false
mov r4,r18 # If yes, get argument from saved copy of r5.
br asm_printf_do_conversion
asm_printf_not_r5:
cmpeqi r9,r17,2 # Is argument number equal to 2?
beq r9,r0,asm_printf_not_r6 # beq jumps if cmpeqi false
mov r4,r19 # If yes, get argument from saved copy of r6.
br asm_printf_do_conversion
asm_printf_not_r6:
cmpeqi r9,r17,3 # Is argument number equal to 3?
beq r9,r0,asm_printf_not_r7 # beq jumps if cmpeqi false
mov r4,r20 # If yes, get argument from saved copy of r7.
br asm_printf_do_conversion
asm_printf_not_r7:
# This should not be possible.
# If this strange error happens, print format string.
br asm_printf_doprint
asm_printf_do_conversion:
ldb r8,0(r16) # Get byte after percent-sign.
addi r16,r16,1 # Increase byte count.
cmpeqi r9,r8,'x' # Check for %x (hexadecimal).
beq r9,r0,asm_printf_not_x
movia r8,out_hex_uart_0
callr r8
br asm_printf_loop
asm_printf_not_x:
cmpeqi r9,r8,'d' # Check for %d (decimal).
beq r9,r0,asm_printf_not_d
movia r8,out_number_uart_0
callr r8
br asm_printf_loop
asm_printf_not_d:
cmpeqi r9,r8,'c' # Check for %c (character).
beq r9,r0,asm_printf_not_c
# Print character argument.
br asm_printf_doprint
asm_printf_not_c:
cmpeqi r9,r8,'s' # Check for %s (string).
beq r9,r0,asm_printf_not_s
movia r8,out_string_uart_0
callr r8
br asm_printf_loop
asm_printf_not_s:
asm_printf_unknown:
# We do not know what to do with other formats.
# Print the format string text.
movi r4,'%'
movia r8,out_char_uart_0
callr r8
ldb r4,-1(r16)
br asm_printf_doprint
asm_printf_end:
POP r20
POP r19
POP r18
POP r17
POP r16
POP ra
ret
#
# End of simplified printf() replacement code.
#
################################################################
#
# End of file.
#
.end
</code></pre>
<p>… and C code:</p>
<pre><code>/*
* lab3upg1helpers.c - version 2010-02-22
*
* Written by F Lundevall.
* Copyright abandoned.
* This file is in the public domain.
*/
/* Declare functions which are defined in other files,
* or late in this file (after their first use). */
int nextprime( int );
void out_char_uart_0( int );
/* The sloppy declaration of nios2int_printf below
* hides the variable number of arguments,
* and the variable types of those arguments. */
void nios2int_printf();
int primesearch( int next )
{
next = nextprime( next ); /* Produce a new prime. */
nios2int_printf( "\n\rMain: %d is prime", next );
return( next );
}
/*
* ********************************************************
* *** You don't have to study the code below this line ***
* ********************************************************
*/
/*
* nextprime
*
* Return the first prime number larger than the integer
* given as a parameter. The integer must be positive.
*/
#define PRIME_FALSE 0 /* Constant to help readability. */
#define PRIME_TRUE 1 /* Constant to help readability. */
int nextprime( int inval )
{
register int perhapsprime = 0; /* Holds a tentative prime while we check it. */
register int testfactor; /* Holds various factors for which we test perhapsprime. */
register int found; /* Flag, false until we find a prime. */
if (inval < 3 ) /* Initial sanity check of parameter. */
{
if(inval <= 0) return(1); /* Return 1 for zero or negative input. */
if(inval == 1) return(2); /* Easy special case. */
if(inval == 2) return(3); /* Easy special case. */
}
else
{
/* Testing an even number for primeness is pointless, since
* all even numbers are divisible by 2. Therefore, we make sure
* that perhapsprime is larger than the parameter, and odd. */
perhapsprime = ( inval + 1 ) | 1 ;
}
/* While prime not found, loop. */
for( found = PRIME_FALSE; found != PRIME_TRUE; perhapsprime += 2 )
{
/* Check factors from 3 up to perhapsprime/2. */
for( testfactor = 3; testfactor <= (perhapsprime >> 1) + 1; testfactor += 1 )
{
found = PRIME_TRUE; /* Assume we will find a prime. */
if( (perhapsprime % testfactor) == 0 ) /* If testfactor divides perhapsprime... */
{
found = PRIME_FALSE; /* ...then, perhapsprime was non-prime. */
goto check_next_prime; /* Break the inner loop, go test a new perhapsprime. */
}
}
check_next_prime:; /* This label is used to break the inner loop. */
if( found == PRIME_TRUE ) /* If the loop ended normally, we found a prime. */
{
return( perhapsprime ); /* Return the prime we found. */
}
}
return( perhapsprime ); /* When the loop ends, perhapsprime is a real prime. */
}
/*
* out_string_uart_0
*
* Simple output routine, replaces printf()
* for constant strings.
*
* The argument is a pointer to an array of char.
* The array can have any length, as long as there
* is a trailing null-character at the end.
*
* This routine calls out_char_uart_0 repeatedly,
* to do the actual output.
*/
void out_string_uart_0( char * cp )
{
while( *cp )
{
out_char_uart_0( *cp );
cp += 1;
}
}
</code></pre>
<p>The improvement I can think of is placing the macros in files of their own instead of everything in the same file so that the file does not get this large and cumbersome. </p>
|
[] |
[
{
"body": "<p>Macros in assembler language can be useful but you have to be careful not to\nover use them. Your <code>PUSH</code>/<code>POP</code> macros are overused and hence inefficient -\nand <strong>in interrupt related code, efficiency is king</strong>. </p>\n\n<p>For example your <code>PUSH</code> macro has two instructions, reserving space and\nstoring a register. You then use it 16 times in <code>PUSHMOST</code> (and its\nequivalent, <code>POP</code> in <code>POPMOST</code>). This will be processed into:</p>\n\n<pre><code> subi sp, sp,4\n stw at, 0(sp)\n subi sp, sp,4\n stw r2, 0(sp)\n subi sp, sp,4\n stw r3, 0(sp)\n subi sp, sp,4\n stw r4, 0(sp)\n ... etc\n</code></pre>\n\n<p>It reserves 4 bytes 16 times! What you should do in <code>PUSHMOST</code> is to reserve\nspace once and then store each register:</p>\n\n<pre><code>.macro PUSHMOST reg\n subi sp, sp,48\n stw at, 0(sp)\n stw r2, 0(sp)\n stw r3, 0(sp)\n stw r4, 0(sp)\n ... etc\n.endm\n</code></pre>\n\n<p>Same goes for <code>POPINT</code> and <code>PUSHINT</code></p>\n\n<p>I'll come back to the main code later...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:40:01.587",
"Id": "36209",
"ParentId": "18986",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T01:49:51.817",
"Id": "18986",
"Score": "2",
"Tags": [
"c",
"assembly",
"embedded",
"trampoline"
],
"Title": "Nios 2 interrupt handler"
}
|
18986
|
<p>I would like a fair minded critique of this code to get some feedback. I am not trying to re-invent the mold here, and I know there are plugins galore I could have used to do what I am doing here, but the point was to do it myself so that I can learn more and become better.</p>
<p>I have included comments to try and best explain my train of thought through the process, please don't implicitly critique the comments, they are just to explain my thinking as I made this code. </p>
<p>code below does exactly what I want..functions great in all modern browsers, rip me apart and make it better so I can get better:</p>
<pre><code>$(document).ready(function(){
var sliding = false
$(function () {
var pos = new Array(); //certainly a way to automate this more but I didn't mind putting exact numbers in for interval postions...please critique.
pos[0] = 0;
pos[1] = 67;
pos[2] = 133;
pos[3] = 199;
pos[4] = 267;
pos[5] = 333;
var target = $('span.slider')
var targetToMove = null;
var sliderCoordStart = null;
var mouseMovement = null;
target.mousedown(function(c) {
c.preventDefault();//prevent chrome from turning cursor to text when dragging
sliding = true
targetToMove = $(this);
targetToMove.addClass('noselect');//make sure we cant drag untargeted things all over the screen
mouseCoordStart = c.clientX;
sliderCoordStart= parseInt(targetToMove.css('marginLeft'));
oncontextmenu = function() {
return false
}
});
$(document).mouseup(function(e) {
oncontextmenu = function() {
return true
}
sliding = false
document.onselectstart = function(){
return true;
}
if(targetToMove !=null){
targetToMove.removeClass('noselect');//no need to have the non select class anymore
}
var compare = new Array();
if(mouseMovement !=null ){
for(c=0;c<=5;c++){//do some math to make sure the slider ends up going to the closest interval postion
compare[c] = Math.abs(pos[c] - mouseMovement);
}
var goTo = Math.min.apply(Math, compare)
var finalPos = compare.indexOf(goTo);
targetToMove.css('marginLeft', pos[finalPos])
}
})
$(document).mousemove(function(e) {
if(sliding){
document.onselectstart = function(){ //probably a better/smoother way to chain that right?
return false;
}
sliderPos = targetToMove.css('marginLeft');
mouseMovement = (e.pageX - mouseCoordStart)+sliderCoordStart;
if(mouseMovement <= 0){//make sure we never exceed the left boundary
mouseMovement = 0;
}
if(mouseMovement >= 333){//make sure we never exceed the right boundary
mouseMovement = 333;
}
targetToMove.css('marginLeft', mouseMovement)
}
})
})
});
</code></pre>
|
[] |
[
{
"body": "<p>Here are some suggestions to simplify the syntax:</p>\n\n<ul>\n<li>For <code>pos</code>, use an array literal: <code>var pos = [0, 67, 133, 199, 267, 333]</code>\n<ul>\n<li>Similar thing for <code>compare</code>: <code>var compare = [];</code></li>\n</ul></li>\n<li>You're missing semi-colons after some statements</li>\n<li><p>You can make initializing <code>compare</code> simpler using <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow\">Array.prototype.map</a> (doesn't work on IE < 9):</p>\n\n<pre><code>var compare = pos.map(function (e) {\n return e - mouseMovement;\n});\n</code></pre>\n\n<ul>\n<li><p>If you need to support IE < 9, I'd either implement <code>map</code>, or do basically what you're doing, but use <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push\" rel=\"nofollow\">Array.prototype.push</a> instead:</p>\n\n<pre><code>for(var c=0;c<=5;c++){//do some math to make sure the slider ends up going to the closest interval postion\n compare.push(Math.abs(pos[c] - mouseMovement));\n}\n</code></pre></li>\n</ul></li>\n<li><p>You've got a lot of undefined variables that will default to the global scope:</p>\n\n<ul>\n<li><code>sliderPos</code>- not used</li>\n<li><code>mouseCoordStart</code>- dangerous because it might not be defined when it's used</li>\n<li><code>oncontextmenu</code>- not used anywhere</li>\n</ul></li>\n<li><code>333</code> in your mousemove handler is magic, perhaps it should be <code>pos[pos.length-1]</code>?</li>\n</ul>\n\n<p>I'm not going to comment on jQuery plug-in style (I don't use jQuery) or your implementation of a \"form slider\" (which I assume is an implementation of an <a href=\"http://php.quicoto.com/how-to-create-html5-input-range/\" rel=\"nofollow\">HTML5 input range</a>).</p>\n\n<p>Hopefully this was useful!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T22:01:44.763",
"Id": "30390",
"Score": "0",
"body": "Thanks much for the feedback. So what should I do with mouseCoordStart? The other variables are indeed not used and missed removing them before posting. Actually was not going to use input range...just was going to js in the final value on some hidden form fields?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T05:51:49.917",
"Id": "30412",
"Score": "0",
"body": "First of all, declare it somewhere, there's no `var mouseCoordStart`, so this is global. Maybe stick it next to `sliderCoordStart`. I missed the `if (sliding)` conditional, so you should be fine. The formatting was funky, so it looked like it returned after creating the callback. Just declare it and you should be fine."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T08:19:44.667",
"Id": "18988",
"ParentId": "18987",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18988",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T06:10:04.710",
"Id": "18987",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Wanted to write my own form slider, Jquery/JS"
}
|
18987
|
<p>This is an iterative implementation of alpha beta tree search in C#. Please help me confirm the correctness of my code. <code>search()</code> is called when the search begins.</p>
<pre><code>int depth;
Func<board, int> value;
Func<board, List<string>> legalmoves;
Random randomgenerator = new Random();
board board;
Stack<int> alphas = new Stack<int>();
Stack<int> betas = new Stack<int>();
Stack<int> calllevels = new Stack<int>();
Stack<string> nodesleft = new Stack<string>();
Stack<string> callstack = new Stack<string>();
void search()
{
alphas.Push(int.MinValue);
betas.Push(int.MaxValue);
pushlegalmoves();
//initialize the alpha, beta, and push all legal moves
while (nodesleft.Any())
{
string currentnode = nodesleft.Pop();
int calllevel = calllevels.Count;
int movesleft = calllevels.Pop();
callstack.Push(currentnode);
move(currentnode);
//extract all information about the node and play the move
if (calllevel != depth)
{
calllevels.Push(movesleft);
alphas.Push(alphas.First());
betas.Push(betas.First());
pushlegalmoves();
//expand the tree if not terminal(aka not enough depth here)
}
else
{
if (calllevel % 2 == 0) max(calllevel, movesleft, currentnode);
else min(calllevel, movesleft, currentnode);
//cleanup and process everything if node is terminal
}
}
}
void max(int calllevel, int movesleft, string currentnode)
//cleans up and processes tree, starting from a max player terminal node
{
bool color = true;
bool cleanup = false;
//color means which player is the function currently processing. true = max player, false = min player
//cleanup means whether to process the the search tree up to the next level
int score = value(board);
if (score >= betas.First())
{
cleanup = true;
score = betas.First();
}
if (score > alphas.First())
{
alphas.Pop();
alphas.Push(score);
}
if (movesleft == 1) cleanup = true;
unmove(callstack.Pop());
//changes the alpha and beta values. if the move is last move or a beta cutoff is issued, then clean up the current tree level. undo the current move.
while (cleanup)
{
color = !color;
cleanup = false;
//change the player. reset whether to clecan up
for (; movesleft > 0; movesleft--)
{
nodesleft.Pop();
}
movesleft = calllevels.Pop();
unmove(callstack.Pop());
alphas.Pop();
betas.Pop();
//climbing up the next level
if (color)
{
if (score >= betas.First())
{
cleanup = true;
score = betas.First();
}
if (score > alphas.First())
{
alphas.Pop();
alphas.Push(score);
}
}
else
{
if (score <= alphas.First())
{
cleanup = true;
score = alphas.First();
}
if (score < betas.First())
{
betas.Pop();
betas.Push(score);
}
}
if (movesleft == 1) cleanup = true;
//processing the next level and deciding whether to keep cleaning up
}
calllevels.Push(movesleft - 1);
//puts in the correct number of unprocessed moves
}
void min(int calllevel, int movesleft, string currentnode)
//cleans up and processes tree, starting from a min player terminal node
{
bool color = false;
bool cleanup = false;
//color means which player is the function currently processing. true = max player, false = min player
//cleanup means whether to process the the search tree up to the next level
int score = -value(board);
if (score <= alphas.First())
{
cleanup = true;
score = alphas.First();
}
if (score < betas.First())
{
betas.Pop();
betas.Push(score);
}
if (movesleft == 1) cleanup = true;
unmove(callstack.Pop());
//changes the alpha and beta values. if the move is last move or a alpha cutoff is issued, then clean up the current tree level. undo the current move.
while (cleanup)
{
color = !color;
cleanup = false;
//change the player. reset whether to clecan up
for (; movesleft > 0; movesleft--)
{
nodesleft.Pop();
}
movesleft = calllevels.Pop();
unmove(callstack.Pop());
alphas.Pop();
betas.Pop();
//climbing up the next level
if (color)
{
if (score >= betas.First())
{
cleanup = true;
score = betas.First();
}
if (score > alphas.First())
{
alphas.Pop();
alphas.Push(score);
}
}
else
{
if (score <= alphas.First())
{
cleanup = true;
score = alphas.First();
}
if (score < betas.First())
{
betas.Pop();
betas.Push(score);
}
}
if (movesleft == 1) cleanup = true;
//processing the next level and deciding whether to keep cleaning up
}
calllevels.Push(movesleft - 1);
//puts in the correct number of unprocessed moves
}
</code></pre>
|
[] |
[
{
"body": "<h3>Readability</h3>\n<p>The indentation is good and you have good variable names, but some of them are hard to read. Why? More or less because they're lowercase. <a href=\"http://msdn.microsoft.com/en-us/library/x2dbyw72(v=vs.71).aspx\" rel=\"nofollow noreferrer\">Variables and parameters should be camelCase.</a></p>\n<ul>\n<li>calllevels >> callLevels</li>\n<li>nodesleft >> nodesLeft</li>\n<li>callstack >> callStack</li>\n</ul>\n<p>Method names like <code>search</code> and <code>max</code> should be PascalCase. In other words, <code>Search</code> and <code>Max</code>.</p>\n<hr />\n<p>This could use some braces.</p>\n<pre><code>else\n{\n if (calllevel % 2 == 0) max(calllevel, movesleft, currentnode);\n else min(calllevel, movesleft, currentnode);\n //cleanup and process everything if node is terminal\n}\n</code></pre>\n<p>It seems like a minor thing, but if you go to change it later, and forget to add braces then, it could cause trouble.</p>\n<hr />\n<p>I'm not a big fan of for loops without an index declared right in it. Opt for a while loop instead.</p>\n<pre><code>for (; movesleft > 0; movesleft--)\n{\n nodesleft.Pop();\n}\n</code></pre>\n<p>Vs</p>\n<pre><code>while (movesLeft > 0) \n{\n nodesLeft.Pop();\n movesLeft--;\n}\n</code></pre>\n<hr />\n<p>It's not obvious to me how to fix it, but there should be some way to clean up the seeming duplication here. It should be possible to write a single function to do this work. Perhaps it takes a boolean parameter. I'm not sure, but I know there's a way.</p>\n<pre><code> if (color)\n {\n if (score >= betas.First())\n {\n cleanup = true;\n score = betas.First();\n }\n if (score > alphas.First())\n {\n alphas.Pop();\n alphas.Push(score);\n }\n }\n else\n {\n if (score <= alphas.First())\n {\n cleanup = true;\n score = alphas.First();\n }\n if (score < betas.First())\n {\n betas.Pop();\n betas.Push(score);\n }\n }\n</code></pre>\n<hr />\n<p>Here is some duplication that we can pretty easily fix. There are <em>a lot</em> of places where you Pop an item off the stack and immediately push the score on. Replace every instance of it with a method. It's a small step toward DRYing this up.</p>\n<pre><code>private void PopThenPushScore(Stack<int> stack, int score)\n{\n stack.Pop();\n stack.Push(score);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-30T01:29:38.227",
"Id": "104962",
"Score": "0",
"body": "I know this isn't the help you're really looking for, but maybe the bump will help the question gain some attention from someone who *can* actually help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-30T01:26:40.447",
"Id": "58458",
"ParentId": "18989",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T09:11:15.203",
"Id": "18989",
"Score": "2",
"Tags": [
"c#",
"tree",
"search"
],
"Title": "Iterative implementation of alpha beta tree search"
}
|
18989
|
<p>I have this function definition which takes an r and applies the function <code>f</code> <code>n</code> times:</p>
<pre><code>r => (1 to n).foldLeft(r)((rx, _) => f(rx))
</code></pre>
<p>So for <code>n=3</code> this is equivalent to <code>f(f(f(r)))</code></p>
<p>I don't like this solution, because it defines a <code>Range</code> from <code>1 to n</code> which really isn't get used at all, which becomes obvious in the unused parameter <code>_</code> in the fold left. This in turn forces me to give a separate name to <code>rx</code> which feels wrong to me.</p>
<p>Any idea how I can streamLine this code?</p>
|
[] |
[
{
"body": "<p>What's wrong with straight recursion?</p>\n\n<pre><code>def ntimes[A](n:Int, f:A=>A, a:A):A = if (n==0) a else ntimes(n-1, f, f(a))\n</code></pre>\n\n<p>Another clean option is</p>\n\n<pre><code>Iterator.iterate(a)(f).drop(n).next\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T10:19:07.277",
"Id": "18991",
"ParentId": "18990",
"Score": "7"
}
},
{
"body": "<p>I found one alternative, which at least spares the number Range:</p>\n\n<pre><code>r => Array.fill(n)(f(_)).reduce((f1, f2) => x => f1(f2(x)))(r)\n</code></pre>\n\n<p>But I find the reduce part rather verbose and hard to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T10:22:10.093",
"Id": "18992",
"ParentId": "18990",
"Score": "0"
}
},
{
"body": "<p>What about lazy evaluation, using Streams?</p>\n\n<pre><code>def applyFunc[A]( f : A => A, a :A ) : Stream[A] = f( a ) #:: applyFunc( f, f(a) )\n</code></pre>\n\n<p>Then for example you could use it like so: </p>\n\n<pre><code>def addOne( i :Int ) = i + 1\n\nval succs = applyFunc( addOne, 0 )\n\nval firstThreeResults= succs.take( 3 ).toList\n\nval onlyFifthResult = succs( 4 )\n</code></pre>\n\n<p>Of course, if f is a heavy computation, you could also calculate the result as an intermediate step:</p>\n\n<pre><code> def applyFunc[A]( f : A => A, a :A ) : Stream[A] = {\n\n val res = f( a )\n\n res #:: applyFunc( f, res )\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T10:45:29.650",
"Id": "18994",
"ParentId": "18990",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T09:59:19.687",
"Id": "18990",
"Score": "5",
"Tags": [
"scala",
"functional-programming"
],
"Title": "Cleaner way for coding a repetitive application of a function"
}
|
18990
|
<p>I'm new to C# and just tried the <a href="http://osherove.com/tdd-kata-1/" rel="nofollow">String Calculator Kata</a> for practice. What I like to know is if you (as more experienced C# programmers) have some suggestions for improvement with the end result (concerning readability, good practices, C# specific idioms etc.)</p>
<p>Code:</p>
<pre><code>public class StringCalculator
{
private const char DefaultDelimiter = ',';
public int Add(string input)
{
if (string.IsNullOrEmpty(input))
return 0;
IEnumerable<string> tokens = Tokenize(input);
IEnumerable<int> numbers = tokens.Select(ConvertToNumber).ToList();
CheckForNegativeNumbers(numbers);
return numbers.Sum();
}
private static void CheckForNegativeNumbers(IEnumerable<int> numbers)
{
List<int> negativeNumbers = numbers.Where(number => number < 0).ToList();
if (negativeNumbers.Count > 0)
throw new ArgumentException("Negatives not allowed: " + FormatNegativeNumbers(negativeNumbers));
}
private static string FormatNegativeNumbers(IEnumerable<int> negativeNumbers)
{
return string.Join(" ", negativeNumbers);
}
private static IEnumerable<string> Tokenize(string input)
{
char delimiter = DefaultDelimiter;
if (CustomDelimiterSpecified(input))
{
delimiter = ParseCustomDelimiter(ref input);
}
else
{
input = ReplaceAlternativeDelimitersWithCommas(input);
}
return input.Split(delimiter);
}
private static char ParseCustomDelimiter(ref string input)
{
char customDelimiter = input[2];
input = input.Substring(4);
return customDelimiter;
}
private static bool CustomDelimiterSpecified(string input)
{
return input.StartsWith("//");
}
private static string ReplaceAlternativeDelimitersWithCommas(string input)
{
return input.Replace("\n", ",");
}
private static int ConvertToNumber(string input)
{
return int.Parse(input);
}
}
</code></pre>
<p>Tests:</p>
<pre><code>[TestClass]
public class StringCalculatorTest
{
private StringCalculator calculator = new StringCalculator();
[TestMethod]
public void Add_EmptyString_ReturnsZero()
{
int result = calculator.Add("");
Assert.AreEqual(0, result);
}
[TestMethod]
public void Add_OneNumber_ReturnsNumber()
{
int result = calculator.Add("42");
Assert.AreEqual(42, result);
}
[TestMethod]
public void Add_TwoNumbersDelimitedWithComma_ReturnsSum()
{
int result = calculator.Add("1,2");
Assert.AreEqual(3, result);
}
[TestMethod]
public void Add_MultipleNumbersDelimitedWithComma_ReturnsSum()
{
int result = calculator.Add("1,2,3");
Assert.AreEqual(6, result);
}
[TestMethod]
public void Add_TwoNumbersDelimitedWithNewLine_ReturnsSum()
{
int result = calculator.Add("1\n2");
Assert.AreEqual(3, result);
}
[TestMethod]
public void Add_TwoNumbersDelimitedWithCustomDelimiter_ReturnsSum()
{
string input = "//;\n1;2";
int result = calculator.Add(input);
Assert.AreEqual(3, result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Add_NegativeNumber_ThrowsArgumentException()
{
calculator.Add("-1");
}
[TestMethod]
public void Add_NegativeNumber_ErrorMessageContainsNumber()
{
try
{
calculator.Add("-1");
Assert.Fail();
}
catch (ArgumentException e)
{
Assert.AreEqual("Negatives not allowed: -1", e.Message);
}
}
[TestMethod]
public void Add_MultipleNegativeNumbers_ErrorMessageContainsAllNegativeNumbers()
{
try
{
calculator.Add("-1,2,-3");
Assert.Fail();
}
catch (ArgumentException e)
{
Assert.AreEqual("Negatives not allowed: -1 -3", e.Message);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think your answer was pretty well done. Really, for that test, you probably got near full marks. I know that wasn't much of an answer, but there really wasn't much to add to your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:47:02.157",
"Id": "30307",
"Score": "0",
"body": "+1 thank you. Actually, that is a valuable answer for me as this is all new for me and I can't always judge well if this is the way to do it in C#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:53:26.203",
"Id": "30308",
"Score": "0",
"body": "It was very good, really. You're code was very readable, with good naming, clear refactoring, and everything. I can't really think of ways to do it more clear than you did. Good job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:53:54.177",
"Id": "30309",
"Score": "0",
"body": "By the way, what did you program in previously anyway? Just curious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T14:15:18.287",
"Id": "30315",
"Score": "0",
"body": "Mainly Delphi for my job, occasionally some Java in my free time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T14:45:34.590",
"Id": "30316",
"Score": "0",
"body": "Mostly what you do in Java would be correct in C#. Of course there are significant differences but there're still more of the same thing than otherwise."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T11:38:41.323",
"Id": "18996",
"ParentId": "18995",
"Score": "1"
}
},
{
"body": "<p>I like your solution as well. The only thing I might consider doing differently is making input a private instance variable which would mean all your input parameter requirements to the methods would no longer be required.</p>\n\n<p>Something like:</p>\n\n<pre><code>public class StringCalculator\n{\n private const char DefaultDelimiter = ',';\n private string _input = \"\";\n\n public int Add(string input)\n {\n _input = input;\n\n if (string.IsNullOrWhiteSpace(_input))\n return 0;\n\n IEnumerable<string> tokens = Tokenize();\n IEnumerable<int> numbers = tokens.Select(ConvertToNumber).ToList();\n\n CheckForNegativeNumbers(numbers);\n\n return numbers.Sum();\n }\n\n private static void CheckForNegativeNumbers(IEnumerable<int> numbers)\n {\n var negativeNumbers = numbers.Where(number => number < 0).ToList();\n\n if (negativeNumbers.Any())\n throw new ArgumentException(\"Negatives not allowed: \" + FormatNegativeNumbers(negativeNumbers));\n }\n\n private static string FormatNegativeNumbers(IEnumerable<int> negativeNumbers)\n {\n return string.Join(\" \", negativeNumbers);\n }\n\n private IEnumerable<string> Tokenize()\n {\n char delimiter = DefaultDelimiter;\n\n if (CustomDelimiterSpecified())\n {\n delimiter = ParseCustomDelimiter();\n }\n else\n {\n ReplaceAlternativeDelimitersWithCommas();\n }\n\n return _input.Split(delimiter);\n }\n\n private char ParseCustomDelimiter()\n {\n char customDelimiter = _input[2];\n _input = _input.Substring(4);\n return customDelimiter;\n }\n\n private bool CustomDelimiterSpecified()\n {\n return _input.StartsWith(\"//\");\n }\n\n private void ReplaceAlternativeDelimitersWithCommas()\n {\n _input = _input.Replace(\"\\n\", \",\");\n }\n\n private static int ConvertToNumber(string input)\n {\n int intValue;\n return int.TryParse(input, out intValue) ? intValue : 0; \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T20:23:51.633",
"Id": "30325",
"Score": "0",
"body": "@codesparkle yep :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T20:04:50.787",
"Id": "19002",
"ParentId": "18995",
"Score": "1"
}
},
{
"body": "<p>In regards to your implementation, I can see no reason that it needs to be an instance class so I would suggest making the class static. There is no reason to have to create a <code>Calculator</code> to call <code>Add</code>, it returns the result of the addition and maintains no state. If you were maintaining a running total and had a <code>Subtract</code> method etc then it would make sense as an instance class as you wouldn't want 2 separate callers to share the same running total.</p>\n\n<p>This method may be better expressed as a Linq query:</p>\n\n<pre><code>private static void CheckForNegativeNumbers(IEnumerable<int> numbers)\n{\n List<int> negativeNumbers = numbers.Where(number => number < 0).ToList();\n\n if (negativeNumbers.Count > 0)\n throw new ArgumentException(\"Negatives not allowed: \" + FormatNegativeNumbers(negativeNumbers));\n}\n</code></pre>\n\n<p>Using <code>.Any()</code> will return true as soon as it finds a match rather than having to enumerate the whole collection (I know in this case you will have a limited number of values in <code>numbers</code> but it's a good method to know about). Also, it saves having to create a list just to check the count so it's more efficient too (the amount by which will depend on the implementation and number of values, but again it's a good practice to stick to where it makes sense).</p>\n\n<pre><code>private static void CheckForNegativeNumbers(IEnumerable<int> numbers)\n{\n if (numbers.Any(number => number < 0))\n {\n throw new ArgumentException(\"Negatives not allowed: \" + FormatNegativeNumbers(negativeNumbers));\n }\n}\n</code></pre>\n\n<p>Also, avoid inline or unbraced <code>if</code> conditions - always wrap the body in braces. It makes it easier to follow the code and helps prevent bugs being introduced at a later stage if additional actions needs to happen inside the same <code>if</code> body.</p>\n\n<p>In terms of your tests, I have a few suggestions.</p>\n\n<p>Firstly, change these two tests:</p>\n\n<pre><code>[TestMethod]\n[ExpectedException(typeof(ArgumentException))]\npublic void Add_NegativeNumber_ThrowsArgumentException()\n{\n calculator.Add(\"-1\");\n}\n\n[TestMethod]\npublic void Add_NegativeNumber_ErrorMessageContainsNumber()\n{\n try\n {\n calculator.Add(\"-1\");\n Assert.Fail();\n }\n catch (ArgumentException e)\n {\n Assert.AreEqual(\"Negatives not allowed: -1\", e.Message);\n }\n}\n</code></pre>\n\n<p>The <code>ExpectedException</code> attribute is known to be problematic as you can't verify which method call has thrown an exception in the case that you have multiple method calls (see <a href=\"http://jamesnewkirk.typepad.com/posts/2008/06/replacing-expec.html\">this blog post</a> for further details). Another problem is the one you are facing in the second method whereby you want to verify the exception. If your testing framework has it (both NUnit and xUnit do) use <code>Assert.Throws</code> instead.</p>\n\n<pre><code>var exception = Assert.Throws<ArgumentException>(() => calculator.Add(\"-1\"));\n</code></pre>\n\n<p>This allows you to verify the exact method that should fail and also capture the exception if you want to check the message, param name etc.</p>\n\n<p>Secondly, stop using a shared instance of <code>calculator</code> across all tests. They should all be isolated from each other. One test method should not have the ability to potentially alter the state for another test method. I know in this example, there is no shared state in calculator and in this instance it would be alleviated by making the class static as I mentioned above, but it's a good practice to get into regardless.</p>\n\n<p>Personally I consider calling <code>Assert.Fail()</code> a code smell, it's use should be carefully considered to see if there is a different way the test can be written. If for whatever reason you decide that you need to call it, at least use the overload to specify a failure reason so that if the test fails you have some clue as to why: <code>Assert.Fail(\"An ArgumentException should have been thrown since we have called Add with a negative number\");</code>.</p>\n\n<p>Something else you may want to consider as far as test names go is re-wording the test names to be more contextual to the desired behaviour. For example <code>Add_EmptyString_ReturnsZero</code> could be expressed as <code>WhenCallingAdd_WithAnEmptyString_ZeroShouldBeReturned</code> the method name is slightly longer but it defines the specification of the behaviour. This will help you (and other developers) understand <em>how</em> your application should behave at a later stage.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T21:47:05.803",
"Id": "30329",
"Score": "0",
"body": "+1, this has been very useful, thank you very much for your input, you have some very good points."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T03:33:11.427",
"Id": "30340",
"Score": "0",
"body": "I'm confused, you advocate moving it to a static class with static methods, then you say don't have an instance class running across all tests in your unit tests because they might step on each other. A static class introduces the same problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T07:24:16.303",
"Id": "30341",
"Score": "0",
"body": "@JeffVanzella you might reread the last sentence of this paragraph where he states that this does not apply here (when using the static class) but is a good general practice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T21:23:37.680",
"Id": "19005",
"ParentId": "18995",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T11:21:57.843",
"Id": "18995",
"Score": "6",
"Tags": [
"c#",
"unit-testing",
"calculator"
],
"Title": "String calculator kata"
}
|
18995
|
<p>I have written a simple VM in JavaScript and it interprets source code written in JSON.</p>
<p>The JSON object must have a "exports" property, which is a dictionary that matches a string into a integer value. This value is an index to "entries" property, which is an array of entries.</p>
<p>For each entry it contains a "binds" and a "execs" property. They are all arrays of object that contains <code>callee</code> and <code>params</code>. <code>callee</code> is a single object that contains "type" and <code>name</code> (string) or <code>index</code> (integer). <code>type</code> can be <code>extern</code> (refer to some function implemented in the VM) or "entry" (refer to entries array) or "bind" (refer to binds array) or "param" (at runtime, refer to the parameters given to the call). <code>params</code> is an array of exactly the same type of <code>callee</code>.</p>
<p>At runtime, to call the VM one must specify a name listed in "exports" array, and some parameters. The VM will then look at the referred entry and create bind objects (record all resolved parameters, but not actually call them) for each item in the binds array. And then for each item in the "execs" array, execute at least one of them (how to do so is not specified).</p>
<p>Here is a simple implementation that only execute the first item in the "execs" array, and only provides externs for <code>+</code> <code>-</code> <code>*</code> <code>1</code> and <code><</code> (it also allow to "run" a <code>boolean</code> typed value, the rule is to run the first argument if the value is true otherwise the second argument):</p>
<pre><code>function evalJson(json){
return eval("(" + json + ")");
}
function RunEngine(){
var log = function(str){
var p = document.createElement("p");
p.appendChild(document.createTextNode(str));
document.getElementById("log").appendChild(p);
};
var externs = {
"<":function(n1,n2,c){
log(n1 + " < "+n2+"? " + (n1<n2));
this.callobj(c,n1<n2);
}.bind(this),
"1":1,
"+":function(n1,n2,c){
log(n1 + " + "+n2+" = " + (n1+n2));
this.callobj(c,n1+n2);
}.bind(this),
"-":function(n1,n2,c){
log(n1 + " - "+n2+" = " + (n1-n2));
this.callobj(c,n1-n2);
}.bind(this),
"*":function(n1,n2,c){
log(n1 + " * "+n2+" = " + (n1*n2));
this.callobj(c,n1*n2);
}.bind(this)
};
this.getExtern = function(name){
return externs[name];
};
var calls=[];
var running = false;
this.callobj = function(obj){
var args=[].slice.apply(arguments);
args.shift();
if(typeof(obj)==="boolean") this.callobj(obj?args[0]:args[1]);
if(typeof(obj)==="function") {
calls.push(obj.bind.apply(obj,[this].concat(args)));
if(!running)running=true;
else return;
while(calls.length>0){
calls.pop()();
}
running = false;
};
};
this.bindobj = function(obj){
var args=[].slice.apply(arguments);
args.shift();
return this.callobj.bind.apply(this.callobj,[this,obj].concat(args));
};
}
function JsonVM(code,engine){
var entries = [];
var getRefItem = function(refitem,ent,binds,args){
if(refitem.type==="entry") return ent[refitem.index];
else if(refitem.type==="bind") return binds[refitem.index];
else if(refitem.type==="param") return args[refitem.index];
else if(refitem.type=="extern") return engine.getExtern(refitem.name);
}.bind(this);
var getBind = function(callspec,ent,binds,args){
var objs = [getRefItem(callspec.callee,ent,binds,args)];
for(var i=0;i<callspec.params.length;++i){
objs.push(getRefItem(callspec.params[i],ent,binds,args));
}
return engine.bindobj.apply(engine,objs);
}.bind(this);
var getEntry = function(entry){
var f = function(){
var binds=[];
var args = [].slice.apply(arguments);
entry.binds.forEach(function(bind){
binds.push(getBind(bind,entries,binds,args));
});
var v = getBind(entry.execs[0],entries,binds,args);
engine.callobj(v);
};
return f.bind(this);
}.bind(this);
code.entries.forEach(function(entry){
entries.push(getEntry(entry));
});
this.runExport = function(name){
var args=[].slice.apply(arguments);
args.shift();
engine.callobj.apply(engine,[entries[code.exports[name]]].concat(args));
};
}
window.onload = function(){
document.getElementById("run").onclick=function(){
var code = evalJson(document.getElementById("code").value);
var vm = new JsonVM(code,new RunEngine());
vm.runExport("Factorial",10,function(n){ alert(n); });
};
};
</code></pre>
<p>The following HTML file is associated with it:</p>
<pre><code><!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>JSON VM test</title>
<script type="text/javascript" src="jsonvm.js" ></script>
</head>
<body>
<textarea id="code" rows="60" cols="80"></textarea>
<input type="button" id="run" value="run" />
<div id="log" ></div>
</body>
</html>
</code></pre>
<p>Here is a sample JSON code that implements the <code>Factorial()</code> function:</p>
<pre><code>{
"exports":{"Factorial":0},
"entries":[{
"binds":[{
"callee":{"type":"entry","index":1},
"params":[{"type":"param","index":0},
{"type":"param","index":1}]
}],
"execs":[{
"callee":{"type":"extern","name":"<"},
"params":[{"type":"param","index":0},
{"type":"extern","name":"1"},
{"type":"bind","index":0}]
}]
},{ "binds":[{
"callee":{"type":"param","index":1},
"params":[{"type":"extern","name":"1"}]
},{
"callee":{"type":"entry","index":2},
"params":[{"type":"param","index":0},
{"type":"param","index":1}]
}],
"execs":[{
"callee":{"type":"param","index":2},
"params":[{"type":"bind","index":0},
{"type":"bind","index":1}]
}]
},{ "binds":[{
"callee":{"type":"entry","index":3},
"params":[{"type":"param","index":0},
{"type":"param","index":1}]
}],
"execs":[{
"callee":{"type":"extern","name":"-"},
"params":[{"type":"param","index":0},
{"type":"extern","name":"1"},
{"type":"bind","index":0}]
}]
},{ "binds":[{
"callee":{"type":"entry","index":4},
"params":[{"type":"param","index":0},
{"type":"param","index":1}]
}],
"execs":[{
"callee":{"type":"entry","index":0},
"params":[{"type":"param","index":2},
{"type":"bind","index":0}]
}]
},{ "binds":[],
"execs":[{
"callee":{"type":"extern","name":"*"},
"params":[{"type":"param","index":0},
{"type":"param","index":2},
{"type":"param","index":1}]
}]}]
}
</code></pre>
<p>To test, create the js file and the .html file, and open the html file in a browser, and then paste the JSON code to the text area, click "run". an alert will show the result ant prints the steps in the page (may require scrolling)</p>
<p>One more thing needed to know is that this VM implementation uses a trick to avoid keep using the call stack. Without this trick it will be even simpler.</p>
<p>The given code is working good. However, to make it working I have did some dirty hacks (I think). So I want this code to be reviewed and to see how to remove those hacks and makes the code more clear. Also please give me advice about OO design, code style and so on.</p>
<p>NOTES: Please do not advise about <code>evalJson</code> function, I understand using <code>eval</code> is not good but for this simple example it is OK and simple enough. If I were to move it to production I can simply replace the <code>evalJson</code> function implementation.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T12:56:18.717",
"Id": "37748",
"Score": "0",
"body": "You mentioned 'move it to production', can you tell us what you are trying to solve? Is the JSON generated from yet another programming language?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T05:32:15.387",
"Id": "38015",
"Score": "0",
"body": "Yes, I'm planning to create a Web UI for it. But now it is far too early to that step."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T03:25:28.273",
"Id": "52771",
"Score": "0",
"body": "@plalx Umm... Maybe I need more explanation. I think the example in the code above shall already implemented a VM with simple arithmetic operations as atomic functions, so it is ready to interpret the given Json code for \"Factorial\" function, so it is an example of how to use it. Roughly speaking, you write `JsonVM` function once only, and adjust `RunEngine` function whenever you want to add more atomic operations, to interpret an existing program that written in my JSON format given above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T13:57:26.087",
"Id": "52797",
"Score": "0",
"body": "@EarthEngine Yeah, I get the concept, however it's not that easy to follow the implementation through all these `callObj`, `doCallObj`, `bindObj` etc. Perhaps if you could add comments in the code so that it would be easier to understand. Otherwise I'll draw the execution plan once I have time to have a better understanding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T23:29:23.390",
"Id": "52858",
"Score": "0",
"body": "Emm... in this implementation `callObj` is just a wrapper to call `doCallObj` in order to make it work with varidic parameters (`arguments` in javascript). `bindObj` is just a lazy vesion of `callObj`, so calling `bindObj` just returns a function which when called, do the real jobs. This shall be clear when you look at the updated version of the code. Furthermore, `bindObj` is part of the public interface of the `RunEngine` but `callObj` is not. Also remember `bindObj` and `getExtern` are the only two methods required by the VM, an both of them return something executable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T23:38:02.473",
"Id": "52859",
"Score": "0",
"body": "Actually, since `callObj` is not exported, it is redundant. I leave it there simply because I am not sure would it be useful for the VM to call it directly. For example, the second loop of `getEntry` obtains results of `bindObj` and then calls it. Replace it by using `callObj` or `doCallObj` instead could be a way to optimize, since `bindObj` is lazy, and that loop requires strict evaluation."
}
] |
[
{
"body": "<p>I have re-written the whole code to make it more modular as well as taking advantage of prototypes. The way your code was written was quite inefficient since everything had to be redefined for every newly created instances of <code>JsonVM</code> or <code>RunEngine</code>, since the whole code was inside constructor functions.</p>\n\n<p>Unfortunately, there is no way to enforce the privacy of non-function instance members without sacrificing the benefits of using prototypes, so I've used a naming convention to identify private members: they start with and underscore _ (it's a very common practice).</p>\n\n<p>You will also notice that I've extracted the logging strategy out of the <code>RunEngine</code> and allowed to inject it instead. I am still unsure about how that feature should be designed (perhaps an AOP approach?), however it's better than having it encapsulated within the class.</p>\n\n<p>Anyway, have a look and let me know what you think.</p>\n\n<p><em><strong>Note: I haven't changed anything related to the processing logic since I wasn't enough confident.</em></strong></p>\n\n<pre><code>!function (exports, slice) {\n\n exports.RunEngine = (function () {\n\n var externs = ['<', '-', '*', '/'].reduce(function (res, op) {\n res[op] = createOperatorExternFn(op);\n return res;\n }, {\n '1': 1\n });\n\n function RunEngine(log) {\n this._calls = [];\n this._running = false;\n this._log = log;\n }\n\n function createOperatorExternFn(op) {\n var fn = new Function('n1, n2, c', [\n 'this._log(n1 + \" ', op, ' \" + n2 + \"', (op === '<'? '? ' : ' = '), '\" + (n1 ', op , 'n2));',\n 'arguments.callee.callObj.call(this, c, n1 ', op, ' n2);'\n ].join(''));\n\n fn.callObj = callObj;\n\n return fn;\n }\n\n function runItem(item) {\n var calls = this._calls,\n fn;\n\n calls.push(item);\n\n if (this._running) return;\n\n this._running = true;\n\n while (fn = calls.pop()) fn();\n\n this._running = false;\n }\n\n function callObj(obj) {\n doCallObj.call(this, obj, slice.call(arguments, 1));\n }\n\n function doCallObj(obj, args) {\n\n switch (typeof obj) {\n case 'boolean': doCallObj.call(this, obj? args[0] : args[1]); break;\n case 'function': runItem.call(this, obj.apply.bind(obj, this, args));\n }\n }\n\n function bindObj(obj, args) {\n var me = this;\n\n return function () {\n doCallObj.call(me, obj, args.concat(slice.apply(arguments)));\n };\n }\n\n RunEngine.prototype = {\n constructor: RunEngine,\n\n getExtern: function (name) {\n return externs[name];\n },\n\n bindObj: bindObj\n };\n\n return RunEngine;\n })();\n\n exports.VM = (function () {\n\n function VM(code, engine) {\n var entries = this._entries = [];\n this._code = code;\n this._engine = engine;\n\n code.entries.forEach(function (entry) {\n entries.push(getEntry.call(this, entry));\n }, this);\n }\n\n function getRefItem(refItem, binds, args) {\n switch (refItem.type) {\n case 'entry': return this._entries[refItem.index];\n case 'bind': return binds[refItem.index];\n case 'param': return args[refItem.index];\n case 'extern': return this._engine.getExtern(refItem.name);\n }\n }\n\n function getBind(callspec, binds, args) {\n var objs = callspec.params.map(function (param) {\n return getRefItem.call(this, param, binds, args);\n }, this);\n\n return this._engine.bindObj(\n getRefItem.call(this, callspec.callee, binds, args),\n objs\n );\n }\n\n function getEntry(entry) {\n var me = this;\n\n return function () {\n var binds = [],\n args = arguments;\n\n entry.binds.forEach(function (bind) {\n binds.push(getBind.call(me, bind, binds, args));\n });\n\n entry.execs.forEach(function (exec) {\n getBind.call(me, exec, binds, args)();\n });\n };\n }\n\n VM.prototype = {\n constructor: VM,\n runExport: function (name) {\n this._engine.bindObj(\n this._entries[this._code.exports[name]], \n slice.call(arguments, 1)\n )();\n }\n };\n\n return VM;\n })();\n\n}(\n window.jsonVM = window.jsonVM || {},\n Array.prototype.slice\n);\n\nwindow.addEventListener('load', function () {\n document.getElementById('run').addEventListener('click', function () {\n\n var code = JSON.parse(document.getElementById(\"code\").value),\n logFn = console.log.bind(console),\n vm = new jsonVM.VM(code, new jsonVM.RunEngine(logFn));\n\n vm.runExport(\"Factorial\", 10, logFn);\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T04:05:06.060",
"Id": "52775",
"Score": "0",
"body": "Thanks for your answer. I was focus on something else and not often check this page so thanks for your patient to my response. I will have a look at your code and update the Google code project if it passes the tests. Anyway, there are other tests available in the Google project, I would be very excited to see someone interested in them and tried them!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-12T06:28:46.377",
"Id": "32592",
"ParentId": "18997",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:23:43.043",
"Id": "18997",
"Score": "5",
"Tags": [
"javascript",
"json"
],
"Title": "A JavaScript VM that interprets code written in JSON"
}
|
18997
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.