body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
JavaScript is primarily a language focused on web development. Being a monopoly on the front end and having Node on the back end. Use this tag for questions regarding vanilla JavaScript; optionally tagged with an ECMAScript version. If you are using a preprocessor such as TypeScript please tag with that too.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-05-20T14:35:58.953",
"Id": "2515",
"Score": "0",
"Tags": null,
"Title": null
}
|
2515
|
<p>I have written a recursive function that I believe will return the 'maximum' row of the 4x4 matrix it is fed. By 'maximum' I mean that the maximum row of the matrix.</p>
<pre><code>1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
</code></pre>
<p>is row 4 (on account of the first column's values); the maximum row of the matrix</p>
<pre><code>1 2 3 4
2 3 4 1
4 4 1 2
4 1 2 3
</code></pre>
<p>is row 3 (on account of the first and second columns' values); the maximum row of the matrix</p>
<pre><code>1 2 3 4
2 3 4 1
4 4 1 2
4 4 2 3
</code></pre>
<p>is row 4 (on account of the first, second, and third columns' values); the maximum row of the matrix</p>
<pre><code>1 2 3 4
2 3 4 1
4 4 1 2
4 4 1 3
</code></pre>
<p>is row 4 (on account of the values in every column); and the maximum row of the matrix</p>
<pre><code>1 2 3 4
2 3 4 1
4 4 1 3
4 4 1 3
</code></pre>
<p>is row 3 (on account of the values in every column - pick the topmost row).</p>
<p>This function is a lot more involved than I expected when I sat down to write it. Please tell me there's an easier way to express this algorithm in C!</p>
<p>(The function is employed in a program written by a Pascalite; please forgive the fact that the arrays ignore their 0th member!)</p>
<p>Here's the function (together with its helper <code>indexOf()</code>, which is never fed an array in which val fails to appear!) Apologies for variable indentation - bit of a nightmare just getting it to this state!</p>
<pre><code>int indexOf(int a[], int val)
{ /* returns index at which val occurs in a[] */
int i=1;
while(a[i] != val)
i++;
return i;
}
int maxRow (int a[5][5], int index)
{
int store [5] = {-1, a[1][index], a[2][index], a[3][index], a[4][index] };
int store2[5] = {-1, a[1][index], a[2][index], a[3][index], a[4][index] };
int i, j, k, max, i1=0, i2=0, i3=0, i4=0;
int arr[5]={-1,-1,store2[2],store2[3],store2[4]};
if (index==5)
{
if(a[1][4]>=0)
return 1;
else if(a[2][4]>=0)
return 2;
else if(a[3][4]>=0)
return 3;
else if(a[4][4]>=0)
return 4;
}
/* order store[] from max -> min: */
for(i=1; i<=3; i++)
{
max=store[i];
j=i;
for(k=i+1; k<=4; k++)
if(store[k]>max)
{
max=store[k];
j=k;
}
store[j]=store[i];
store[i]=max;
}
i1 = indexOf(store2, store[1]);
/* now we must indicate which (if any ) rows to recurse on... */
if (store[1]==store[2])
{
if(i1==1)
i2 = indexOf(arr,store[1]);
else if (i1==2)
{
arr[2] = -1;
i2 = indexOf(arr, store[1]);
}
else if (i1==3)
i2 = 4;
/* note: if i2==4 then can't have store[1] equal to any other members of store[] */
if(store[1]==store[3])
{
/* i2 = 2 or 3 */
if(store2[4] <= store2[3])
i3 = 3;
else i3=4;
if (store[1]==store[4])
{
i4=4;
}
}
}
if (i2==0)
return i1;
else if(i3==0)
{
i = indexOf(store2,store[4]);
for(j=0;j<5;j++)
a[i][j]=-1;
i = indexOf(store2,store[3]);
for(j=0;j<5;j++)
a[i][j]=-1;
return maxRow(a, index+1);
}
else if (i4==0)
{
i = indexOf(store2,store[4]);
for(j=0;j<5;j++)
a[i][j]=-1;
return maxRow(a, index+1);
}
else /* all i are non-zero */
return maxRow(a, index+1);
}
</code></pre>
|
[] |
[
{
"body": "<p>You could use strcmp(char*, char*) to compare two strings. If you convert the matrix rows to the equivalent characters, then the strcmp() will do the hard work for you. </p>\n\n<pre><code>int isFirstGreater = strcmp(\"1234\", \"1232\");\n</code></pre>\n\n<p>This will return 1 to say that the first string is greater. In your context:</p>\n\n<pre><code>for(int i=0; i < MatrixSize; i++)\n{\n charArray[i] = (char*) matrixRow[i];\n}\ncharArray[MatrixSize] = 0; // You need to add a zero to make it a string. \nstrcmp(charArray, anotherCharArray); \n</code></pre>\n\n<p>However, this does seem like a bit of a crude hack. </p>\n\n<p>Maybe this is better:</p>\n\n<pre><code>int number = 0;\nfor(int i=0; i< matrixSize; i++)\n{\n number += matrixRow[i] * pow(10, (matrixSize-i)-1);\n}\n</code></pre>\n\n<p>That just converts the matrix row to a number, which you can just use >, < to see which is bigger, which is the equivalent to your original goal. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:12:10.350",
"Id": "3985",
"Score": "1",
"body": "this won't work if the matrix contains a number greater than 9."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:28:03.897",
"Id": "3986",
"Score": "0",
"body": "As it happens, 9 is the maximum number that this matrix will contain!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:35:32.480",
"Id": "3987",
"Score": "0",
"body": "It should work fine. I'll give a better example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:39:48.430",
"Id": "3988",
"Score": "0",
"body": "That's OK Mowgli - I think I can take it from here..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:49:48.863",
"Id": "3989",
"Score": "0",
"body": "It will work for numbers up to 255 (as a char is only a byte). I suggest you use the second method- convert to a number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T02:01:54.887",
"Id": "4083",
"Score": "0",
"body": "instead can use \n' number = number*<MAX_MATRIX_VALUE + 1> + matrixRow[i] '\nThis pattern is fairly common."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:08:05.247",
"Id": "2525",
"ParentId": "2523",
"Score": "1"
}
},
{
"body": "<p>A non-recursive solution could look like this (sorry, no C code, but an algorithm description instead):</p>\n\n<ul>\n<li><p>Keep a <code>bool</code> array <em><code>row_ruled_out[4]</code></em> with one item per row. This array will be used to keep track of which rows have already been \"ruled out\". Initially, all rows are still considered \"in\".</p></li>\n<li><p>For each column of your matrix, do the following:</p>\n\n<ol>\n<li><p>Find the maximum number <em>m</em> appearing in the column. For example, in the following matrix column:</p>\n\n<pre><code> . a . .\n . b . .\n . c . .\n . d . .\n</code></pre>\n\n<p><em>m</em> = max(<em>a</em>, <em>b</em>, <em>c</em>, <em>d</em>).</p></li>\n<li><p>For each row that hasn't yet been ruled out (according to <em><code>row_ruled_out</code></em>), if its value in that column is less than <em>m</em>, it cannot be the largest row. Therefore mark that row as \"ruled out\" in the <em><code>row_ruled_out</code></em> array. It won't be considered any further.</p></li>\n</ol></li>\n<li><p>After you've done the above for each column, look at <em><code>row_ruled_out</code></em>. All rows that are left, ie. haven't been ruled out, must be the largest rows. This could be zero, one, or several rows, depending on your input.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:40:54.903",
"Id": "3990",
"Score": "0",
"body": "A small correction: at step 1, you should only consider the columns of the rows that hasn't been ruled out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:47:59.113",
"Id": "3991",
"Score": "0",
"body": "This was a mistake I too made in an earlier version of the function..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:19:08.847",
"Id": "2526",
"ParentId": "2523",
"Score": "0"
}
},
{
"body": "<p>One way to do this is to simply compare two rows at a time and find which rows are the greatest seen so far:</p>\n\n<p>iterative version:</p>\n\n<pre><code>int maxrow(int *matrix, int width, int height) { \n int maxrowindex = 0; // first, assume the first row is the maxrow\n int r, c;\n for (r = 0; r < height; r++) {\n for (c = 0; c < width; c++) {\n if (matrix[maxrowindex*width+c] != matrix[r*width+c]) {\n if (matrix[maxrowindex*width+c] < matrix[r*width+c]) {\n maxrowindex = r;\n }\n break;\n }\n }\n }\n return maxrowindex;\n}\n</code></pre>\n\n<p>recursive version:</p>\n\n<pre><code>int lexicographic_compare(int a[], int b[], int width) {\n if (width == 1) return a[0] <= b[0];\n if (a[0] == b[0]) return lexicographic_compare(a+1, b+1, width-1);\n return a[0] <= b[0];\n} \nint maxrow(int *matrix, int width, int height) {\n if (height == 1) return 0;\n int a = 0;\n int b = maxrow(matrix + width, width, height-1) + 1;\n if (lexicographic_compare(matrix+a*width, matrix+b*width, width)) {\n return b;\n } else {\n return a;\n } \n} \n</code></pre>\n\n<p>this code should work for a matrix of arbitrary size.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T12:29:54.457",
"Id": "66512",
"Score": "0",
"body": "For the iterative `maxrow()`, you might as start with `for (r = 1; r < height; r++)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:58:17.103",
"Id": "2527",
"ParentId": "2523",
"Score": "3"
}
},
{
"body": "<p>The first thing I'd do if I were refactoring this code is get rid of recursion.</p>\n\n<p>You should be able to do it with a variable to keep track of \"best row number so far\", and a simple \"for each row\" loop. Inside the loop would be code that compares the current row with the best row so far (and does \"best row so far = current row\" if the current row is better).</p>\n\n<p>Example:</p>\n\n<pre><code>int maxRow(int a[4][4]) {\n int i,j;\n int bestRow = 0;\n\n for(i = 1; i < 4; i++) {\n for(j = 0; j < 4; j++) {\n if(a[i][j] != a[bestRow][j]) {\n if(a[i][j] > a[bestRow][j]) {\n bestRow = i;\n }\n break;\n }\n }\n }\n return bestRow;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T07:07:36.230",
"Id": "2529",
"ParentId": "2523",
"Score": "6"
}
},
{
"body": "<p>with tests.... just comparing every row.... </p>\n\n<pre><code>#include \"seatest.h\"\n\n\nint m1[4][4] = { \n {1,2,3,4},\n {2,3,4,1},\n {3,4,1,2},\n {4,1,2,3}};\n\n\nint m2[4][4] = { \n {1,2,3,4},\n {2,3,4,1},\n {4,4,1,2},\n {4,1,2,3}};\n\nint m3[4][4] = { \n {1,2,3,4},\n {2,3,4,1},\n {4,4,1,2},\n {4,4,2,3}};\n\nint m4[4][4] = { \n {1,2,3,4},\n {2,3,4,1},\n {4,4,1,2},\n {4,1,1,3}};\n\nint m5[4][4] = { \n {1,2,3,4},\n {2,3,4,1},\n {4,4,1,3},\n {4,1,1,3}};\n\n\nint compare(int* d1, int* d2, int l)\n{\n int i;\n for(i=0; i<l; i++) \n {\n if(d1[i] > d2[i]) return 1;\n if(d1[i] < d2[i]) return -1;\n }\n return 0;\n}\n\nint matrix_max_row_r(int* m, int w, int h)\n{\n int i; \n int max = 0;\n for(i=1; i<h; i++) max = compare(m+(w*i), m+(w*(i-1)), w) > 0 ? i : max;\n return max;\n}\n\n\n\nint matrix_max_row(int* m)\n{\n return matrix_max_row_r(m, 4,4);\n}\n\n\nvoid test_max_matrix_row()\n{ \n assert_int_equal(3, matrix_max_row((int*)m1));\n assert_int_equal(2, matrix_max_row((int*)m2));\n assert_int_equal(3, matrix_max_row((int*)m3));\n assert_int_equal(2, matrix_max_row((int*)m4));\n assert_int_equal(2, matrix_max_row((int*)m5));\n}\n\nvoid test_fixture_matrix( void )\n{\n test_fixture_start(); \n run_test(test_max_matrix_row); \n test_fixture_end(); \n}\n\nvoid all_tests( void )\n{\n test_fixture_matrix(); \n}\n\nint main( int argc, char** argv )\n{\n run_tests(all_tests); \n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T05:01:26.863",
"Id": "2567",
"ParentId": "2523",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T06:36:32.983",
"Id": "2523",
"Score": "5",
"Tags": [
"c",
"matrix"
],
"Title": "Finding the maximum row of a 4x4 matrix"
}
|
2523
|
<p>I just want to see if any part of one "rectangle" overlaps the other.
Is this the correct code?</p>
<pre><code> bool checkCollide(int x, int y, int oWidth, int oHeight, int x2, int y2, int o2Width, int o2Height){
bool collide;
collide = false;
if(x >= x2 && x <= x2+o2Width && y >= y2 && y <= y2+o2Height){
collide = true;
}
if(x+oWidth >= x2 && x+oWidth <= x2+o2Width && y >= y2 && y <= y2+o2Height){
collide = true;
}
if(x >= x2 && x<= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height){
collide = true;
}
if(x+oWidth >= x2 && x+oWidth <= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height){
collide = true;
}
return collide;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T15:42:22.710",
"Id": "4006",
"Score": "0",
"body": "Is it meant to work for x and y less than zero also?"
}
] |
[
{
"body": "<p>No, this is not correct; it only verifies whether the vertices of one rectangle are inside the other, not the other way around. Try calling it with the following parameters:</p>\n\n<pre><code>checkCollide(2,2,4,4, 1,3,2,2);\ncheckCollide(1,3,2,2, 2,2,4,4);\n</code></pre>\n\n<p>They should print the same result, but they don't. This case can be seen in the picture below.<img src=\"https://i.stack.imgur.com/zdjFf.png\" alt=\"enter image description here\"></p>\n\n<p>Update: even if you repeat the checks changing x/x2, y/y2, etc, this still won't catch all the cases: two rectangles may intersect even if none of their vertices are inside the other rectangle - see the other picture below.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CmRGH.png\" alt=\"enter image description here\"></p>\n\n<p>A more generic solution should use a segment intersection routine to check whether for all segments in one rectangle whether they intersect with any the segments on the other one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T22:43:41.567",
"Id": "2543",
"ParentId": "2533",
"Score": "8"
}
},
{
"body": "<p>Besides the correctness of the code, since this is a code review site I'd also point out that it can be rewritten to make it more readable. I'd say your code (which is incorrect, see my other answer), would be easier understood if you were explicit about the intent of each if statement (i.e., is the point inside a rectangle). Below is a version of the code which IMO is a lot more readable (and happens to be smaller).</p>\n\n<pre><code> bool isInside(int pointX, int pointY, int rectX, int rectY, int rectWidth, int rectHeight)\n {\n return\n (rectX <= pointX && pointX <= rectX + rectWidth) &&\n (rectY <= pointY && pointY <= rectY + rectHeight);\n }\n\n bool checkCollide(int x, int y, int oWidth, int oHeight, int x2, int y2, int o2Width, int o2Height)\n {\n bool collide =\n isInside(x, y, x2, y2, x2 + o2Width, y2 + o2Height) ||\n isInside(x + oWidth, y, x2, y2, x2 + o2Width, y2 + o2Height) ||\n isInside(x, y + oHeight, x2, y2, x2 + o2Width, y2 + o2Height) ||\n isInside(x + oWidth, y + oHeight, x2, y2, x2 + o2Width, y2 + o2Height);\n\n return collide;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T23:03:04.077",
"Id": "2544",
"ParentId": "2533",
"Score": "3"
}
},
{
"body": "<p>Firstly, I suggest the use of Rect structs/objects to hold rectangles rather then passing a whole bunch of parameters. </p>\n\n<p>Secondly, the algorithm is simpler then that.</p>\n\n<p>Imagine the problem in 1D. You want to know whether two lines collide:</p>\n\n<pre><code>----------------------------|\n |----------------------------\n</code></pre>\n\n<p>The lines collide if the second starts after the first begins, and the first begins after the second starts. </p>\n\n<p>To check for 2D collision just check for 1D collision in both x/y. If they both collide so do the rectangles.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T22:10:25.270",
"Id": "2560",
"ParentId": "2533",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T15:27:33.573",
"Id": "2533",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Does my Rectangle intersect code work?"
}
|
2533
|
<p>This is a plug-in which tracks your online activity aka a lifestream. You're currently able to use feeds like:</p>
<ul>
<li>Delicious</li>
<li>Flickr</li>
<li>Github</li>
<li>Google Reader</li>
<li>Last.fm</li>
<li>Stackoverflow</li>
<li>Twitter</li>
<li>Youtube</li>
</ul>
<p>At first I decided to load all the feeds at the end of all the asynchronous requests. This only required one DOM request at the end.</p>
<p>The problem with that approach is that it just takes too long to load. Some requests timed-out and others just took a while.</p>
<p>What I'm doing right now is changing the DOM after each feed request (e.g. twitter). At the moment this means 8 DOM changes.</p>
<p>What would be the best practice in this situation? Doing a setTimeout and accessing the dom after e.g. 400ms? Or would you leave it as it is now?</p>
<p>If you have any other remarks or suggestions, those would be appreciated as well.</p>
<pre class="lang-js prettyprint-override"><code>/**
* Initializes the lifestream plug-in
* @param {Object} config Configuration object
*/
$.fn.lifestream = function(config){
var outputElement = this;
// Extend the default settings with the values passed
var settings = jQuery.extend({
"classname": "lifestream",
"limit": 10
}, config),
data = {
"count": settings.list.length,
"items": []
};
var finished = function(inputdata){
$.merge(data.items, inputdata);
data.items.sort(function(a,b){
if(a.date > b.date){
return -1;
} else if(a.date === b.date){
return 0;
} else {
return 1;
}
});
var div = $('<ul class="' + settings.classname + '"/>');
var length = (data.items.length < settings.limit)
? data.items.length
: settings.limit
for(var i = 0, j=length; i<j; i++){
if(data.items[i].html){
div.append('<li class="'+ settings.classname + "-"
+ data.items[i].service + '">'
+ data.items[i].html + "</li>");
}
}
outputElement.html(div);
}
var load = function(){
// Run over all the items in the list
for(var i=0, j=settings.list.length; i<j; i++) {
var item = settings.list[i];
if($.fn.lifestream.feeds[item.service] &&
$.isFunction($.fn.lifestream.feeds[item.service])){
$.fn.lifestream.feeds[item.service](item, finished);
}
}
}
load();
};
</code></pre>
<p>Complete code:</p>
<ul>
<li><a href="https://github.com/christianv/jquery-lifestream/blob/master/jquery.lifestream.js">https://github.com/christianv/jquery-lifestream/blob/master/jquery.lifestream.js</a></li>
</ul>
<p>Documentation:</p>
<ul>
<li><a href="https://github.com/christianv/jquery-lifestream#readme">https://github.com/christianv/jquery-lifestream#readme</a></li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n <p>At first I decided to load all the feeds at the end of all the asynchronous requests. This only required one DOM request at the end. The problem with that approach is that it just takes too long to load. Some requests timed-out and others just took a while.</p>\n</blockquote>\n\n<p>It's unclear to me why the requests are timing out, but you could simply store the results of the responses in memory as opposed to what you might be doing; synchronization logic is not necessary, you only need to know when all requests ended. However, the downside of this approach is that time outs can make your application show nothing to your visitors, which is something you really don't want to do...</p>\n\n<blockquote>\n <p>What I'm doing right now is changing the DOM after each feed request (e.g. twitter). At the moment this means 8 DOM changes.</p>\n</blockquote>\n\n<p>It feels to me that 8 DOM changes are trivial to do by your browser; but the thing to do here is to actually figure out how many requests your code needs to be capable of handling.</p>\n\n<p>A bad option would be to update the DOM on each X-th response, because you are introducing the timed-out problem again. So, a better option is adding your responses to a queue and updating the DOM each X ms. That way you have the best of both worlds, and it doesn't matter how much feeds you'll be adding because it scales pretty well. There might probably be other problems at the high end, like updating too much DOM at once, but that's out of the question here...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T06:27:10.437",
"Id": "10427",
"ParentId": "2535",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T17:52:11.107",
"Id": "2535",
"Score": "7",
"Tags": [
"javascript",
"jquery",
"ajax",
"performance"
],
"Title": "jQuery Lifestream Plug-in"
}
|
2535
|
<p>I am a Java dev and trying to prepare for interviews in C++. Can someone please review the below solution for me?</p>
<blockquote>
<p>Assume that you are given the head and tail pointers of a doubly linked list where each node can also have a single child pointer to another similar doubly linked list. There are no cycles in this structure outside of the traditional double links. Write a procedure in C++ that flattens this structure into a single list.</p>
</blockquote>
<p>**I am ignoring that it is a doubly linked list for now to make the posted code more simple, since the "doubly" part doesn't seem to be of any help to me for this question.</p>
<pre><code>void LL::flatten(Node *head,Node *tail)
{
if(!head||!tail) return;
while(!head->down &&!(head==tail))
{
head = head->next;
}
// Flattening is complete
if(head==tail && !head->down) return;
tail->next = head->down;
head->down = null;
//getTail returns the last node of the linkedlist
flatten(head->next, getTail(tail->next));
}
class Node
{
public:
Node()
{
next = prev = down = null;
data = -1;
}
private:
Node * next;
Node * down;
Node * prev;
int data;
};
</code></pre>
<p>I have some questions:</p>
<ul>
<li>Is the "doubly" part required. What am I missing?</li>
<li>I have read it is better non-recursively. How is that? Since we have only pointers on the stack and the actual objects/list structure are on the heap, this should not take huge space on the stack, apart from usual recursion overheads.</li>
<li>Does someone have a non-recursive way of doing it in C++ or Java. The code on this forum is in C# and I am having trouble understanding it with enumerations and all the iterations</li>
<li>The <code>getTail(tail->next)</code> function is \$O(n)\$. Is there a way of not using this function ?. Even If I attach the 'down' linked list to the next node instead of last node, I will need the last node of the 'down' LL so that I can attach it to the next node of parent.</li>
</ul>
<p>Though I know there might be many solution already posted elsewhere, I am looking for review for my code as well, this will help me understand my gaps while coding in c++ (at least up to interview standards).</p>
|
[] |
[
{
"body": "<p>You could write this code in Java first, it would not be much different from a C++ implementation. It seems that your problem is not the language, but rather the algorithm: E.g. you only update the next pointer, not the prev pointer. The following must be true for every link between two nodes: node->next->prev == node.</p>\n\n<p>Let me try to answer your questions:</p>\n\n<ul>\n<li><p>The \"doubly\" part is not required to write something that can be flattened, but it is explicitly asked for so you must maintain it. It will allow you to traverse the list in two directions, instead of just one. This can be valuable in many situations.</p></li>\n<li><p>The question states that the child pointer is to a list similar to the first list. This means that it can also have child pointers of its own. A recursive solution would be easy to write and easy to understand.</p></li>\n<li><p>Why do you want a non-recursive algorithm? This is not stated in the question.</p></li>\n<li><p>I believe you can use any language you like in this forum. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T20:07:50.570",
"Id": "4013",
"Score": "0",
"body": "sommerlund .. Thnx for the reply !!. I made necessary changes in the question to reflect your concerns."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T19:30:01.603",
"Id": "2537",
"ParentId": "2536",
"Score": "4"
}
},
{
"body": "<pre><code>if(!head||!tail) return;\n</code></pre>\n\n<p>Should it really happen that head or tail can be null? Is it really right to ignore a situation head is null and tail isn't? I'm suspicious of what this test is doing.</p>\n\n<p>Don't do this:</p>\n\n<pre><code>while(!head->down &&!(head==tail))\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>while(!head->down && head != tail)\n</code></pre>\n\n<p>Less symbols makes its easier to read the code. </p>\n\n<p>As for the algorithm:</p>\n\n<p>In order to implement the iterative algorithm you need the doubly-linked lists. i.e. by ignoring those you've made yourself unable to find the non-recursive algorithm.</p>\n\n<p>Since you want to practice for an interview, I'm rot13ing the following hints, so you can use as much or as little as you want:</p>\n\n<ol>\n<li>Guvax guebhtu n cebprff bs jevgvat n shapgvba gung sbyybjf gur hasynggrarq punva jvgubhg synggravat vg. Gura nqq synggravat gb gung cebprff.</li>\n<li>Ng rnpu abqr lbh pna znxr bar bs guerr pubvprf: Zbir Arkg, Zbir Qbja, Zbir Onpx Hc.</li>\n<li>Jura lbh zbir qbja, gur cerivbhf cbvagre ba gur abqr jvyy or hahfrq. Frg gung cbvagre fb lbh pna pbzr onpx gb gur cerivbhf yriry.</li>\n<li>Zbivat hc vf gevpxl, ohg lbh fubhyq xabj gur gnvy naq urnq bs gur ybjre yvfg nf jryy nf gur abqr sebz juvpu lbh npprffrq gur ybjre yvfg. Pnershyyl zbir gubfr cbvagref nebhaq!</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T21:33:41.033",
"Id": "2551",
"ParentId": "2536",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T18:04:27.837",
"Id": "2536",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"linked-list",
"interview-questions"
],
"Title": "Flattening a doubly linked list"
}
|
2536
|
<p>Please suggest improvements in the following java program I've written for producer-consumer scenario. The program seems to be working fine. Does it suffer from possible deadlock scenarios? How better I could have done this? Since I am using Stack read/write (push/pop) already been synchronized? What if they do not?</p>
<pre><code>import java.util.Stack;
import logger.CustomLogger;
public class TestProducerConsumer {
private Stack<Integer> buffer;
public static final int MAX_SIZE = 10;
public int count;
public TestProducerConsumer(){
buffer = new Stack<Integer>();
count = 0;
}
public Stack<Integer> getBuffer(){
return buffer;
}
public void addToBuffer(Integer i) throws StackException{
if(buffer.size() < MAX_SIZE){
buffer.push(i);
CustomLogger.logger.info("pushed "+i);
}else
throw new StackException("Stack Over Flow");
}
public Integer removeFromBuffer() throws StackException{
if(buffer.size() == 0)
throw new StackException("Buffer Empty");
else
return buffer.pop();
}
public static void main(String[] args) {
TestProducerConsumer pd = new TestProducerConsumer();
Producer p1 = new Producer(pd);
Producer p2 = new Producer(pd);
Producer p3 = new Producer(pd);
Consumer c1 = new Consumer(pd);
Consumer c2 = new Consumer(pd);
Consumer c3 = new Consumer(pd);
Consumer c4 = new Consumer(pd);
Consumer c5 = new Consumer(pd);
Thread tp1 = new Thread(p1);
Thread tp2 = new Thread(p2);
Thread tp3 = new Thread(p3);
Thread tc1 = new Thread(c1);
Thread tc2 = new Thread(c2);
Thread tc3 = new Thread(c3);
Thread tc4 = new Thread(c4);
Thread tc5 = new Thread(c5);
tp1.start();
tc1.start();
tc2.start();
tc3.start();
tc4.start();
tc5.start();
tp2.start();
tp3.start();
}
}
class Producer implements Runnable{
private TestProducerConsumer pc;
public Producer(){
}
public Producer(TestProducerConsumer pc){
this.pc = pc;
}
public void run() {
Stack<Integer> buf = pc.getBuffer();
while(true){
synchronized(pc){
if(buf.size() < pc.MAX_SIZE){
try {
pc.addToBuffer(new Integer((pc.count)++));
if(buf.size() == 1){
CustomLogger.logger.info("Wake up consumer");
pc.notifyAll();
}
} catch (StackException e) {
CustomLogger.logger.info(e.getError());
break;
}
} else{
try {
CustomLogger.logger.info("Producer sleeping");
pc.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Consumer implements Runnable{
private TestProducerConsumer pc;
public Consumer(TestProducerConsumer pc){
this.pc = pc;
}
public void run(){
Stack<Integer> buf = pc.getBuffer();
int i;
while(true){
synchronized(pc){
if(buf.size() == 0){
try {
CustomLogger.logger.info("Consumer Sleeping");
pc.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else
{
try {
i = pc.removeFromBuffer();
CustomLogger.logger.info("poped "+i);
if(buf.size() == 0){
CustomLogger.logger.info("Wake up Producer");
pc.notifyAll();
}
} catch (StackException e) {
System.out.println(e.getError());
break;
}
}
}
}
}
}
class StackException extends Exception{
private String reason;
public StackException(){
super();
}
public StackException(String reason){
super(reason);
this.reason = reason;
}
public String getError(){
return reason;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T13:07:44.620",
"Id": "4007",
"Score": "4",
"body": "I wouldn't use a Stack for Producer/Consumer. I would just use a Queue or even better an ExecutorService."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T13:16:37.307",
"Id": "4008",
"Score": "2",
"body": "Let me discourage you from having a `getBuffer()` method which directly exposes the underlying data structure. If you want to control how the collection is modified through your own `addToBuffer` and `removeFromBuffer` methods, then you're completely sacrificing any guarantee of that by exposing `buffer` directly (allowing some outside code to call `getBuffer().push`)."
}
] |
[
{
"body": "<p>Your program is not thread-safe.</p>\n\n<p>For example, if two threads invoke <code>addToBuffer(Integer i)</code> at the <em>same</em> time, both can pass the <code>if(buffer.size() < MAX_SIZE)</code> check before one of them puts an item into the stack, therefore the stack can have more items than MAX_SIZE!</p>\n\n<p>The same is for <code>removeFromBuffer()</code>, and combinations of add and remove will have there own unexpected behaviour.</p>\n\n<hr>\n\n<p>In general instead of implementing it by your own have a look at the <a href=\"http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html\" rel=\"nofollow\"><code>java.util.concurrent</code></a> package</p>\n\n<blockquote>\n <p>Queues</p>\n \n <p>The java.util.concurrent ConcurrentLinkedQueue class supplies an efficient scalable thread-safe non-blocking FIFO queue. Five implementations in java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue. The different classes cover the most common usage contexts for producer-consumer, messaging, parallel tasking, and related concurrent designs. The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provides an implementation. </p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T13:09:51.870",
"Id": "2539",
"ParentId": "2538",
"Score": "3"
}
},
{
"body": "<p>You could try using a queue as they are designed for this sort of thing. The code is much shorter.</p>\n\n<pre><code>import java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic class TestProducerConsumer {\n public static final int MAX_SIZE = 10;\n private final BlockingQueue<Integer> tasks = new ArrayBlockingQueue<Integer>(MAX_SIZE);\n public final ExecutorService executor = Executors.newCachedThreadPool();\n public final AtomicInteger count = new AtomicInteger();\n\n public static final int POISON_VALUE = -1;\n\n public void addToBuffer(Integer i) {\n try {\n tasks.put(i);\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n }\n }\n\n public Integer removeFromBuffer() {\n try {\n return tasks.take();\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n }\n }\n\n public static void main(String... args) {\n TestProducerConsumer pd = new TestProducerConsumer();\n pd.new Producer();\n pd.new Producer();\n pd.new Producer();\n\n pd.new Consumer();\n pd.new Consumer();\n pd.new Consumer();\n pd.new Consumer();\n pd.new Consumer();\n }\n\n class Producer implements Runnable {\n public Producer() {\n executor.execute(this);\n }\n\n public void run() {\n while (count.get() >= 0) {\n addToBuffer(count.getAndIncrement());\n }\n addToBuffer(TestProducerConsumer.POISON_VALUE);\n }\n }\n\n class Consumer implements Runnable {\n public Consumer() {\n executor.execute(this);\n }\n\n public void run() {\n Integer num;\n while ((num = removeFromBuffer()) != TestProducerConsumer.POISON_VALUE) {\n System.out.println(\"popped \" + num);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T14:18:17.880",
"Id": "4009",
"Score": "0",
"body": "This implementation does not rise an exception if the queue is full, it blocks the request! (same for removeFromBuffer for an empty queue). -- I don't know if this is an improvement or not - any way it should be mentioned, that this implementation does not behave like the \"original\" one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T14:33:08.947",
"Id": "4010",
"Score": "0",
"body": "It uses a queue instead of a Stack so it processes work in the order it is created. That is a more important difference. The StackException would only be thrown when there is a thread safety issue which won't happen for a BlockingQueue."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T13:37:28.770",
"Id": "2540",
"ParentId": "2538",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T13:04:19.673",
"Id": "2538",
"Score": "5",
"Tags": [
"java"
],
"Title": "Producer Consumer scenario implementation in Java"
}
|
2538
|
<p>Consider the following two code examples:</p>
<p><strong>1.</strong></p>
<pre><code>void foo(boolean cake) {
if (!cake)
return;
// TODO some work.
}
</code></pre>
<p><br/></p>
<p><strong>2.</strong></p>
<pre><code>void bar(boolean cake) {
if (cake)
//TODO some work.
}
</code></pre>
<p>Which one is the most readable/ semantic correct? With the first example you avoid additional indentation on the below code.</p>
<p>Should one return right away when there is no cake or not?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-24T02:11:48.803",
"Id": "37462",
"Score": "0",
"body": "Related: http://stackoverflow.com/questions/4887212/shall-i-use-guard-clause-and-try-to-avoid-else-clause"
}
] |
[
{
"body": "<p>Usually you get the advice to avoid multiple exit points in a method. However the reasoning behind this rule is only valid if you have <strong>long</strong> methods - and then you have more to worry about than exit points.</p>\n\n<p>Make your methods <strong>short</strong>, then make them even <strong>shorter</strong>. After this you can use whatever exit style you want, because it will be readable either way.</p>\n\n<p>I came to this conclusion myself, but good books like <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\"><em>Clean Code</em></a> by Robert C. Martin will tell you the same.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T21:55:30.593",
"Id": "2542",
"ParentId": "2541",
"Score": "19"
}
},
{
"body": "<p>It depends on your intent. Your code should use idioms to match what its actually trying to do.</p>\n\n<pre><code>void foo(boolean cake) {\n if (!cake)\n return;\n\n // TODO some work.\n}\n</code></pre>\n\n<p>Indicates that <code>!cake</code> is a precondition and as such is insignificant to what the function is doing. </p>\n\n<pre><code>void bar(boolean cake) {\n if (cake)\n //TODO some work.\n}\n</code></pre>\n\n<p>Indicates that cake is an important part of what the function is doing. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T02:50:00.553",
"Id": "2565",
"ParentId": "2541",
"Score": "20"
}
},
{
"body": "<p>The first approach is what's called a guard. See <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">this article</a> by Jeff Atwood.</p>\n\n<blockquote>\n <p>Replace conditions with guard clauses. This code..</p>\n\n<pre><code>if (SomeNecessaryCondition) {\n // function body code\n}\n</code></pre>\n \n <p>.. works better as a guard clause:</p>\n\n<pre><code>if (!SomeNecessaryCondition)\n{\n throw new RequiredConditionMissingException;\n}\n// function body code\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-24T02:20:10.153",
"Id": "24294",
"ParentId": "2541",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "2542",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-21T21:37:10.963",
"Id": "2541",
"Score": "14",
"Tags": [
"java"
],
"Title": "Return explicitly or implicitly?"
}
|
2541
|
<p>I'm making a simple text game using the pdCurses library and a few other minor things like a vertical scroller in which you avoid the randomly-generated walls.</p>
<p>There are two walls on left and right made out of 'X' characters and blank, black space in which you can move around and avoid the 'X's your character is an '8' and your forced to continue forward or get touched by the X's each time a new line of the randomly generated "map" is revealed (for performance tests I'm making new lines show as fast as possible).</p>
<p>However, I am having performance issues and need new lines to be inserted and shown at least 3-5 times per second. Please suggest some simple ways of boosting performance.</p>
<pre><code>#include <iostream>
#include <time.h> // or "ctime"
#include <stdio.h> // for
#include <cstdlib>
// Windows stuff
#include <Windows.h> // GOD DAMMNIT WINDOWS WHY????
#include <conio.h>
// Ncurses
#include<curses.h>
// STL stuff
#include <algorithm>
#include <string>
#include <vector>
//String/Int conversion
#include <sstream>
// gives access to rand function
#include <cstdlib>
//gives access to time functions
#include <ctime>
// mySTOPWATCH i think i'm gonna cry.... =')
#include <myStopwatch.h> // for keeping times
#include <myMath.h> // numb_digits() and digit_val();
using namespace std;
enum{ NUMB_LINES= 24, SEC= 1000}; // time stuff
enum{TIME= 345, HEALTH = 346, MAP= 247}; // for Refresh() command
enum{NONE= 256}; // for Refresh() transition
enum{NEW = 590, OLD = 591}; // for the old/new screen command
// Some nCurses setup
int r = 0,
c = 0; // current row and column (upper-left is (0,0))
const int nrows = 56, // number of rows in window
ncols = 79; // number of columns in window
// Timer Setup
Stopwatch myStopwatch(3, START);
/////////////////////////// RandNumb() ///////////////////////////////////////
int RandNumb(int scope){
srand(GetTickCount());
return rand() % scope;};
////////////////////////// GeneratePathStart() ///////////////////////////////
void GeneratePathStart(vector<string>& buff){
int wall= RandNumb(80)/2,
space = (RandNumb(75)/2)+5,
wall2= 80- (wall+space);
buff.push_back("");
for(;wall> 0; wall--){
buff[0].push_back('X');}
for(;space> 0; space--){
buff[0].push_back(' ');}
for(; wall2 > 0; wall2--){
buff[0].push_back('X');}
};
////////////////////////// GeneratePath() ////////////////////////////////////
void GeneratePath( vector<string>& buff){// the buff is the seed too
int wall= RandNumb(80)/2,
space = (RandNumb(75)/2)+5,
wall2= 80-(space+wall);
int swall= 0;
for(char i= '0'; i!= ' ';swall++)
i= buff[buff.size()-1][swall+1];
int sspace= 0; int I= swall+1;
for(char i= '0'; i!= 'X';sspace++, I++)
i= buff[buff.size()-1][I];
int swall2 = 80-(sspace+swall);
// now the actual generation
int cwall= wall-swall;
int cspace= space-sspace;
int cwall2= wall2-swall2;
for(;cwall!= 0 || cspace!= 0 /*|| cwall2 != 0*/;){
buff.push_back("");
//cwall
if(cwall!= 0){
if(cwall>0){
swall++;
cwall--;}
else{ // cwall is negative
swall--;
cwall++;}}
for(int w= 0; w <swall; w++)
buff[buff.size()-1].push_back('X');
// cspace
if(cspace!= 0){
if(cspace>0){
sspace++;
cspace--;}
else{ // cspace is negative
sspace--;
cspace++;}}
for(int s= 0; s <sspace; s++)
buff[buff.size()-1].push_back(' ');
// cwall2
//if(cwall2!= 0){
// if(cwall2>0){
// wall2++;
// cwall2--;}
// else{ // cspace is negative
// wall2--;
// cwall2++;}}
for(int w2= 0; w2 <80- (swall+sspace); w2++)
buff[buff.size()-1].push_back('X');
}}// end of function
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// Sprite Class ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Sprite
{
private:
string name;
char symbol;
float health;
int location[2];
public:
///////////////////// Get and SET all the privates ///////
Sprite(){};
Sprite(string a_name, char a_symbol, float a_health){
name = a_name;
symbol = a_symbol;
health = a_health;};
char get_symbol() {return symbol;};
void set_symbol(char sym) {symbol = sym;};
float get_health() {return health;};
void set_health(float numb) {health = numb;};
void add_health (float numb) {health += numb;};
string get_name() {return name;};
string set_name(string aName) {name = aName;};
int* get_location(){return location;};
void set_location(int X, int Y) {
location[0] = X;
location[1] = Y;};
//////////////////////////////// Move ////////////
bool move(int X, int Y) {
location[0] += X;
location[1] += Y;
return true;};
};// end of sprite
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////// Player Class ///////////////////////////////////////////////////////////////////////////////////////////////////////////
class Player : public Sprite
{
public:
Player(string name,int X, int Y, float health){
set_symbol('8');
set_name(name);
set_location(X,Y);
set_health(100);};
private:
// none?
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// Map class ///////////////////////////////////////////////////////////////////////////////////////////////////
class Map
{
private:
/////////////////////////////////////////// Map Variables ///////////////
string name;
vector <string> contents;
vector <string> save;
public:
Map(){};
Map(string* lines, int i, string name= "map"){name = name;
contents.resize(56);
Insert(lines, i);};
~Map(){};
/////////////////////////////////////////// generate ////////////////////
void generate(){GeneratePath(contents);};
/////////////////////////////////////////// Return() ////////////////////
string Name() {return name;};
vector <string> Contents() {return contents;};
string Contents(int Y) {return contents[Y];};
char Contents(int Y, int X) {return contents[Y][X];};
vector <string> Save() {return save;};
int size() {return contents.size();};
/////////////////////////////////////////// Insert() ////////////////////
// string* to an array of 24 strings;
void Insert(string* lines, int i)
{contents.assign(lines, lines+i);}; //insert lines 1-24
void Insert(string astring, int Y) {contents[Y] = astring;};
void Insert(char achar, int X, int Y){contents[Y][X] = achar;};
void Saveline(string line) {save.push_back(line);};
};
///////////////////////// SCREEN CLASS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Screen
{
private:
/////////////////////////////////////////// Screen Variables ///////////////
string _name;
vector <string> new_map;
vector <string> old_map;
vector <Sprite*> sprites_p;
public:
Screen(string name){_name = name;
new_map.resize(nrows);
old_map.resize(nrows);};
~Screen(){};
//////////////////////////////////////////// Get contents ///////////////////////////
vector <string> get_contents(int comm= NEW) {switch(comm){ case NEW: return new_map; break;
case OLD: return old_map; break;}};
string get_contents (int Y, int comm= NEW) {switch(comm){ case NEW: return new_map[Y]; break;
case OLD: return old_map[Y]; break;}};
char get_contents (int X, int Y, int comm= NEW){switch(comm){ case NEW: return new_map[Y][X]; break;
case OLD: return old_map[Y][X]; break;}};
//////////////////////////////////////////// Refresh ///////////////////////////
void Refresh(int command= ALL, int transition= NONE)
{
//old_map = new_map; // update the old map
for(int r= 0; r< nrows; r++){ move(r,0);
addstr((char*)new_map[r].c_str());} // make sure this works later
// Insert Time
if(command== ALL || command== TIME){
enum{ time_loc_y= 22,
time_loc_x= 38 };
mvaddstr(time_loc_y, time_loc_x, myStopwatch.ClockTime().c_str());}
refresh();}; // end of function
/////////////////////////////////////////// Insert ////////////////////////
/////////////////// Map
void Insert(Map& map, int y1, int y2) {for ( int mc = y1, nm= 0; mc< map.size() && mc< y2; mc++, nm++){
new_map[nm] = map.Contents(mc);}
};
/////////////////// string
void Insert(string astring, int Y) {new_map[Y] = astring;};
///////////////////// char
void Insert(char achar, int X, int Y) {new_map[Y][X] = achar;};
//////////////////// sprite
void Insert(Sprite& sprite) {new_map[sprite.get_location()[1]][sprite.get_location()[0]] = sprite.get_symbol();
sprites_p.push_back(&sprite);}; // save a pointer to the sprite
/////////////////////////////////////////// Collision Detection ///////////
bool check_collision(Sprite& sprite,int X, int Y, char& buff)
{
////////////////////// check whats already there /////
char newloc = new_map[sprite.get_location()[1]+Y]
[sprite.get_location()[0]+X];
if(newloc == '|' || newloc == '/' || newloc == '_' || newloc == '=' || newloc == 'X' || newloc == '-' || newloc == 'x' ) {buff = newloc; return true;}
else return false;
};
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// MAIN //////////////////////////////////// MAIN ////////////////////////////////////////////////////////////////////////
int main()
{
cout << "make the screen fullscreen!!";
char response; cin >> response;
WINDOW *wnd;
wnd = initscr(); // curses call to initialize window and curses mode
//cbreak(); // curses call to set no waiting for Enter key
noecho(); // curses call to set no echoing
//curs_set(a number); (0 = invisible, 1 = normal, 2 = very visible)
int row,col; getmaxyx(stdscr,row,col); /* get the number of rows and columns */
clear(); // curses call to clear screen, send cursor to position (0,0)
Screen theScreen("ascreen");
string splashScreen[24] = { // HERE"S THE SPLASH !
// 1 2 3 4 5 6 7 8
// 123456789 123456789 123456789 123456789
// 0123456789 123456789 123456789 123456789 1234567
/* 0 */ "________________________________________________________________________________",
/* 1 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 2 */ "|XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 3 */ "|XXXXXX / XXXXXXXXXXXXXXXXXXXXX xXXXXXXXXXX XXXXXXXXXXXx xXXXXXXx xXXX|",
/* 4 */ "|XXXXX /0} XXXXXXXXXXXXXXXXX /XXXXx XXXXXXx /X xXXXXXXXXX XXXXXX XXX|",
/* 5 */ "|XXXX /000} XXXXXXXXXXXXXX /XXXXXXXx XXXXX /X XXXXXXXX /X XXXX /X XX|",
/* 6 */ "|XXX XXXXXXXXXXXX /XXXXXXXXxx XXXX /XXX XXXXXXX /XX XXXX |X XX|",
/* 7 */ "|XX /XXXXXX XXXXXXXXXX /XXXXXXXXXXXXXXXX /XXX XXXXXX |XXX XX /X xX|",
/* 8 */ "|X /XXXXXXXX X*X*X*XXX /XXXXx xXX XXXXX |XXX /XXX X|",
/* 9 */ "|XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX XX /XXXXX XXXX |XXXX /XXXX X|",
/* 10 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX Xx /XXXXXXX xXXX |XXXXx /XXXX X|",
/* 11*/ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXx /XXXXXXX xXX XXXXXxxXXXX x|",
/* 12 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 13 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxxxxxxxxxxxxxxxXXXX|",
/* 14 */ "|XXX XXxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX|",
/* 15 */ "|XXX XXXx XX/ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX_____XX XXXXXXXXXXXXXXXX|",
/* 16 */ "|XXX XXX / XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX|",
/* 17 */ "|XXX /0] XX/ XXXXx xXX XXXXXXXXXXX xXXX xXXXX xXXX|",
/* 18 */ "|XXX XX/ XXXXX XXXXXXXX xXXX XXX XXXXXX XXXXXXX xXXX|",
/* 19 */ "|XXXXXXXX XXXXXXX XXx xXX XXXXXX XXX xXXX xXXXX XXXXXXXXXXXXXXXX|",
/* 20 */ "|XXXXXXXXXXXXXXXXX XXXX XX XXXXXX XXX XXXXXX XXXXXXX XXXXXXXXXXXXXXXX|",
/* 21 */ "|XXXXXXXXXXXXXXXXXx xXXxxXXXXXXxxXXX xXXXXXX xXXXXXXX XXX|",
/* 22 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxxxxxxxxxxxxxxxxxXXX|",
/* 23 */ "|______________________________________________________________________________|",};
string _lines_[56] = {
// 1 2 3 4 5 6 7 8
// 123456789 123456789 123456789 123456789
// 0123456789 123456789 123456789 123456789 1234567
/* 0 */ "________________________________________________________________________________",
/* 1 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 2 */ "|XXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXX|",
/* 3 */ "|XXXXX XXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXX XXXXXXXX|",
/* 4 */ "|XXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXX XXXXXXXX|",
/* 5 */ "|XXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXX XXXXXXXX|",
/* 6 */ "|XX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|",
/* 7 */ "|XX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|",
/* 8 */ "|XXX XXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX|",
/* 9 */ "|XXXX XXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX|",
/* 10 */ "|XXXXX XXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX|",
/* 11 */ "|XXXXXXX XXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|",
/* 12 */ "|XXXXXXXX XXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|",
/* 13 */ "|XXXXXXXXXX XXXXX XXXXXXX XXXXXXXXXXXXXXX XXXXXXXX___XXXXXXXX|",
/* 14 */ "|XXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXxxxXXXXXXXX|",
/* 15 */ "|XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXX XXXXXXXXXXx xXXXXXXX|",
/* 16 */ "|XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXx xXXXXXXX|",
/* 17 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 18 */ "|______________________________________________________________________________|",
/* 19 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 20 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 21 */ "|XXX XXX|",
/* 22 */ "|XXX XXX|",
/* 23 */ "|XXX XXX|",
/* 0 */ "|XXX XXX|",
/* 1 */ "|XXX XXX|",
/* 2 */ "|XXX XXX|",
/* 3 */ "|XXX XXX|",
/* 4 */ "|XXX XXX|",
/* 5 */ "|XXX XXX|",
/* 6 */ "|XXX XXX|",
/* 7 */ "|XXX XXX|",
/* 8 */ "|XXX XXX|",
/* 9 */ "|XXXX XXXX|",
/* 10 */ "|XXXXX XXXXX|",
/* 11*/ "|XXXXXX XXXXXX|",
/* 12 */ "|XXXXXXX XXXXXXX|",
/* 13 */ "|XXXXXXXX XXXXXXXX|",
/* 14 */ "|XXXXXXXXX XXXXXXXXX|",
/* 15 */ "|XXXXXXXXXX XXXXXXXXXX|",
/* 16 */ "|XXXXXXXXXXX XXXXXXXXXXX|",
/* 17 */ "|XXXXXXXXXXX XXXXXXXXXXX|",
/* 18 */ "|XXXXXXXXXXXX XXXXXXXXXXXX|",
/* 19 */ "|XXXXXXXXXXXX XXXXXXXXXXXX|",
/* 20 */ "|XXXXXXXXXXXXX XXXXXXXXXXXXX|",
/* 21 */ "|XXXXXXXXXXXXX XXXXXXXXXXXXX|",
/* 22 */ "|XXXXXXXXXXXXXX XXXXXXXXXXXXXX|",
/* 23 */ "|XXXXXXXXXXXXXX XXXXXXXXXXXXXX|"
/* 24 */ "|XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX|",
/* 25 */ "|XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX|",
/* 26 */ "|XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX|",
/* 27 */ "|XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX|",
/* 28 */ "|XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX|",
/* 29 */ "|XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX|",
/* 30 */ "|XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 31*/ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 32 */ "|XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
};
////////////////////////////////// Splash Screen /////////////////////////////
Map splashScreen_map(splashScreen, 24);
theScreen.Insert(splashScreen_map, 0, nrows);
theScreen.Refresh(MAP);
myStopwatch.Wait(3);
myStopwatch.Restart();
/////////////////////////////////////////////////////////////////////////////////
Map L1(_lines_, nrows, "L1");
theScreen.Insert(L1, 0, nrows);
Sprite player("Player",'8',100); //(8, 12, 16);
player.set_location(24, 48);
////////////////////// Check if new line is needed;
double refreshes= 0;
double newSpeed= 10;
for (bool quit = false; quit != true;)
{ double newTime= myStopwatch.ElapsedTime()- refreshes;
if(newTime*newSpeed >= 1){
theScreen.Insert(L1, 0+refreshes, nrows+refreshes);
refreshes++;
if(L1.size()<= nrows+refreshes+2)
L1.generate();}
///////////////// Keypress ///////////
if (kbhit()){
int key = getch();
key = toupper(key); // makes whatever key uppercase
int xMove = 0;
int yMove = 0;
int stepSize = 1;
bool validPress = true;
switch(key){
// update health here............
case 'W': yMove = -stepSize;break;
case 'S': yMove = stepSize; break;
case 'A': xMove = -stepSize;break;
case 'D': xMove = stepSize; break;
case'P': getch(); break;
case'O': quit = true;
default: validPress = false;}
if(validPress == true){
char coll; // if there's no collision
if(theScreen.check_collision(player, xMove, yMove, coll) != true){
// get rid of old player placing
theScreen.Insert(' ', player.get_location()[0],player.get_location()[1]);
// put in new charater placing
player.move(xMove, yMove);
theScreen.Insert(player);
theScreen.Refresh();}
else{
theScreen.Refresh();}};
// do other stuff with 'coll';
} /* end of if(kbhit())*/
theScreen.Refresh();}// so refresh and restart the for loop
endwin(); // curses call to restore the original window and leave
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>#include <iostream>\n#include <time.h> // or \"ctime\"\n#include <stdio.h> // for \n</code></pre>\n\n<p>Its best to avoid useless noise comments which contribute nothing</p>\n\n<pre><code>#include <cstdlib> \n// Windows stuff\n#include <Windows.h> // GOD DAMMNIT WINDOWS WHY????\n</code></pre>\n\n<p>As fun as complaining about Windows is, it is distracting to have comments like this. Have your comments tell me about what is going on, not your complaints about Microsoft.</p>\n\n<pre><code>#include <conio.h>\n// Ncurses\n#include<curses.h>\n// STL stuff\n#include <algorithm>\n#include <string>\n#include <vector>\n//String/Int conversion\n#include <sstream>\n// gives access to rand function\n#include <cstdlib>\n//gives access to time functions\n#include <ctime>\n\n// mySTOPWATCH i think i'm gonna cry.... =')\n</code></pre>\n\n<p>Again, not a substantive comment</p>\n\n<pre><code>#include <myStopwatch.h> // for keeping times\n#include <myMath.h> // numb_digits() and digit_val();\nusing namespace std;\nenum{ NUMB_LINES= 24, SEC= 1000}; // time stuff\nenum{TIME= 345, HEALTH = 346, MAP= 247}; // for Refresh() command\nenum{NONE= 256}; // for Refresh() transition\nenum{NEW = 590, OLD = 591}; // for the old/new screen command\n\n// Some nCurses setup\n int r = 0,\n c = 0; // current row and column (upper-left is (0,0))\n</code></pre>\n\n<p>If you want to split the assignment onto two lines, just make it two statements. Also I suggest using row and column or x,y because r/c aren't quite common enough that its obvious what they mean.</p>\n\n<pre><code> const int nrows = 56, // number of rows in window\n ncols = 79; // number of columns in window\n// Timer Setup\n Stopwatch myStopwatch(3, START);\n\n\n /////////////////////////// RandNumb() ///////////////////////////////////////\nint RandNumb(int scope){\n srand(GetTickCount());\n return rand() % scope;};\n</code></pre>\n\n<p>Many commonly used formatting rules exist. I'm not aware of any which put the } on the same line as the final statement. Also, srand should be called exactly once at the start of your program not every time you want a random number. There is also no need for the final semicolon.</p>\n\n<pre><code>////////////////////////// GeneratePathStart() ///////////////////////////////\n</code></pre>\n\n<p>Some people do comments like this. I think they are silly because if I wanted to know the function's name I'd have read the function's name in the code.</p>\n\n<pre><code>void GeneratePathStart(vector<string>& buff){\n int wall= RandNumb(80)/2, \n</code></pre>\n\n<p>Ok, why don't you use RandNumb(40)?</p>\n\n<pre><code> space = (RandNumb(75)/2)+5,\n wall2= 80- (wall+space);\n</code></pre>\n\n<p>I'm really not a fan of multiple assignments like this. it makes me hunt to try and figure out they are ints. Also, its best to adopt a consistent spacing regimine. I recommond putting spaces around all binary operators.</p>\n\n<pre><code> buff.push_back(\"\");\n for(;wall> 0; wall--){\n buff[0].push_back('X');}\n</code></pre>\n\n<p>Counting down is unusual. You don't have any reason to do it here, so I recommend counting up. Otherwise its just seems odd. odd is bad.</p>\n\n<pre><code> for(;space> 0; space--){\n buff[0].push_back(' ');}\n for(; wall2 > 0; wall2--){\n buff[0].push_back('X');}\n };\n\n////////////////////////// GeneratePath() ////////////////////////////////////\nvoid GeneratePath( vector<string>& buff){// the buff is the seed too\n int wall= RandNumb(80)/2, \n space = (RandNumb(75)/2)+5,\n wall2= 80-(space+wall);\n int swall= 0;\n for(char i= '0'; i!= ' ';swall++)\n i= buff[buff.size()-1][swall+1];\n</code></pre>\n\n<p>Its really really important that you put all statements in the same block as the same level as each other. Otherwise you WILL introduce bugs.</p>\n\n<pre><code> int sspace= 0; int I= swall+1;\n</code></pre>\n\n<p>This I is a really bad variable name because it provides no hints as to what it does.</p>\n\n<pre><code> for(char i= '0'; i!= 'X';sspace++, I++)\n i= buff[buff.size()-1][I];\n</code></pre>\n\n<p>For loops are best for simple iterations. Here you're doing a bunch of crazy stuff which makes it hard to follow what the loop is doing. A while loop can do this cleaner.</p>\n\n<pre><code> int swall2 = 80-(sspace+swall);\n</code></pre>\n\n<p>Variable names like swall2 suggest you were too lazy to come up with a better variable name. Come up with a more descriptive one.</p>\n\n<pre><code> // now the actual generation\n int cwall= wall-swall; \n int cspace= space-sspace; \n int cwall2= wall2-swall2;\n for(;cwall!= 0 || cspace!= 0 /*|| cwall2 != 0*/;){\n buff.push_back(\"\");\n//cwall\n</code></pre>\n\n<p>Comments are not for pieces of old code. They are for explanation. Right about now I have no idea what this piece of code is doing. Some comments explaining your algorithm or at least some meaningful variable names would be good.</p>\n\n<pre><code> if(cwall!= 0){\n if(cwall>0){\n swall++;\n cwall--;}\n else{ // cwall is negative\n swall--;\n cwall++;}}\n for(int w= 0; w <swall; w++)\n buff[buff.size()-1].push_back('X');\n// cspace\n if(cspace!= 0){\n if(cspace>0){\n sspace++;\n cspace--;}\n else{ // cspace is negative\n sspace--;\n cspace++;}}\n for(int s= 0; s <sspace; s++)\n buff[buff.size()-1].push_back(' ');\n// cwall2\n //if(cwall2!= 0){ \n // if(cwall2>0){\n // wall2++;\n // cwall2--;}\n // else{ // cspace is negative\n // wall2--;\n // cwall2++;}}\n for(int w2= 0; w2 <80- (swall+sspace); w2++)\n buff[buff.size()-1].push_back('X');\n }}// end of function\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////// Sprite Class ///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n</code></pre>\n\n<p>Seriously... do you think all those / help?</p>\n\n<pre><code>class Sprite\n{\n\nprivate:\n string name;\n char symbol;\n float health;\n int location[2];\n\npublic:\n///////////////////// Get and SET all the privates ///////\n Sprite(){};\n Sprite(string a_name, char a_symbol, float a_health){\n name = a_name;\n symbol = a_symbol;\n health = a_health;};\n\n char get_symbol() {return symbol;};\n void set_symbol(char sym) {symbol = sym;};\n\n float get_health() {return health;};\n void set_health(float numb) {health = numb;};\n void add_health (float numb) {health += numb;};\n\n string get_name() {return name;};\n string set_name(string aName) {name = aName;};\n\n int* get_location(){return location;};\n void set_location(int X, int Y) {\n location[0] = X;\n location[1] = Y;};\n</code></pre>\n\n<p>Getters and setters are bad. But you probably haven't been coding long enough to worry about that. But seriously, unless someone is making you I suggest directly access the data for now. Don't worry about encapsulation until you've got the complete hang of things. (I'd probably get in trouble for saying that, but nobody is going to read this far)</p>\n\n<pre><code>//////////////////////////////// Move ////////////\n bool move(int X, int Y) {\n location[0] += X;\n location[1] += Y;\n return true;};\n</code></pre>\n\n<p>A function like this is good because it provides a higher level interface, not requiring external objects to deal with getters/setters.</p>\n\n<pre><code>};// end of sprite\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n///////////////////////////////// Player Class ///////////////////////////////////////////////////////////////////////////////////////////////////////////\nclass Player : public Sprite\n{\npublic:\n Player(string name,int X, int Y, float health){\n set_symbol('8');\n set_name(name);\n set_location(X,Y);\n set_health(100);};\nprivate:\n // none?\n\n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////// Map class ///////////////////////////////////////////////////////////////////////////////////////////////////\nclass Map\n{\nprivate:\n/////////////////////////////////////////// Map Variables ///////////////\n</code></pre>\n\n<p>Again useless comment noise. Assume the reader knows the language.</p>\n\n<pre><code> string name;\n vector <string> contents;\n vector <string> save;\n</code></pre>\n\n<p>I suggest not using string to hold a map. A map isn't text. Better to use enums.</p>\n\n<pre><code>public:\n Map(){};\n Map(string* lines, int i, string name= \"map\"){name = name;\n contents.resize(56);\n Insert(lines, i);};\n ~Map(){};\n\n/////////////////////////////////////////// generate ////////////////////\n void generate(){GeneratePath(contents);};\n/////////////////////////////////////////// Return() ////////////////////\n string Name() {return name;};\n vector <string> Contents() {return contents;};\n string Contents(int Y) {return contents[Y];};\n char Contents(int Y, int X) {return contents[Y][X];};\n vector <string> Save() {return save;};\n int size() {return contents.size();};\n\n/////////////////////////////////////////// Insert() ////////////////////\n // string* to an array of 24 strings;\n void Insert(string* lines, int i) \n {contents.assign(lines, lines+i);}; //insert lines 1-24\n\n void Insert(string astring, int Y) {contents[Y] = astring;};\n\n void Insert(char achar, int X, int Y){contents[Y][X] = achar;};\n\n void Saveline(string line) {save.push_back(line);}; \n};\n\n///////////////////////// SCREEN CLASS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nclass Screen\n{\nprivate:\n/////////////////////////////////////////// Screen Variables ///////////////\n string _name;\n vector <string> new_map;\n vector <string> old_map;\n</code></pre>\n\n<p>Its odd that you have a Map class but hold everything with strings here.</p>\n\n<pre><code> vector <Sprite*> sprites_p;\n\npublic:\n Screen(string name){_name = name;\n new_map.resize(nrows);\n old_map.resize(nrows);};\n ~Screen(){};\n\n//////////////////////////////////////////// Get contents ///////////////////////////\n vector <string> get_contents(int comm= NEW) {switch(comm){ case NEW: return new_map; break;\n case OLD: return old_map; break;}};\n string get_contents (int Y, int comm= NEW) {switch(comm){ case NEW: return new_map[Y]; break;\n case OLD: return old_map[Y]; break;}};\n char get_contents (int X, int Y, int comm= NEW){switch(comm){ case NEW: return new_map[Y][X]; break;\n case OLD: return old_map[Y][X]; break;}};\n\n//////////////////////////////////////////// Refresh ///////////////////////////\nvoid Refresh(int command= ALL, int transition= NONE)\n{\n //old_map = new_map; // update the old map\n for(int r= 0; r< nrows; r++){ move(r,0); \n</code></pre>\n\n<p>Please don't put more then the for loop on that line. Its makes it hard to follow.</p>\n\n<pre><code> addstr((char*)new_map[r].c_str());} // make sure this works later\n // Insert Time \n if(command== ALL || command== TIME){\n enum{ time_loc_y= 22, \n time_loc_x= 38 };\n mvaddstr(time_loc_y, time_loc_x, myStopwatch.ClockTime().c_str());}\n\nrefresh();}; // end of function\n\n/////////////////////////////////////////// Insert ////////////////////////\n /////////////////// Map\n void Insert(Map& map, int y1, int y2) {for ( int mc = y1, nm= 0; mc< map.size() && mc< y2; mc++, nm++){\n new_map[nm] = map.Contents(mc);}\n };\n /////////////////// string\n void Insert(string astring, int Y) {new_map[Y] = astring;};\n ///////////////////// char\n void Insert(char achar, int X, int Y) {new_map[Y][X] = achar;};\n //////////////////// sprite\n void Insert(Sprite& sprite) {new_map[sprite.get_location()[1]][sprite.get_location()[0]] = sprite.get_symbol();\n sprites_p.push_back(&sprite);}; // save a pointer to the sprite\n\n/////////////////////////////////////////// Collision Detection ///////////\n bool check_collision(Sprite& sprite,int X, int Y, char& buff) \n {\n ////////////////////// check whats already there /////\n char newloc = new_map[sprite.get_location()[1]+Y]\n [sprite.get_location()[0]+X];\n if(newloc == '|' || newloc == '/' || newloc == '_' || newloc == '=' || newloc == 'X' || newloc == '-' || newloc == 'x' ) {buff = newloc; return true;}\n</code></pre>\n\n<p>Here is where using enums would help. The code would make it clear what its saying. Right now we just have a bunch of crazy symbols.</p>\n\n<pre><code> else return false;\n };\n};\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n///////////////////////// MAIN //////////////////////////////////// MAIN ////////////////////////////////////////////////////////////////////////\n</code></pre>\n\n<p>Hmm... doubly main.</p>\n\n<pre><code>int main()\n{\ncout << \"make the screen fullscreen!!\";\nchar response; cin >> response;\n</code></pre>\n\n<p>Don't put multiple statements on the same line, there isn't any reason and it odd.</p>\n\n<pre><code> WINDOW *wnd;\n wnd = initscr(); // curses call to initialize window and curses mode\n //cbreak(); // curses call to set no waiting for Enter key\n noecho(); // curses call to set no echoing\n //curs_set(a number); (0 = invisible, 1 = normal, 2 = very visible)\n int row,col; getmaxyx(stdscr,row,col); /* get the number of rows and columns */\n clear(); // curses call to clear screen, send cursor to position (0,0)\n\n Screen theScreen(\"ascreen\");\n\n string splashScreen[24] = { // HERE\"S THE SPLASH !\n// 1 2 3 4 5 6 7 8 \n// 123456789 123456789 123456789 123456789\n// 0123456789 123456789 123456789 123456789 1234567\n/* 0 */ \"________________________________________________________________________________\", \n/* 1 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 2 */ \"|XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 3 */ \"|XXXXXX / XXXXXXXXXXXXXXXXXXXXX xXXXXXXXXXX XXXXXXXXXXXx xXXXXXXx xXXX|\", \n/* 4 */ \"|XXXXX /0} XXXXXXXXXXXXXXXXX /XXXXx XXXXXXx /X xXXXXXXXXX XXXXXX XXX|\", \n/* 5 */ \"|XXXX /000} XXXXXXXXXXXXXX /XXXXXXXx XXXXX /X XXXXXXXX /X XXXX /X XX|\", \n/* 6 */ \"|XXX XXXXXXXXXXXX /XXXXXXXXxx XXXX /XXX XXXXXXX /XX XXXX |X XX|\", \n/* 7 */ \"|XX /XXXXXX XXXXXXXXXX /XXXXXXXXXXXXXXXX /XXX XXXXXX |XXX XX /X xX|\", \n/* 8 */ \"|X /XXXXXXXX X*X*X*XXX /XXXXx xXX XXXXX |XXX /XXX X|\", \n/* 9 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX XX /XXXXX XXXX |XXXX /XXXX X|\", \n/* 10 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX Xx /XXXXXXX xXXX |XXXXx /XXXX X|\", \n/* 11*/ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXx /XXXXXXX xXX XXXXXxxXXXX x|\", \n/* 12 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 13 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxxxxxxxxxxxxxxxXXXX|\", \n/* 14 */ \"|XXX XXxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX|\", \n/* 15 */ \"|XXX XXXx XX/ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX_____XX XXXXXXXXXXXXXXXX|\", \n/* 16 */ \"|XXX XXX / XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX|\", \n/* 17 */ \"|XXX /0] XX/ XXXXx xXX XXXXXXXXXXX xXXX xXXXX xXXX|\", \n/* 18 */ \"|XXX XX/ XXXXX XXXXXXXX xXXX XXX XXXXXX XXXXXXX xXXX|\", \n/* 19 */ \"|XXXXXXXX XXXXXXX XXx xXX XXXXXX XXX xXXX xXXXX XXXXXXXXXXXXXXXX|\", \n/* 20 */ \"|XXXXXXXXXXXXXXXXX XXXX XX XXXXXX XXX XXXXXX XXXXXXX XXXXXXXXXXXXXXXX|\", \n/* 21 */ \"|XXXXXXXXXXXXXXXXXx xXXxxXXXXXXxxXXX xXXXXXX xXXXXXXX XXX|\", \n/* 22 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxxxxxxxxxxxxxxxxxXXX|\", \n/* 23 */ \"|______________________________________________________________________________|\",};\n\n string _lines_[56] = { \n// 1 2 3 4 5 6 7 8 \n// 123456789 123456789 123456789 123456789\n// 0123456789 123456789 123456789 123456789 1234567\n/* 0 */ \"________________________________________________________________________________\", \n/* 1 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 2 */ \"|XXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXX|\",\n/* 3 */ \"|XXXXX XXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXX XXXXXXXX|\",\n/* 4 */ \"|XXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXX XXXXXXXX|\",\n/* 5 */ \"|XXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXX XXXXXXXX|\",\n/* 6 */ \"|XX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|\",\n/* 7 */ \"|XX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|\",\n/* 8 */ \"|XXX XXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX|\",\n/* 9 */ \"|XXXX XXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX|\",\n/* 10 */ \"|XXXXX XXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX|\",\n/* 11 */ \"|XXXXXXX XXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|\",\n/* 12 */ \"|XXXXXXXX XXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXX|\",\n/* 13 */ \"|XXXXXXXXXX XXXXX XXXXXXX XXXXXXXXXXXXXXX XXXXXXXX___XXXXXXXX|\",\n/* 14 */ \"|XXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXxxxXXXXXXXX|\",\n/* 15 */ \"|XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXX XXXXXXXXXXx xXXXXXXX|\",\n/* 16 */ \"|XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXx xXXXXXXX|\",\n/* 17 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|\",\n/* 18 */ \"|______________________________________________________________________________|\",\n/* 19 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|\",\n/* 20 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|\",\n/* 21 */ \"|XXX XXX|\",\n/* 22 */ \"|XXX XXX|\",\n/* 23 */ \"|XXX XXX|\",\n/* 0 */ \"|XXX XXX|\", \n/* 1 */ \"|XXX XXX|\", \n/* 2 */ \"|XXX XXX|\", \n/* 3 */ \"|XXX XXX|\", \n/* 4 */ \"|XXX XXX|\", \n/* 5 */ \"|XXX XXX|\", \n/* 6 */ \"|XXX XXX|\", \n/* 7 */ \"|XXX XXX|\", \n/* 8 */ \"|XXX XXX|\", \n/* 9 */ \"|XXXX XXXX|\", \n/* 10 */ \"|XXXXX XXXXX|\", \n/* 11*/ \"|XXXXXX XXXXXX|\", \n/* 12 */ \"|XXXXXXX XXXXXXX|\", \n/* 13 */ \"|XXXXXXXX XXXXXXXX|\", \n/* 14 */ \"|XXXXXXXXX XXXXXXXXX|\", \n/* 15 */ \"|XXXXXXXXXX XXXXXXXXXX|\", \n/* 16 */ \"|XXXXXXXXXXX XXXXXXXXXXX|\", \n/* 17 */ \"|XXXXXXXXXXX XXXXXXXXXXX|\", \n/* 18 */ \"|XXXXXXXXXXXX XXXXXXXXXXXX|\", \n/* 19 */ \"|XXXXXXXXXXXX XXXXXXXXXXXX|\", \n/* 20 */ \"|XXXXXXXXXXXXX XXXXXXXXXXXXX|\", \n/* 21 */ \"|XXXXXXXXXXXXX XXXXXXXXXXXXX|\", \n/* 22 */ \"|XXXXXXXXXXXXXX XXXXXXXXXXXXXX|\", \n/* 23 */ \"|XXXXXXXXXXXXXX XXXXXXXXXXXXXX|\"\n/* 24 */ \"|XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX|\", \n/* 25 */ \"|XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX|\", \n/* 26 */ \"|XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX|\", \n/* 27 */ \"|XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX|\", \n/* 28 */ \"|XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 29 */ \"|XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 30 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 31*/ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX|\", \n/* 32 */ \"|XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX|\", \n}; \n</code></pre>\n\n<p>I recommend putting big things like this in a global variable or external file. That way your code isn't cluttered.</p>\n\n<pre><code> ////////////////////////////////// Splash Screen ///////////////////////////// \n Map splashScreen_map(splashScreen, 24);\n theScreen.Insert(splashScreen_map, 0, nrows);\n theScreen.Refresh(MAP);\n myStopwatch.Wait(3);\n myStopwatch.Restart();\n /////////////////////////////////////////////////////////////////////////////////\n\n Map L1(_lines_, nrows, \"L1\");\n theScreen.Insert(L1, 0, nrows);\n Sprite player(\"Player\",'8',100); //(8, 12, 16);\n player.set_location(24, 48);\n\n ////////////////////// Check if new line is needed;\n double refreshes= 0;\n double newSpeed= 10;\n for (bool quit = false; quit != true;)\n { double newTime= myStopwatch.ElapsedTime()- refreshes;\n</code></pre>\n\n<p>I've probably already said it, but adopt a consistent strategy for where you put your braces.</p>\n\n<pre><code> if(newTime*newSpeed >= 1){\n theScreen.Insert(L1, 0+refreshes, nrows+refreshes);\n refreshes++;\n if(L1.size()<= nrows+refreshes+2)\n L1.generate();}\n ///////////////// Keypress ///////////\n if (kbhit()){\n int key = getch(); \n key = toupper(key); // makes whatever key uppercase\n\n int xMove = 0;\n int yMove = 0;\n int stepSize = 1;\n bool validPress = true;\n switch(key){\n // update health here............\n case 'W': yMove = -stepSize;break;\n case 'S': yMove = stepSize; break;\n case 'A': xMove = -stepSize;break;\n case 'D': xMove = stepSize; break;\n\n case'P': getch(); break;\n case'O': quit = true;\n\n default: validPress = false;}\n\n if(validPress == true){\n\n char coll; // if there's no collision\n if(theScreen.check_collision(player, xMove, yMove, coll) != true){ \n // get rid of old player placing\n theScreen.Insert(' ', player.get_location()[0],player.get_location()[1]);\n // put in new charater placing\n player.move(xMove, yMove);\n theScreen.Insert(player);\n theScreen.Refresh();}\n else{\n theScreen.Refresh();}};\n // do other stuff with 'coll';\n\n } /* end of if(kbhit())*/ \n\n theScreen.Refresh();}// so refresh and restart the for loop\n\nendwin(); // curses call to restore the original window and leave\nreturn 0;\n}\n</code></pre>\n\n<p>Altogether pretty good for someone who only has two months of coding expierence. However, you really wanted help on speed and nothing jumped out at me as problematic. (Mind you, I was lost for what most of the code was doing).</p>\n\n<p>At this point what you need is a profiler. I don't know what compiler/IDE you are using so I can't tell you how to do it. Essentially, a profiler will help you narrow down which part of the code is problematic. I'd run mine but your code doesn't even come close to compiling on my linux box.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-08T15:02:07.400",
"Id": "5008",
"Score": "0",
"body": "Assuming 2 months coding experience of OP literally means they started programming for the first time in their life then using a profiler may be quite a bit tricky, but that's just my opinion. Second, if this is a homework question by any chance, then those extra comments, that I agree are noise as well, are what keeps a TA deducting marks from the project on the grounds of \"Code was not commented properly\". This has been my experience with TAs/markers (it is quite sad, I agree, but nothing can be done about it). +1 for a thorough breakdown."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T22:04:20.777",
"Id": "2552",
"ParentId": "2546",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "2552",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T04:50:05.700",
"Id": "2546",
"Score": "4",
"Tags": [
"c++",
"performance",
"game",
"windows",
"curses"
],
"Title": "Text-based vertical scroller game"
}
|
2546
|
<p>I need automatic dependency generation to be done in my <code>makefile</code>. So, I have tried to write one, after googling for similar ones. I have found some ways to do that, but the problem is that they are usually too complicated for me (because of usage of <code>sed</code> command etc. and I want a way for me to create a <code>makefile</code> without the need of refering to some other <code>makefile</code>).</p>
<p>Below is a <code>makefile</code> I hope should do the same job i.e. automatically find out all the dependencies of the object files and build them. Could you please review this <code>makefile</code> and point out cases where the build may fail when it should not have?</p>
<pre><code>Gpp=g++
srcs=$(wildcard *.cpp)
objs=$(srcs:.cpp=.o)
deps=$(srcs:.cpp=.d)
default:test
%.o:%.d
$(Gpp) -c $*.cpp
%.d:%.cpp
echo -n "$*.d ">$*.d
$(Gpp) -MM $*.cpp>>$*.d
test: $(objs)
$(Gpp) $^ -o $@
-include $(deps)
.PHONY:clean default
clean:
-rm -rf *.o test *.d
</code></pre>
<p>One place where the <code>makefile</code> fails is when for example <code>a.cpp</code> initially included <code>a1.h</code> but it has been updated to exclude <code>a1.h</code> and <code>a1.h</code> file has been deleted from file-system. So, except that is there any place that this makefile fails?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T12:01:11.370",
"Id": "4011",
"Score": "5",
"body": "You may want to investigate the `-MP` option. \"This option instructs CPP to add a phony target for each dependency other than the main file, causing each to depend on nothing. These dummy rules work around errors 'make' gives if you remove header files without updating the 'Makefile' to match.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T16:58:01.133",
"Id": "4012",
"Score": "0",
"body": "@[Charles Bailey](http://codereview.stackexchange.com/users/72/charles-bailey) : thanks! that made it even nicer"
}
] |
[
{
"body": "<p>That will likely generate deps all the time, even if your target is 'clean'.\nPut the dep targets and includes in an ifeq block which checks the makefile target, then there wont be any dependency generation prior to cleaning (since those files should be removed by the clean, it is a waste to generate them prior to clean).</p>\n\n<pre><code>ifeq ($(MAKECMDGOALS),clean)\n# doing clean, so dont make deps.\ndeps=\nelse\n# doing build, so make deps.\ndeps=$(srcs:.cpp=.d)\n\n%.d:%.cpp\n echo -n \"$*.d \">$*.d\n $(Gpp) -MM $*.cpp>>$*.d\n\n-include $(deps)\nendif # ($(MAKECMDGOALS),clean)\n</code></pre>\n\n<p>Also it is much cleaner to create subdirs and place the .d and .o files in the subdirs. Then the source directories (i.e. 'src', ...) remain spotless and the dangerous \"-rm -rf *.o test *.d\" is completely avoided.</p>\n\n<p>Also \"-rm -rf *.o test *.d\" in itself is not optimal. Best to only remove what is defined, don't remove arbitrary files (and no need for \"-r\" either). New code:</p>\n\n<pre><code>target=test \nrm -f $(objs) $(srcs:.cpp=.d) $(target)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-20T21:40:30.560",
"Id": "3571",
"ParentId": "2547",
"Score": "7"
}
},
{
"body": "<p>Not exactly what you are asking for but I would suggest using <strong>cmake</strong> to generate the Makefile. <strong>cmake</strong> is good at automatically finding dependencies and it also lets you build in a separate build directory.</p>\n\n<p><a href=\"http://www.cmake.org\" rel=\"nofollow\">http://www.cmake.org</a></p>\n\n<p>First create a file called <strong>CMakeLists.txt</strong> with this content:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>cmake_minimum_required(VERSION 2.8)\nproject(test)\nfile(GLOB files *.cpp)\nadd_executable(test ${files})\ninstall(TARGETS test RUNTIME DESTINATION bin)\n</code></pre>\n\n<p>then build and install your program <strong>test</strong> like this</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>erik@linux:~$ ls ~/codereview/\nfile.cpp file.h CMakeLists.txt main.cpp\nerik@linux:~$ mkdir /tmp/build\nerik@linux:~$ mkdir /tmp/install\nerik@linux:~$ cd /tmp/build/\nerik@linux:/tmp/build$ cmake -DCMAKE_INSTALL_PREFIX=/tmp/install ~/codereview/\n-- The C compiler identification is GNU\n-- The CXX compiler identification is GNU\n-- Check for working C compiler: /usr/bin/gcc\n-- Check for working C compiler: /usr/bin/gcc -- works\n-- Detecting C compiler ABI info\n-- Detecting C compiler ABI info - done\n-- Check for working CXX compiler: /usr/bin/c++\n-- Check for working CXX compiler: /usr/bin/c++ -- works\n-- Detecting CXX compiler ABI info\n-- Detecting CXX compiler ABI info - done\n-- Configuring done\n-- Generating done\n-- Build files have been written to: /tmp/build\nerik@linux:/tmp/build$ make\nScanning dependencies of target test\n[ 50%] Building CXX object CMakeFiles/test.dir/main.cpp.o\n[100%] Building CXX object CMakeFiles/test.dir/file.cpp.o\nLinking CXX executable test\n[100%] Built target test\nerik@linux:/tmp/build$ ls -l /tmp/build/test\n-rwxrwxr-x 1 erik erik 7702 2012-04-12 16:58 /tmp/build/test\nerik@linux:/tmp/build$ make install\n[100%] Built target test\nInstall the project...\n-- Install configuration: \"\"\n-- Installing: /tmp/install/bin/test\nerik@linux:/tmp/build$ ls -l /tmp/install/bin/test\n-rwxr-xr-x 1 erik erik 7702 2012-04-12 16:58 /tmp/install/bin/test\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T09:41:04.113",
"Id": "17733",
"Score": "0",
"body": "+1 for bringing up CMake, but please, **please**, never use `file(GLOB)`. It completely breaks CMake (i.e. when you add or remove source files you will have to re-run CMake manually). Just list the sources explicitly. It's not so much work..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-02T07:44:25.557",
"Id": "18269",
"Score": "2",
"body": "Interesting point. I looked around and found [this stackoverflow question](http://stackoverflow.com/questions/1027247/best-way-to-specify-sourcefiles-in-cmake) that discuss advantages and disadvantages of using `file(GLOB)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-12T15:25:52.130",
"Id": "10825",
"ParentId": "2547",
"Score": "3"
}
},
{
"body": "<p>Not to be too blunt; but, you're going about this the wrong way. Look into the command line option <code>-MMD</code> for GCC, specify it when compiling your source; and, retain the inclusion statement for dependencies.</p>\n\n<p>Also, no need for a <code>default</code> target. The first target is the <code>default</code> target.</p>\n\n<p>An example:</p>\n\n<pre><code>Gpp = g++\nsrcs = $(wildcard *.cpp)\nobjs = $(srcs:.cpp=.o)\ndeps = $(srcs:.cpp=.d)\n\ntest: $(objs)\n $(Gpp) $^ -o $@\n\n%.o: %.cpp\n $(Gpp) -MMD -MP -c $< -o $@\n\n.PHONY: clean\n\n# $(RM) is rm -f by default\nclean:\n $(RM) $(objs) $(deps) test\n\n-include $(deps)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-17T21:35:06.680",
"Id": "28108",
"Score": "0",
"body": "This is the right way to approach the problem. Dependencies are only useful in _re_-compilation (everything gets built the first time through), so you don't need to generate the `.d` files in a separate step."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T10:05:07.670",
"Id": "11109",
"ParentId": "2547",
"Score": "16"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T10:07:24.577",
"Id": "2547",
"Score": "20",
"Tags": [
"c++",
"makefile"
],
"Title": "makefile dependency generation"
}
|
2547
|
Erlang is a general-purpose programming language and runtime environment. It has built-in support for concurrency, distribution and fault tolerance. Erlang is used in several large telecommunication systems from Ericsson. Erlang is open source and available for download on GitHub.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T18:22:39.987",
"Id": "2550",
"Score": "0",
"Tags": null,
"Title": null
}
|
2550
|
<p>This is a revisit to a <a href="https://stackoverflow.com/questions/1995418/python-generator-expression-vs-yield">question</a> already asked here about a year and a half ago. </p>
<p>Project Euler's <a href="http://projecteuler.net/index.php?section=problems&id=40" rel="nofollow noreferrer">Problem 40</a> involves generating the sequence of digits that appear in the natural numbers, all concatenated together (<code>123456789101112131415161718192021…</code>). As part of the solution, I wrote this:</p>
<pre><code>def counting_digits():
for number in count(1):
for digit in str(number):
yield digit
</code></pre>
<p>After finishing the solution, I tried this:</p>
<pre><code>def counting_digits():
return (digit for number in count(1) for digit in str(number))
</code></pre>
<p>My questions:</p>
<ol>
<li>In the face of Python 3, Which solution is more <em>pythonic</em>?</li>
<li>As someone who just wants to understand the code. Which is easier/clearer to read?</li>
<li>If you haven't read the statement for Project Euler's <a href="http://projecteuler.net/index.php?section=problems&id=40" rel="nofollow noreferrer">Problem 40</a>, Which version lets you better know what the function does?</li>
</ol>
<p>Performance is not part of the question: <em>pythonism</em> and understandability is the issue.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T02:45:12.567",
"Id": "4031",
"Score": "4",
"body": "I think generator expressions are only useful when they are simple enough that they don't need explanation and you can use them inline in whatever your code is doing. The moment you want to move into its own function the yield syntax is clearer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T04:25:10.227",
"Id": "64490",
"Score": "0",
"body": "The first is easier to read, and hence more Pythonic. There should also be no difference in performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:46:17.760",
"Id": "64491",
"Score": "0",
"body": "Since you didn't do any operation on `c`, the last one makes more sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:49:44.127",
"Id": "64492",
"Score": "0",
"body": "How about `yield int(c)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:23:18.087",
"Id": "64493",
"Score": "0",
"body": "As a programmer who is somewhat familiar with Python, but writes it fairly infrequently, I find the `yield` version more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:44:40.040",
"Id": "64494",
"Score": "0",
"body": "@Matt But isn't the _yield_ concept harder to grasp unless you come from Ruby or such?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:56:07.150",
"Id": "64495",
"Score": "0",
"body": "I already understand what `yield` does from JavaScript, but JS doesn't have generator expressions. I don't know Ruby. I find that the extra white space in the `yield` version is just plain easier on the eyes. It's all a matter of opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T16:02:28.513",
"Id": "64496",
"Score": "0",
"body": "@Matt _easier on the eyes_: It's my own code, and, hoopla, I have to think harder to understand what I wrote in the generator expression version."
}
] |
[
{
"body": "<p>The one where you return a generator is easier to read were it the case that there was only one <code>for</code>. Also, as OP pointed out, the associativity of nested for loops is not what you'd expect in Python.</p>\n\n<p>The top one may be slightly easier to read for some people; it would be MUCH easier to read if there were comments or if the variables were semantically named, and the indented structure allows for comments much better. With semantically-named variables, the first version is easier to read; I'd only use single-letter variable names as the pattern in list comprehensions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:27:37.137",
"Id": "4014",
"Score": "0",
"body": "In which case(s) is the generator more efficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:29:33.997",
"Id": "4015",
"Score": "0",
"body": "In the case of nested generators, see http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys/6043835#6043835 where I mention asymptotic speed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:51:03.620",
"Id": "4016",
"Score": "0",
"body": "That's not so much an issue with yielding though, as it is with re-yielding, so perhaps not that applicable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:53:44.327",
"Id": "4017",
"Score": "0",
"body": "@ninjagecko I edited the variable names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T16:17:47.550",
"Id": "4018",
"Score": "2",
"body": "It seems that the double `for` is the killer, because Python's way of determining scope (the earlier `for` dominates the following one) is unusual. You'd expect the result to be more closely related to the `for` that is closer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T16:24:37.907",
"Id": "4019",
"Score": "0",
"body": "@Apalala: oh my, that is incredibly awkward... I had never noticed that. Wish I could upvote your comment more... I wonder what the rationale for the very awkward ordering in nested `for`s is..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T16:27:23.920",
"Id": "4020",
"Score": "0",
"body": "@ninjagecko As I said in the question's text, just edit your answer, and make my comment yours. The insight is yours, after all."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:21:57.367",
"Id": "2554",
"ParentId": "2553",
"Score": "12"
}
},
{
"body": "<p>\"pythonic\" and \"easier/clearer\" is a completely subjective issue.</p>\n\n<p>The first example is more readable and understandable - even for a Java developer.\nThe second piece of code is more dense but I would not call it pythonic.\nBoth pieces of code are fine for me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:48:36.903",
"Id": "4024",
"Score": "0",
"body": "I think that Java doesn't yet support the concept of _yield_ (suspended/lazy execution). Why would the more 'structured code' version be clearer for a Java developer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:55:49.473",
"Id": "4025",
"Score": "0",
"body": "You are correct that Java doesn't support `yield`, but the `yield` version still _looks_ more like Java than the generator version."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:42:56.263",
"Id": "2556",
"ParentId": "2553",
"Score": "4"
}
},
{
"body": "<p>I think this is very subjective. In my case, I've used Python for about 9 months (albeit rather a lot) and find the syntax of the generator expression more concise and readable. Given the simplicity, using the generator inline would be preferable, in this case. If you needed something a bit more complicated, I'd lean towards a function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T16:00:00.287",
"Id": "4027",
"Score": "0",
"body": "I agree, except that I'd rather place the generator in a well-named function than place it inline and have to explain it with a comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T16:40:47.240",
"Id": "4028",
"Score": "0",
"body": "@Apalala Maybe a good rule of thumb is to avoid using a generator expression when you feel it'd be necessary to add a comment explaining what it does. In this case I think a comment would be unnecessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:56:11.487",
"Id": "2558",
"ParentId": "2553",
"Score": "1"
}
},
{
"body": "<p>Someone who doesn't know Python would look at the first version and ask \"What's yield do?\" After a quick google search of \"python yield\" they'd easily grok it. </p>\n\n<p>The same person would look at that second version and say \"WTF?\" What would we expect them to google to understand it?</p>\n\n<p>I won't speak for the Python community at large, but as an experienced Python programmer I find the first version clearer and more pythonic. When I encounter nested generators or list comprehensions I still need to stop for a moment to puzzle it out. I think the <a href=\"http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions\">docs</a> concede that nested generators and list comprehensions can be confusing when they advise</p>\n\n<blockquote>\n <p>To avoid apprehension when nesting\n list comprehensions, read from right\n to left.</p>\n</blockquote>\n\n<p>And shortly after that they say</p>\n\n<blockquote>\n <p>In real world, you should prefer\n built-in functions to complex flow\n statements.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T19:55:42.373",
"Id": "4029",
"Score": "0",
"body": "+1 As I mentioned, it was unexpected for me that right after writing this question, I found that my own code was harder to understand in the single-liner version."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T18:44:30.897",
"Id": "2559",
"ParentId": "2553",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "2554",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-22T15:19:31.103",
"Id": "2553",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"comparative-review",
"generator"
],
"Title": "Generating the sequence of the digits that appear in the sequence of natural numbers"
}
|
2553
|
<p>I'm fetching a string that is JSONP, and looking to convert it to JSON. </p>
<p>I'm using the following regular expression for matching (for removal) the padding on the JSON. </p>
<pre><code>([a-zA-Z_0-9\.]*\()|(\);?$)
</code></pre>
<p>In python, here's the line I'm using for converting the JSONP to JSON:</p>
<pre><code>apijson = re.sub(r'([a-zA-Z_0-9\.]*\()|(\);?$)','',jsonp)
</code></pre>
<p>Is there anything I should worry about using this regular expression? Any chance I could end up mangling the JSON?</p>
|
[] |
[
{
"body": "<p>The problem with the code is that it doesn't really express what you are trying to do:</p>\n\n<pre><code>apijson = re.sub(r'([a-zA-Z_0-9\\.]*\\()|(\\);?$)','',jsonp)\n</code></pre>\n\n<p>The code would seem to indicate that you are trying to find and replace many instances of some regular expressions inside the string. However, you are really trying to strip parts off of the beginning and end. I'm also not a huge fan of regular expressions because they are usually pretty dense and hard to read. Sometimes they are awesome, but this is not one of those times.</p>\n\n<p>Additionally, you aren't anchoring the regular expression to the beginning of the string which is what you'd need to strip off. The only case I could see that being a problem is perhaps if there were strings inside the json which matched the regular expression. Its best to be sure.</p>\n\n<p>Also, I think JSON-P allows functions like alpha[\"beta\"] which will doesn't fit your regular expression. Also what about additional whitespace or comments? </p>\n\n<p>I would suggest doing something like:</p>\n\n<pre><code> apijson = jsonp[ jsonp.index(\"(\") + 1 : jsonp.rindex(\")\") ]\n</code></pre>\n\n<p>That way you are more clearly stripping everything outside of the first and last parenthesis. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T01:19:10.333",
"Id": "2562",
"ParentId": "2561",
"Score": "8"
}
},
{
"body": "<p>You can simply slice the jsonp text to remove the initial padding and ending bracket by doing something like this:</p>\n\n<pre><code>jsonp_data = \"callbackfunc({'count':2345, 'url':\"http://stackoverflow.com/})\"\n\njsonp_data[len('callbackfunc('):-1]\n</code></pre>\n\n<p>This will easily remove the padding. As in most of the cases, you might be just calling some API, then this method might be the best as API would always return the same string. If your response jsonp string padding varies every time, then you'd better write some regex.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T21:26:28.673",
"Id": "38941",
"ParentId": "2561",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2562",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T00:30:33.330",
"Id": "2561",
"Score": "6",
"Tags": [
"python",
"json",
"regex"
],
"Title": "Converting JSONP to JSON: Is this Regex correct?"
}
|
2561
|
<p>I'm pretty new to C so I decided to implement <a href="http://srfi.schemers.org/srfi-1/srfi-1.html" rel="nofollow">SRFI-1</a> (linked-list library) to help me learn.</p>
<p>What I have so far is working, but only handles integers.</p>
<pre><code>typedef struct pair {
int car;
struct pair *cdr;
} pair;
</code></pre>
<p>From what I've read I can use a void * for the car:</p>
<pre><code>typedef struct pair {
void *car;
struct pair *cdr;
} pair;
</code></pre>
<p>This works but I get lots of these...</p>
<pre><code>llist.c:262:3: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘void *’
llist.c:27:7: note: expected ‘void *’ but argument is of type ‘int’
</code></pre>
<p>I've found some workarounds but before diving in and fixing everything I want to be sure this is the appropriate way to go.</p>
<p>The only other way I can think of is using some sort of generic object type:</p>
<pre><code>typedef struct object {
union {
int fixnum;
double flonum;
}
}
typedef struct pair {
object *car;
struct pair *cdr;
} pair;
</code></pre>
<p>Or something similar.</p>
<p>Is there a best practice for generic functions/data types?</p>
<p>The full source is <a href="https://github.com/jacktrades/SRFI-1-in-C/blob/master/llist.c" rel="nofollow">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T02:46:49.057",
"Id": "4032",
"Score": "0",
"body": "This depends on what your goal is. Do you want to produce a linked list library that will be useful to users in C? Or do you want to produce something in the spirit of the SRFI-1? A straightforward copy of that won't produce idiomatic C code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T04:20:41.687",
"Id": "4034",
"Score": "0",
"body": "@Winston Ewert: I'd like to make this idiomatic C even if that means deviating from SRFI-1. The purpose of doing this is to help me learn C (pointers, memory management, etc), so a straightforward port isn't really what I'm going for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T12:44:39.273",
"Id": "4035",
"Score": "0",
"body": "This is not so much a review of working code as a request to help solve a problem. Probably a better fit on Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T16:50:03.573",
"Id": "4042",
"Score": "0",
"body": "@Adam Davis, its really a question about best practices. However, that's still off-topic for this site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T19:22:41.270",
"Id": "4045",
"Score": "0",
"body": "Sorry I thought best practice type questions were appropriate here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T21:53:01.857",
"Id": "4056",
"Score": "1",
"body": "@Jack Trades, there are a number of best practice questions here which haven't been challenged. But the official policy is no best practice questions."
}
] |
[
{
"body": "<p>void* is the standard to implement such generics in C. The trouble with union is that the end-user cannot put their own types/structs in it. With void * a pointer to a user-defined struct can be used. However, be careful about memory leaks!</p>\n\n<p>The warnings you are getting is because you haven't consistently used void*. </p>\n\n<pre><code>llist.c:262:3: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘void *’\n</code></pre>\n\n<p>This indicates that you are printf'ing the data as if it were an int. But you don't what it is so you can't do that. Either don't provide printing options or provide a way to control how the object prints.</p>\n\n<pre><code>llist.c:27:7: note: expected ‘void *’ but argument is of type ‘int’\n</code></pre>\n\n<p>You have a void * and you are passing it to a function that takes int. Everything inside your library should be using void * not int. Only the actual code using your library should conver the void * into int or whatever they are using.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T20:41:37.457",
"Id": "4046",
"Score": "0",
"body": "So I should implement everything with void* and let the user worry about the rest, which would look something like this?\n\n`int j = 42;`\n`void *p = &j;`\n`vpair *k = vcons(p, NULL);`\n`printf(\"\\n%d\\n\", *(int *)k->car);`\n\nPresumably I/the user would create some type of wrapper functions which would hide most of the pointer stuff?\n\nI definitely have one foot over the edge of the limit of my knowledge here, so I'm sorry if I'm not making sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T21:50:59.800",
"Id": "4054",
"Score": "0",
"body": "@Jack Trades, firstly, j appears to be a local variable. You really shouldn't take pointers from local variables because they will become invalid as soon as the function ends. You really need to malloc space for an int, and use that. But then you need to free the memory when its not being used anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T21:52:25.680",
"Id": "4055",
"Score": "0",
"body": "@Jack Trades, I'm not seeing any sort of wrapping which would improve situation. You could write wrappers for specific versions of the list. I.e. you could write an int linked-list which used the original linked list underneath. However, I don't think it would be very useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T04:11:14.677",
"Id": "4057",
"Score": "0",
"body": "@Winston Ewert: Yes j was a local var and I can see now why that won't work, thank you. So code like `printf(\"%d\", *(int *)k->car)` is what is expected from generic libraries like this? I was originally thinking of writing wrappers like an int linked-list, but after reading your comments and considering a list of heterogeneous types I realize that would be mostly pointless. My idea of a generic print_list function seems to be drifting further and further away."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T14:22:07.883",
"Id": "4068",
"Score": "0",
"body": "@Jack Trades, generic libraries like this aren't common in C because there isn't a good way of doing it. The ones I have seen do it that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T21:45:53.590",
"Id": "4076",
"Score": "0",
"body": "even in C++ there is no generic containers, there are template containers which basically write code for every type. You can do something similar with macros in C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T22:09:44.377",
"Id": "4078",
"Score": "0",
"body": "@Keith Nicholas, I suppose you could implement such a library as macros in C. But that would be a lot harder then templates in C++. (Not that C++ templates are easy)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T06:22:40.347",
"Id": "4085",
"Score": "0",
"body": "@Winston Ewert: So I'm on the right track as far as generic libraries go. However generic libraries are not consistent with idiomatic C. I mostly just want to say thanks for the help, I think I've learned more about C from this thread than from writing a Scheme interpreter (btw I used a variation of the object union above for the interpreter)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-11T05:04:49.777",
"Id": "17189",
"Score": "1",
"body": "@JackTrades people seem to forget that you can do generics in C. Your linked list can require a pointer to a function that provides print capability. You can set this to a default of your own; include an enumeration in your struct that is like, int = 1, float = 2, user_defined = 3, etc. and your function can handle the built-in types. Users can supply their own functions for code that needs them. This is related to the early C++->C preprocessor compilation techniques; almost everything that C++ can do, C can too, even in terms of templates and generics, even if it's ugly. But this isn't."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T17:59:19.230",
"Id": "2571",
"ParentId": "2564",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2571",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T01:45:39.330",
"Id": "2564",
"Score": "5",
"Tags": [
"c"
],
"Title": "Generic linked-list library in C"
}
|
2564
|
<p>I hate this code. What is the slickest way to write the following:</p>
<pre><code>MyFile = f;
SaveFolder = Server.MapPath("\\") + "returns\\";
if(!System.IO.Directory.Exists(SaveFolder) )
{
System.IO.Directory.CreateDirectory(SaveFolder);
}
MyFile.SaveAs(SaveFolder + "2011" + "000-00-0000" + ".xlsx");
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T21:43:15.930",
"Id": "4053",
"Score": "4",
"body": "What exactly do you hate about this code? Are you looking for a 1-line version of it?"
}
] |
[
{
"body": "<p>well, for starters, use Path.Combine... eg :-</p>\n\n<pre><code>SaveFolder = Path.Combine(Server.MapPath(@\"\\\"),\"returns\");\n</code></pre>\n\n<p>same kind of thing for building your file name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T12:53:20.247",
"Id": "4064",
"Score": "0",
"body": "I'm not using 4.0"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T21:33:17.203",
"Id": "4075",
"Score": "6",
"body": "Thats ok, they were nice enough to build it into .NET since 1.1 I think"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T21:49:45.527",
"Id": "4077",
"Score": "0",
"body": "It's burried in under System.IO :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T12:11:59.617",
"Id": "4092",
"Score": "0",
"body": "You may be right. However, check out Microsoft's own documentation..http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx It only lists .Net 4.0 & Silverlight I googled this BEFORE, I posted that I wasn't using 4.0"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-11T20:57:44.737",
"Id": "251849",
"Score": "0",
"body": "@MVCylon msdn isn't maybe that clear about it, but the trick is, only one Combine override was available pre .Net 4 - https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.80).aspx that's why you could choose it"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T21:40:40.483",
"Id": "2576",
"ParentId": "2573",
"Score": "6"
}
},
{
"body": "<p>Since <code>CreateDirectory</code> does nothing if a directory already exists, you can do this:</p>\n\n<pre><code>MyFile = f;\nSaveFolder = Path.Combine(Server.MapPath(\"\\\\\"), \"returns\");\nSystem.IO.Directory.CreateDirectory(SaveFolder);\nMyFile.SaveAs(SaveFolder, \"2011000-00-0000.xlsx\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T01:02:06.037",
"Id": "2580",
"ParentId": "2573",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "2580",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-05-23T19:36:01.967",
"Id": "2573",
"Score": "4",
"Tags": [
"c#",
"strings",
"file-system"
],
"Title": "Streamline code for checking if a directory exists and saving a file"
}
|
2573
|
<p>I'd really appreciate some harsh/constructive criticism of what I would consider as my first program in Haskell. The program should download all of the xkcd comics into a folder in the current directory.</p>
<p>I basically just threw the kitchen sink at it, using anything I found remotely interesting in RWH and on the Haskell wiki, so I'm 99% sure most of it is unnecessary or overkill. I tried using most popular libraries I could find.
I wasn't clear on how to handle errors, how to deal with the filesystem efficiently, and how to use Text.JSON correctly. </p>
<p><a href="http://hpaste.org/46951/xkcd" rel="nofollow">hpaste link</a></p>
<pre><code> {-# Language PackageImports #-}
module Main where
import System.FilePath (takeFileName, (</>))
import System.IO
import System.Environment
import System.Posix.User
import System.Directory
import Control.Monad (liftM, forM_, replicateM_)
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import Data.List (delete)
import Network.HTTP
import qualified Data.ByteString.Lazy.Char8 as L
import "mtl" Control.Monad.Error
import Network.URI (parseURI)
import Control.Applicative
import Control.Exception
import qualified Network.Stream as Stream (Result)
import Control.Arrow
import Text.JSON
----------------------------------------------------------------------
main = do
dir <- makeComicDir
putStrLn $ "Created " ++ dir
Right json <- xkcdFetchJSON Current
let curNum = xkcdGetNumber json "num"
comics = take curNum $ iterate (subtract 1) curNum
putStrLn $ "Downloading " ++ (show $ length comics) ++ " comics..."
comicQueue <- newTChanIO
atomically $ forM_ (ComicNumber <$> comics) $ writeTChan comicQueue
workers <- newTVarIO 8
replicateM_ 8 . forkIO $ worker comicQueue workers dir
waitFor workers
putStrLn "DONE"
----------------------------------------------------------------------
data ComicNumber = Current | ComicNumber Int deriving (Show)
getReq = fmap (mkRequest GET) . parseURI
getRequestE = maybe (throwError "invalid url") return . getReq
tryRequest :: Request_String
-> IO (Either IOException (Stream.Result (Response String)))
tryRequest = try . simpleHTTP
simpleHttpE request = do
response <- liftIO $ tryRequest request
case response of
Left err -> throwError $ show err
Right rsp -> return rsp
getResponseBodyE = either (throwError.show) (return.rspBody)
fetchHtmlA = Kleisli getRequestE >>>
Kleisli simpleHttpE >>>
Kleisli getResponseBodyE
fetchHTMLBody url = runErrorT $ runKleisli fetchHtmlA url
----------------------------------------------------------------------
xkcd = "http://xkcd.com/"
xkcdJSONUrl Current = xkcd ++ "info.0.json"
xkcdJSONUrl (ComicNumber n) = xkcd ++ show n ++ "/info.0.json"
xkcdFetchJSON :: ComicNumber -> IO (Either String String)
xkcdFetchJSON num = runErrorT $ runKleisli fetchHtmlA $ xkcdJSONUrl num
xkcdComicUrl :: ComicNumber -> IO String
xkcdComicUrl num = do
Right jstr <- xkcdFetchJSON num
let (Ok (JSObject jobj)) = decode jstr
(Ok img) = valFromObj "img" jobj
return img
xkcdGetNumber :: String -> String -> Int
xkcdGetNumber jstr key =
let (Ok (JSObject jobj)) = decode jstr
(Ok jval) = valFromObj key jobj
in jval
----------------------------------------------------------------------
getImgName = takeFileName
downloadComic dir num = do
url <- xkcdComicUrl num
let (ComicNumber n) = num
name = (show n) ++ "_" ++ getImgName url
path = dir </> name
comic <- fetchHTMLBody url
case comic of
Left err -> putStrLn $ "ERROR: " ++ show err
Right img -> do
file <- openBinaryFile path WriteMode
hPutStr file img
hClose file
putStrLn $ "Saving " ++ name
makeComicDir = do
homedir <- getHomeDirectory
let imgdir = homedir </> ".xkcd"
createDirectory imgdir
return imgdir
worker jobs alive dir = work
where quit = atomically $ readTVar alive >>= writeTVar alive . (subtract 1)
cont = do job@(ComicNumber n) <- atomically $ readTChan jobs
if' (n == 404) work $ downloadComic dir job >> work
work = (atomically $ isEmptyTChan jobs) >>= \x -> if' x quit cont
waitFor alive = atomically $ readTVar alive >>= check . (==0)
----------------------------------------------------------------------
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T04:04:59.947",
"Id": "4047",
"Score": "0",
"body": "simpleHttpE seems to be converting Either to an IO Exception, right after tryRequest converts the IO exception to Either. Is this not redundant?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T07:59:42.707",
"Id": "4048",
"Score": "0",
"body": "`comics = reverse [1..curNum]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T08:00:31.613",
"Id": "4049",
"Score": "1",
"body": "The Kleisli stuff is just Kleisli composition, isn't it? Use `<=<`."
}
] |
[
{
"body": "<p>Looks pretty good. You're getting on top of stuff nicely. Some criticism:</p>\n\n<ul>\n<li>don't use package imports</li>\n<li>write type signatures for top level functions</li>\n<li>write comments!</li>\n<li>thread design looks good.</li>\n<li>don't use <code>if'</code>. Haskell has <code>if</code> already.</li>\n<li>Kleisli needs documentation. Starting to go overboard at this point.</li>\n<li>don't mix too many concepts in one program: the code won't be maintainable.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T02:54:50.927",
"Id": "4050",
"Score": "0",
"body": "Thanks. Some of the type signatures were awfully long so I wasn't sure whether to include them or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T03:16:02.197",
"Id": "4051",
"Score": "1",
"body": "Perhaps write type synonyms for the major part of the design?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T14:33:27.917",
"Id": "4052",
"Score": "2",
"body": "I really like using if as a function instead of a keyword. It's more intuitive for me and the syntax seems more readable. Is there any if function in the standard libraries?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-06T07:33:45.710",
"Id": "4957",
"Score": "0",
"body": "@Anonymous if there were, you would be able to find it by putting [its type into Hoogle](http://haskell.org/hoogle/?hoogle=Bool+-%3E+a+-%3E+a+-%3E+a). So I guess not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-06T16:09:55.033",
"Id": "4970",
"Score": "1",
"body": "Haskell's if-then-else can be a bit of a straightjacket sometimes -- such as when you don't want an \"else\" clause. There's a whole discussion about if' here: http://www.haskell.org/haskellwiki/If-then-else"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T06:35:23.517",
"Id": "9891",
"Score": "1",
"body": "What's wrong with the PackageImports extension? Apparently, this was needed to work around the conflicting packages mtl and transformers (though I don't think they conflict anymore these days)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T02:22:21.570",
"Id": "2575",
"ParentId": "2574",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T01:58:32.413",
"Id": "2574",
"Score": "16",
"Tags": [
"haskell",
"json",
"http",
"web-scraping"
],
"Title": "Simple xkcd comic downloader"
}
|
2574
|
<p>I'm looking for any comments or feedback on my database access class. Security and speed are two things I'm most concerned about.</p>
<p>One thing to note is this class has to work in a C# .NET 2 environment, so anything that's more modern would be interesting to me, but please note in the title of your answer if the comments/feedback require a newer .NET version.</p>
<pre><code>using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
/// <summary>
/// This is the base class for database access classes. This is the only
/// class that should directly talk to the database. Every class or page
/// that neads to access the database should be refering to this or a
/// derived class.
/// </summary>
public class DatabaseAccess
{
static string LastDatabaseName = "";
static Database database = null;
static int errorCount = 0;
/// <summary>
/// Execute a SQL statement on the default database
/// </summary>
/// <param name="SQL">The SQL statement to execute</param>
/// <returns>DataTable of selected results</returns>
public static DataTable ExecSQL(string SQL)
{
List<SqlParameter> Parameters = new List<SqlParameter>();
return ExecSQL("", SQL, Parameters);
}
/// <summary>
/// Execute a SQL statement on the default database
/// </summary>
/// <param name="SQL">The SQL statement to execute</param>
/// <param name="Parameters">The parameters for the SQL statement</param>
/// <returns>DataTable of selected results</returns>
public static DataTable ExecSQL(string SQL, List<SqlParameter> Parameters)
{
return ExecSQL("", SQL, Parameters);
}
/// <summary>
/// Execute a SQL statement on the requested database
/// </summary>
/// <param name="DatabaseName">The database to execute the SQL on</param>
/// <param name="SQL">The SQL statement to execute</param>
/// <returns>DataTable of selected results</returns>
public static DataTable ExecSQL(string DatabaseName, string SQL)
{
List<SqlParameter> Parameters = new List<SqlParameter>();
return ExecSQL(DatabaseName, SQL, Parameters);
}
/// <summary>
/// Execute a SQL statement on the requested database
/// </summary>
/// <param name="DatabaseName">The database to execute the SQL on</param>
/// <param name="SQL">The SQL statement to execute</param>
/// <param name="Parameters">The parameters for the SQL statement</param>
/// <returns>DataTable of selected results</returns>
public static DataTable ExecSQL(string DatabaseName, string SQL, List<SqlParameter> Parameters)
{
// Database access variables
// Database database = null;
DbCommand command = null;
DataTable table = new DataTable();
if (DatabaseName != LastDatabaseName || database == null)
{
if (database != null)
database = null;
if (DatabaseName != "")
database = DatabaseFactory.CreateDatabase(DatabaseName);
else
database = DatabaseFactory.CreateDatabase();
}
LastDatabaseName = DatabaseName;
command = database.GetSqlStringCommand(SQL);
foreach (SqlParameter p in Parameters)
{
database.AddInParameter(command, p.ParameterName, p.DbType, p.Value);
}
try
{
if (!SQL.StartsWith("UPDATE") && !SQL.StartsWith("DELETE"))
table = database.ExecuteDataSet(command).Tables[0];
else
database.ExecuteNonQuery(command);
errorCount = 0;
}
catch (SystemException e)
{
errorCount++;
if (errorCount < 2)
{
CMSLog.Exception(e);
CMSLog.Info(SQL);
CMSUtil.setSession("Exception", e.Message);
CMSUtil.setSession("ExceptionExtra", e.StackTrace);
HttpContext.Current.Response.Redirect("~/CMS/SiteError.aspx");
}
else
{
HttpContext.Current.AddError(new Exception("Looping DB Error: " + e.Message));
}
}
return table;
}
}
</code></pre>
<p>A simple example using the class:</p>
<pre><code>string strValue = "Some Untrusted Value";
List<SqlParameter> parms = new List<SqlParameter>();
parms.Add(new SqlParameter("Value", strValue));
string sql = "SELECT * FROM TableName WHERE FieldName=@Value";
DataTable tblResults = DatabaseAccess.ExecSQL(sql, parms);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T09:40:53.533",
"Id": "4062",
"Score": "0",
"body": "In your summary, _\"neads\"_ should be _\"needs\"_ and _\"refering\"_ should be _\"referring\"_. ;p"
}
] |
[
{
"body": "<p>A few quick ideas:</p>\n\n<ul>\n<li>Check spelling.</li>\n<li>Use <code>string.Empty</code> instead of \"\" for improved readability and performance.</li>\n<li>Always use visibility modifiers - For example your fields lack the typical \"private\" keyword. Example <code>private static Database database = null;</code></li>\n<li>Re-evaluate your design choice to go with a static class. Static classes are know for causing head-aches such as threading problems. Read more <a href=\"https://stackoverflow.com/questions/752758/is-using-a-lot-of-static-methods-a-bad-thing\">here</a> to start with if you are unsure. Just removing all \"static\" keywords will make the class just as usable.</li>\n<li>Use lower case for local variables and parameters. For example: \"var parameters = new List();\"</li>\n<li>As for the error-counting-logic I don't even know where to start... :-/ Perhaps the whole thing can be done in some other way.</li>\n<li>Consider the naming of <code>ExecSQL</code> - SQL commands can be both inserts and selects and also other types of commands, while this class concerns itself with <em>select</em></li>\n<li>Consider using <code>IEnumerable<T></code> instead of <code>List<T></code> since you're only iterating the <code>List<T></code>.</li>\n</ul>\n\n<p>If you use c# 3.0 or later</p>\n\n<ul>\n<li>Use the <code>var</code> keyword if target type is redundant. Example <code>List<SqlParameter> Parameters = new List<SqlParameter>();</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T16:51:27.803",
"Id": "4070",
"Score": "0",
"body": "Hi and thanks. To explain the error counting logic (I'll add comments to the code as well). The CMSLog class logs information into the database and itself uses the DatabaseAccess class. The counting catches errors network/connectivity errors, which would result in an endless loop, and breaks the loop with an error page. The idea is all possible errors are logged without stopping the application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T19:10:06.693",
"Id": "4073",
"Score": "0",
"body": "@Justin808 np. yeah I got it. It is just... done in a very strange way for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:56:51.923",
"Id": "447148",
"Score": "0",
"body": "Since .NET 2.0 `string.Empty` performs no better than `\"\"`. Still worth using for readability, though. https://stackoverflow.com/a/151481/3668251"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T13:44:49.120",
"Id": "2587",
"ParentId": "2578",
"Score": "6"
}
},
{
"body": "<p>1) </p>\n\n<pre><code> if (DatabaseName != LastDatabaseName || database == null)\n {\n if (database != null)\n database = null;\n\n if (DatabaseName != \"\")\n database = DatabaseFactory.CreateDatabase(DatabaseName);\n else\n database = DatabaseFactory.CreateDatabase();\n }\n</code></pre>\n\n<p>First two lines inside your <code>if</code> do not make any sense. Anyway you're assigning another value to <code>database</code> variable below. I would write it as: </p>\n\n<pre><code> if (DatabaseName != LastDatabaseName || database == null)\n {\n database = DatabaseName != \"\" ?\n DatabaseFactory.CreateDatabase(DatabaseName) :\n DatabaseFactory.CreateDatabase();\n }\n</code></pre>\n\n<p>2) Define your variables closer to the first assignment place. <code>command</code> variable is defined 10 lines of code before it is assigned and also has some value which is not used at all. </p>\n\n<p>3) Looks like you're following <code>One return</code> rule. I personally do not think this rule should be followed (at least in C#). For example you're assigning <code>dataTable</code> variable in case of <code>select</code> and do <strong>nothing</strong> more with, only returning it. But I (as maintainer of your code) see you're assigning it and I <strong>have</strong> to read the method till the end. Just return <code>dataTable</code> right there - this will let me know that nothing done with it later - it will save my time. </p>\n\n<p>4) In case of <code>insert</code> or <code>update</code> statements you're returning empty dataTable. I would return either <code>null</code> to distinguish it from <code>select</code> statement or dataTable with one cell which will contain number of updated entries (at the moment you're swallowing this information). </p>\n\n<p>5) The entire code is not that intuitive which means that it is not easy readable which means that it is not easy maintainable. I would never guess that in order to add parameter to the command I should look for a method in <code>database</code> class. </p>\n\n<p>6) I would never expect that such method will <strong>create databases</strong>. This is not intuitive at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T16:54:17.663",
"Id": "4071",
"Score": "0",
"body": "JIM-compiler - Thanks for the answer. The 'if (database != null) { database = null; }` bit will close an exiting connection if its open and clear out the variable so a new connection can be opened. It prevents hanging connections to the database."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T16:56:26.773",
"Id": "4072",
"Score": "0",
"body": "The class will never create a database unless you pass the SQL to ExecSQL to do so. The `DatabaseFactory.CreateDatabase` method is part of `Microsoft.Practices.EnterpriseLibrary` and creates a database object to use based on a named connection string in the web.config. Not passing a name to the method uses the defined default connection string in web.config."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T16:05:28.793",
"Id": "2591",
"ParentId": "2578",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2587",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T23:56:41.860",
"Id": "2578",
"Score": "6",
"Tags": [
"c#",
"sql",
".net",
"asp.net",
".net-2.0"
],
"Title": "Database access class"
}
|
2578
|
<p>I am new to the world of coding as well as CSS. This is my first attempt to put together what I would consider a fully-pledged page less the content. I would appreciate if you could poke holes at it and let me know what I could have done better as well as what I should consider doing in the future. </p>
<p><strong>NOTE</strong></p>
<ul>
<li>The file does not have an external CSS as yet as I am testing the style with an internal stylesheeting prior to moving it across to an external file.</li>
<li>The file also have commented out CSS i.e /** **/ where it gives you an idea of what I attempted to achieve using position as opposed to float. I am still unclear on as when to use either. I would appreciate any input. </li>
<li>The page has been designed on a larger screen so will not adapt to a smaller screen. That is my next challenge to try and adapt it to a smaller screen.</li>
</ul>
<p><strong>CODE</strong></p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="en-us" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="author" content= "" />
<title>Example</title>
<base href="" />
<link rel="stylesheet" type="text/css" href="" />
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
#wrapper {
min-height: 100%;
}
#header {
background-image: url('images/bg-inner-page.gif');
height: 200px;
}
#logo {
float: left;
margin-top: 50px;
margin-left: 100px;
}
#topnav {
float: right;
margin-top: 50px;
margin-right: 1250px;
}
#topnav ul {
word-spacing: 10px;
}
#topnav ul li {
list-style-type: none;
display: inline;
}
#columns {
width: 400px;
float: left;
margin-top: 20px;
margin-left: 200px;
}
#col1 {
float: left;
margin-right: 10px;
width: 100px;
border: 1px solid #ffffff;
border-radius: 5px;
height: 80px;
}
#col2 {
float: left;
margin-right: 10px;
width: 100px;
border: 1px solid #ffffff;
border-radius: 5px;
height: 80px;
}
#col3 {
float: left;
width: 100px;
border: 1px solid #ffffff;
border-radius: 5px;
height: 80px;
}
#content {
float: left;
background-color: orange;
width: 500px;
margin-top: 10px;
margin-left: 500px;
overflow: auto;
padding-bottom: 150px;
}
#footer {
position: relative;
margin-top: -150px;
height: 150px;
background-color: #cccccc;
clear: both;
}
#sidebar {
float: left;
width: 100px;
margin-top: 10px;
background-color: gray;
}
/**
#logo {
width: 20px;
position: relative;
top: 50px;
left: 100px;
}
#topnav {
width: 500px;
position: relative;
top: 14px;
left: 150px;
}
#topnav ul {
word-spacing: 10px;
}
#topnav ul li {
list-style-type: none;
display: inline;
}
**/
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="logo">
logo
</div>
<div id="topnav">
<ul>
<li>home</li>
<li>about</li>
<li>browse</li>
<li>faq</li>
<li>contact</li>
</ul>
</div>
<div id="columns">
<div id="col1">col1</div>
<div id="col2">col2</div>
<div id="col3">col3</div>
</div>
</div>
<div id="content">content</div>
<div id="sidebar">sidebar</div>
</div>
<div id="footer">footer</div>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>1- even for testing you should put the css in an external file, especially when it starts to have many lines.</p>\n\n<p>2- relative will position an element relatively to its parent. So you need to ask yourself what is the \"container\", parent of this element.\n<a href=\"http://www.w3schools.com/css/css_positioning.asp\" rel=\"nofollow\">Read this</a> <a href=\"http://www.w3schools.com/css/css_float.asp\" rel=\"nofollow\">and this</a> and try the interactive examples.</p>\n\n<p>3- for a design that fits all kind of screens you will need to use %ages or detect screen size and use multiple css files.</p>\n\n<p>Anyway looking at the code and viewing the result we have no way to know what you're trying to achieve. Though it looks like a basic 3 columns + content + navigation bar design.\n<a href=\"http://www.free-css.com/free-css-layouts/page1.php\" rel=\"nofollow\">Take a look here</a> and see if you can find something that looks like what you want and see how they do it.</p>\n\n<p>For specific coding questions ask on <a href=\"http://www.stackoverflow.com\">stackoverflow</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T05:52:23.257",
"Id": "4058",
"Score": "0",
"body": "In regards to #3, you could use absolute positions in combination with left/right/top/bottom to make a display that will scale up from a sane minimum. Another option many sites use is a container div with a set width centered on the screen to avoid scaling issues as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T09:05:28.290",
"Id": "4059",
"Score": "0",
"body": "`position: relative` does **not** position the element relative to it's parent, it positions it relative to its own normal (static) position. However most of the time `position: relative` is used for its side effect, namely letting the element's absolutely positioned descendents be positioned relative itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T09:05:59.443",
"Id": "4060",
"Score": "0",
"body": "When you say \"detect screen size\", I guess you mean with JavaScript. This is however not necessary any more (unless you need to support different screen sizes in IE 6/7/8), because all relevant current browsers support CSS 3 Media Queries: http://www.w3.org/TR/css3-mediaqueries/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T11:17:49.450",
"Id": "4063",
"Score": "0",
"body": "@all: It's just a fast answer to a question that has no answer. I cannot give a class about css positioning here. Thus the links and other tips on what he should do next, then I flagged the question as off topic since it's a \"debugging\" question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T05:35:07.540",
"Id": "2582",
"ParentId": "2579",
"Score": "2"
}
},
{
"body": "<p>The first thing you should think about, is if you really need to use XHTML. XHTML has virtually no advantages and many disadvantages compared with HTML 4.01 Strict (or HTML 5). See for example <a href=\"http://www.webdevout.net/articles/beware-of-xhtml\" rel=\"nofollow\">http://www.webdevout.net/articles/beware-of-xhtml</a> .</p>\n\n<p>The basic idea of HTML and CSS is that everything \"flows\" and adjusts itself. When doing web design one thing many designers do wrong (in my option at least) is to disregard this \"flow\" and to \"think\" and design in pixels. This can easily go wrong, because the user can (and <strong>should</strong>) easily override many things (most importantly font size), which will break rigid pixel-based designs. This happens usually because of fixed heights or badly absolutely positioned elements.</p>\n\n<p>In your case this would apply to the \"header\" and the \"columns\", which contain text and you gave a fixed pixel height. Try out what happens, if the font size is larger or there is more text in them than you expect.</p>\n\n<p>Consider using less generic IDs. Especially \"column\" and \"col1/2/3\" don't give any information on what they contain. </p>\n\n<p>You can simplify and shorten your CSS by applying more complex selectors to take advantage of the \"cascading\" part of CSS. For example, you repeat the same properties for \"col1/2/3\", which could instead be moved to a rule with the selector <code>#columns > div</code> (or <code>#columns div</code> if you have to support IE 6):</p>\n\n<pre><code>#columns > div {\n float: left;\n margin-right: 10px;\n width: 100px;\n border: 1px solid #ffffff;\n border-radius: 5px;\n height: 80px;\n}\n\n#col3 {\n margin-right: 0;\n}\n</code></pre>\n\n<p>For adapting to different window sizes, look into <a href=\"http://www.w3.org/TR/css3-mediaqueries/\" rel=\"nofollow\">CSS 3 Media Queries</a></p>\n\n<p>For your commented out part: You are using <code>position: relative</code> wrongly. Have a look at <a href=\"http://www.barelyfitz.com/screencast/html-training/css/positioning/\" rel=\"nofollow\">http://www.barelyfitz.com/screencast/html-training/css/positioning/</a> to see how <code>position: relative</code> works, and what to use it for.</p>\n\n<p>You probably were thinking you using <code>position: absolute</code>, but you shouldn't. Layouts with <code>position: absolute</code> can easily break, if you do it wrong. You should consider <code>position: absolute</code> the last resort, if there is no other way to implement a layout. Using <code>float</code> as you are doing is much better as it taking advantage of the \"flow\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T22:40:59.817",
"Id": "4079",
"Score": "0",
"body": "@RoToRa - Thanks for your comments. When you say I was using `position: relative;` incorrectly, what was I doing incorrectly exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T22:45:32.587",
"Id": "4081",
"Score": "0",
"body": "@RoToRa - My understanding of relative is that the elements position is relative to a preceding element if any exists. For example, I would assume that in the code example below if I have the element footer positioned relative, it would be relative to the element content. Is that correct or would it be relative to rightcol?\n\n`<div id=\"content\">\n <div id=\"innercontent\">\n Text\n </div>\n \n <div id=\"rightcol\">\n Text\n </div>\n</div><div id=\"footer\">footer</div>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T07:11:35.900",
"Id": "4088",
"Score": "0",
"body": "Neither. `position: relative` positions an element relative to it's own \"normal\" position. It's like cutting an article out of a newspaper page and sticking it somewher else eonto the same page. All you get is a hole (or gap) and the article then covers other things at the new position. `position: relative` (on it's own) is quite useless for page layout. It however does have a side effect, that absolutely positioned elements inside an element with `position: relative` are positioned relative to that element. Have a look at the link I posted for examples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:53:50.333",
"Id": "4106",
"Score": "0",
"body": "@RoToRa - Thanks. Please correct me if I am wrong. I now understand that an element with the `position: relative;` is relative to its own position in the normal flow of the document. Am I correct to assume then that seeing that an element (let's call it b) with the `position: absolute;` within an element with the `position: relative;` (let's call it a), b's absolute position is restricted within boundaries of a. This would be that if a had a width of 200px and I position b top: 0px; right: 0px; it would be positioned to the top right of a. Is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:54:53.280",
"Id": "4107",
"Score": "0",
"body": "@RoToRa - Assuming I was correct and taking note of your comment that elements with the `position: relative;` are useless on their own, is it better to use floats?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T09:24:10.797",
"Id": "4122",
"Score": "0",
"body": "Yes, you are correct in both cases."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T11:04:22.817",
"Id": "2584",
"ParentId": "2579",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2584",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T00:03:26.190",
"Id": "2579",
"Score": "2",
"Tags": [
"html",
"css"
],
"Title": "CSS Page Example Code Review"
}
|
2579
|
<p>I've made a simple wrapper for <code>MySQLi_STMT</code>, allowing the usage of placeholders and spares you the need to manually bind variables. The full code is at the bottom of this question (it's quite large, with comments). Please give me feedback/criticisms on anything you want (readability and API design for starters).</p>
<p>Usage:</p>
<pre><code>$mysqli = new MySQLi('localhost', 'user', 'pwd', 'testdb');
$statement = new Carrot\Database\MySQLi\StatementWrapper($mysqli,
'SELECT
id, name, balance
FROM
accounts
WHERE
name LIKE #name_like,
balance > #balance_lower_limit'
);
$statement->execute(array('#name_like' => 'John%', '#balance_lower_limit' => 50000));
while ($row = $statement->fetchObject())
{
echo $row->id, $row->name, $row->balance;
}
</code></pre>
<p>I've wrapped a lot of <code>MySQLi_STMT</code> methods/properties (like <code>set_attr</code> and <code>get_attr</code>) so the code might be too long (around 900 lines), is this a problem?</p>
<p>Code on pastebin: <a href="http://pastebin.com/gikrWxFR" rel="nofollow">http://pastebin.com/gikrWxFR</a> - pastie: <a href="http://www.pastie.org/1965280" rel="nofollow">http://www.pastie.org/1965280</a> - or here: a couple of comment blocks deleted to fit:</p>
<pre><code>namespace Carrot\Database\MySQLi;
class StatementWrapper
{
/**
* @var string Statement string with placeholders, injected during construction.
*/
protected $statement_string_with_placeholders;
/**
* @var string Processed statement string, used in constructing the MySQLi_STMT object, placeholders replaced with '?'.
*/
protected $statement_string;
/**
* @var MySQLi_STMT Instance of MySQLi_STMT, constructed using {@see $statement_string}.
*/
protected $statement_object;
/**
* @var array List of placeholders with the hash (#) prefix, extracted from {@see $statement_string_with_placeholders}.
*/
protected $placeholders;
/**
* @var array List of placeholders with 'blob' data type, set by the user - see {@see }.
*/
protected $blob_params = array();
/**
* @var mixed Contains the result of MySQLi_STMT::result_metadata() call.
*/
protected $result_metadata;
/**
* @var array Parameters used to execute the query.
*/
protected $params;
/**
* @var string Parameter types in string, as per MySQLi_STMT::bind_param() specification.
*/
protected $param_types;
/**
* @var array Result row, filled with new values every time a new row is fetched.
*/
protected $result_row;
/**
* @var array Contains references to the {@see $params} property, used for binding in bind_param().
*/
protected $references_params;
/**
* @var array Contains references to the {@see $result_row} property, used for binding in bind_result().
*/
protected $references_result_row;
/**
* @var bool If set to true, any subsequent execution that fails/returns false will trigger an exception.
*/
protected $throw_exception_when_execution_fails = false;
/**
* @var bool True if result set has been buffered using MySQLi_STMT::store_result(), false otherwise.
*/
protected $result_is_buffered = false;
public function __construct(\MySQLi $mysqli, $statement_string_with_placeholders)
{
$this->statement_string_with_placeholders = $statement_string_with_placeholders;
$this->placeholders = $this->extractPlaceholders($statement_string_with_placeholders);
$this->statement_string = $this->replacePlaceholdersWithQuestionMarks($statement_string_with_placeholders);
$this->statement_object = $mysqli->prepare($this->statement_string);
if (empty($this->statement_object) or !is_a($this->statement_object, '\MySQLi_STMT'))
{
throw new \RuntimeException("StatementWrapper error, fails to prepare the statement. Error number: '{$mysqli->errno}', Error message: '{$mysqli->error}', Processed statement: '{$this->statement_string}', Original statement: '{$this->statement_string_with_placeholders}'.");
}
$this->result_metadata = $this->statement_object->result_metadata();
$this->createParameterVariablesAndReferences();
$this->createResultVariablesAndReferences();
$this->bindResult();
}
/**
* Executes the statement.
*
* Pass the parameters as associative array. Previously used
* parameters will be used if you don't pass parameter array.
* You don't need to pass anything if your statement doesn't
* need parameters.
*
* <code>
* $statement = new StatementWrapper($mysqli, 'INSERT INTO accounts (id, first_name) VALUES (#id, #first_name));
* $statement->execute(array('#id' => 'AB12345', '#first_name' => 'John'));
* </code>
*
* Will throw RuntimeException if execution fails and
* $throw_exception_when_execution_fails is true.
*
* @throws RuntimeException
* @see $throw_exception_when_execution_fails
* @param array $params Optional. Parameters to use for execution, if left empty will use previously set parameters.
* @return bool Returns true if statement executed successfully, false otherwise.
*
*/
public function execute(array $params = array())
{
if (!empty($params))
{
$this->setAndBindParameters($params);
}
$result = $this->statement_object->execute();
if (!$result && $this->throw_exception_when_execution_fails)
{
throw new \RuntimeException("StatementWrapper execution error! Error #{$this->statement_object->errno}: '{$this->statement_object->error}', statement is '{$this->statement_string}'.");
}
// After each execution, you need to call MySQLi_STMT::store_result() again.
$this->result_is_buffered = false;
return $result;
}
/**
* Fetches the result as enumerated array using MySQLi_STMT::fetch().
*
* Calls to this method is ignored if the statement doesn't have
* result. Use while() loop to iterate the result set:
*
* <code>
* while ($row = $statement->fetchArray())
* {
* echo "ID: {$row[0]}, Name: {$row[1]}";
* }
* </code>
*
* @return mixed Result row as enumerated array. False if no more rows or failure in fetching.
*
*/
public function fetchArray()
{
if (is_object($this->result_metadata) && is_a($this->result_metadata, '\MySQLi_Result'))
{
$result = $this->statement_object->fetch();
if ($result === true)
{
$row = array();
foreach ($this->result_row as $content)
{
$row[] = $content;
}
return $row;
}
return false;
}
}
/**
* Fetches the result as associative array using MySQLi_STMT::fetch().
*
* Calls to this method is ignored if the statement doesn't have
* result. Use while() loop to iterate the result set:
*
* <code>
* while ($row = $statement->fetchAssociativeArray())
* {
* echo "ID: {$row['id']}, Name: {$row['name']}";
* }
* </code>
*
* @return mixed Result row as associative array. False if no more rows or failure in fetching.
*
*/
public function fetchAssociativeArray()
{
if (is_object($this->result_metadata) && is_a($this->result_metadata, '\MySQLi_Result'))
{
$result = $this->statement_object->fetch();
if ($result === true)
{
$row = array();
foreach ($this->result_row as $field_name => $content)
{
$row[$field_name] = $content;
}
return $row;
}
return false;
}
}
/**
* Fetches the result as PHP standard object using MySQLi_STMT::fetch().
*
* Calls to this method is ignored if the statement doesn't have
* result. Use while() loop to iterate the result set:
*
* <code>
* while ($row = $statement->fetchObject())
* {
* echo "ID: {$row->id}, Name: {$row->name}";
* }
* </code>
*
* @return mixed Result row as PHP standard object. False if no more rows or failure in fetching.
*
*/
public function fetchObject()
{
if (is_object($this->result_metadata) && is_a($this->result_metadata, '\MySQLi_Result'))
{
$result = $this->statement_object->fetch();
if ($result === true)
{
$row = array();
foreach ($this->result_row as $field_name => $content)
{
$row[$field_name] = $content;
}
return (object) $row;
}
return false;
}
}
/**
* Mark parameter placeholder as 'blob' type.
*
* For each statement execution, parameters are automatically
* assigned proper type by detecting the parameter variable type
* using is_integer(), is_float(), and is_string(). Parameter type
* defaults to string. If you have to send a blob parameter type,
* use this method to mark the placeholder as such.
*
* <code>
* $statement->markParamAsBlob('#blob_param');
* </code>
*
* @see $blob_params
* @param string $placeholder The placeholder you want to mark as blob, with hash (#).
*
*/
public function markParamAsBlob($placeholder)
{
if (!isset($this->placeholders[$placeholder]))
{
throw new \RuntimeException("StatementWrapper error in marking parameter as blob. Placeholder '{$placeholder}' is not defined.");
}
$this->blob_params[] = $placeholder;
}
/**
* Tells the class to throw/not to throw exceptions when statement execution fails.
*
* Default behavior is to NOT throw exception when the query fails
* and simply return false. This makes it easier for single statements,
* however if you need to craft a transaction, you can tell this
* class to throw exception if execution fails (for whatever reason).
*
* <code>
* $statement->throwExceptionWhenExecutionFails(true);
* </code>
*
* @param bool $bool Pass true to throw exceptions, false otherwise.
*
*/
public function throwExceptionWhenExecutionFails($bool)
{
$this->throw_exception_when_execution_fails = $bool;
}
/**
* See if the result set is buffered or not.
*
* The result set is buffered if MySQLi_STMT::store_result() is
* called after each statement execution. The wrapper notes this
* by setting $result_is_buffered property to true every time
* MySQLi_STMT::store_result() is called.
*
* The wrapper does not buffer the result by default, following
* MySQLi_STMT standard behavior.
*
* If the result set is not buffered, MySQLi_STMT->num_rows() will
* not return a valid response.
*
* @return bool True if buffered, false otherwise.
*
*/
public function resultIsBuffered()
{
return $this->result_is_buffered;
}
/**
* Returns the result metadata.
*
* This method does not wrap/call MySQLi_STMT::result_metadata(),
* it simply returns a saved value since MySQLi_STMT::result_metadata()
* is already called in construction.
*
* @return mixed Instance of MySQLi_Result or false if there isn't a result.
*
*/
public function getResultMetadata()
{
return $this->result_metadata;
}
/**
* Destroys this object.
*
* Calls MySQLi_STMT::close() for safety.
*
*/
public function __destruct()
{
$this->result_is_buffered = false;
$this->statement_object->close();
}
// ---------------------------------------------------------------
/**
* Wrapper for MySQLi_STMT->affected_rows.
*
* @return mixed -1 indicates query error.
*
*/
public function getAffectedRows()
{
return $this->statement_object->affected_rows;
}
/**
* Wrapper for MySQLi_STMT::attr_get().
*
* @param int $attr The attribute you want to get.
* @return mixed False if the attribute is not found, otherwise return value of the attribute.
*
*/
public function getAttr($attr)
{
return $this->statement_object->attr_get($attr);
}
/**
* Wrapper for MySQLi_STMT::attr_set().
*
* @param int $attr The attribute you want to set.
* @param int $mode The value to assign to the attribute.
*
*/
public function setAttr($attr, $mode)
{
$this->statement_object->attr_set($attr, $mode);
}
/**
* Wrapper for MySQLi_STMT::data_seek().
*
* @param int $offset
*
*/
public function dataSeek($offset)
{
$this->statement_object->data_seek($offset);
}
/**
* Wrapper for MySQLi_STMT->errno.
*
* @return int Error number for the last execution.
*
*/
public function getErrorNo()
{
return $this->statement_object->errno;
}
/**
* Wrapper for MySQLi_STMT->error.
*
* @return string Error message for last execution.
*
*/
public function getErrorMessage()
{
return $this->statement_object->error;
}
/**
* Wrapper for MySQLi_STMT->field_count.
*
* @return int Number of fields in the given statement.
*
*/
public function getFieldCount()
{
return $this->statement_object->field_count;
}
/**
* Wrapper for MySQLi_STMT::free_result().
*
* This method also notes that result buffer has been cleared by
* setting $result_is_buffered property to false.
*
* When you run a prepared statement that returns a result set, it
* locks the connection unless you free_result() or store_result().
*
*/
public function freeResult()
{
$this->statement_object->free_result();
$this->result_is_buffered = false;
}
/**
* Wrapper for MySQLi_STMT::get_warnings().
*
* @return mixed
*
*/
public function getWarnings()
{
return $this->statement_object->get_warnings();
}
/**
* Wrapper for MySQLi_STMT->insert_id.
*
* @return int The ID generated from previous INSERT operation.
*
*/
public function getInsertID()
{
return $this->statement_object->insert_id;
}
/**
* Wrapper for MySQLi_STMT->num_rows.
*
* This method does not return invalid row count, it returns false
* if result set is not buffered.
*
* @return mixed Number of rows if result is buffered, false if result set is not buffered.
*
*/
public function getNumRows()
{
if ($this->result_is_buffered)
{
return $this->statement_object->num_rows;
}
return false;
}
/**
* Wrapper for MySQLi_STMT->param_count.
*
* @return int $param_count Number of parameters in the statement.
*
*/
public function getParamCount()
{
return $this->statement_object->param_count;
}
/**
* Wrapper for MySQLi_STMT::reset().
*
* MySQLi_STMT::reset does not unbind parameter. After you reset, you
* can safely execute it again even if the query has parameters.
*
* @return bool True on success, false on failure.
*
*/
public function reset()
{
return $this->statement_object->reset();
}
/**
* Wrapper for MySQLi_STMT->sqlstate.
*
* @return string SQLSTATE error from previous statement operation.
*
*/
public function getSQLState()
{
return $this->statement_object->sqlstate;
}
/**
* Wrapper for MySQLi_STMT::store_result().
*
* This method also sets $result_is_buffered property to true,
* allowing you getNumRows() method to return valid value. This
* method must be called *after* execution.
*
* @return bool True on success, false on failure.
*
*/
public function storeResult()
{
$this->result_is_buffered = $this->statement_object->store_result();
return $this->result_is_buffered;
}
// ---------------------------------------------------------------
/**
* Extracts placeholder names from original statement string.
*
* Placeholder is defined with this regular expression:
*
* <code>
* #[a-zA-Z0-9_#]+
* </code>
*
* Since the hash character (#) is used in MySQL to mark comments,
* chances are you won't be using it in your query other than for
* marking placeholders. List of example placeholder that will
* match:
*
* <code>
* #placeholder
* #123placeholder
* #_place_holder
* ##placeholder
* #place#holder
* </code>
*
* @param string $statement_string_with_placeholders
* @return array Array that contains placeholder names.
*
*/
protected function extractPlaceholders($statement_string_with_placeholders)
{
preg_match_all('/#[a-zA-Z0-9_#]+/', $statement_string_with_placeholders, $matches);
if (isset($matches[0]) && is_array($matches[0]))
{
return $matches[0];
}
return array();
}
/**
* Replaces placeholders (#string) with '?'.
*
* This in effect creates a statement string that we can use it
* to instantiate a MySQLi statement object. It replaces this
* pattern:
*
* <code>
* #[a-zA-Z0-9_#]+
* </code>
*
* with question mark ('?'). Returns empty array if no placeholder
* is found.
*
* @param string $statement_string_with_placeholders
* @return string Statement string safe to use as MySQLi_STMT instantiation argument.
*
*/
protected function replacePlaceholdersWithQuestionMarks($statement_string_with_placeholders)
{
return preg_replace('/#[a-zA-Z0-9_#]+/', '?', $statement_string_with_placeholders);
}
/**
* Creates parameter array to store parameters and a set of references that refers to it.
*
* We create parameter array to store parameters set by the user,
* and we create an array that references those parameters to be
* used as arguments when we use call_user_func() to call
* MySQLi_STMT::bind_param().
*
* @see $params
* @see $references_params
* @see __construct()
*
*/
protected function createParameterVariablesAndReferences()
{
$placeholder_count = count($this->placeholders);
if ($this->statement_object->param_count != $placeholder_count)
{
throw new \RuntimeException("StatementWrapper error, fails to prepare the statement. Parameter count ({$this->statement_object->param_count}) and placeholder count ({$placeholder_count}) does not match.");
}
$this->references_params['types'] = &$this->param_types;
foreach ($this->placeholders as $placeholder)
{
$this->params[$placeholder] = null;
$this->references_params[$placeholder] = &$this->params[$placeholder];
}
}
/**
* Creates array to store a fetched result row and a set of references that refers to it.
*
* We create result row variables as an array to store each value
* every time we fetch using MySQLi_STMT::fetch(). We create
* references to these result row variables to be passed when we
* use call_user_func() to call MySQLi_STMT::bind_result().
*
* @see $result_row
* @see $references_result_row
* @see __construct()
*
*/
protected function createResultVariablesAndReferences()
{
if (is_object($this->result_metadata) && is_a($this->result_metadata, '\MySQLi_Result'))
{
foreach ($this->result_metadata->fetch_fields() as $field)
{
$this->result_row[$field->name] = null;
$this->references_result_row[$field->name] = &$this->result_row[$field->name];
}
}
}
/**
* Binds result row references using MySQLi_STMT::bind_result().
*
* We only need to bind the result once, hence this method is called
* only at the constructor.
*
* @see $result_row
* @see $references_result_row
* @see __construct()
*
*/
protected function bindResult()
{
if (is_object($this->result_metadata) && is_a($this->result_metadata, '\MySQLi_Result'))
{
call_user_func_array(array($this->statement_object, 'bind_result'), $this->references_result_row);
}
}
/**
* Sets and binds parameters for the next execution.
*
* Will throw RuntimeException if the parameter array count doesn't
* match the parameter/placeholder count.
*
* Will throw RuntimeException if the parameter index doesn't contain
* all placeholders as its indexes.
*
* @throws RuntimeException
* @see execute()
* @param array $params Complete parameter array, indexed with placeholders.
*
*/
protected function setAndBindParameters(array $params)
{
// Ignore method call if we don't have parameters to process
if ($this->statement_object->param_count <= 0)
{
return;
}
$user_param_count = count($params);
$param_type_string = '';
if ($this->statement_object->param_count != $user_param_count)
{
throw new \RuntimeException("StatementWrapper error when setting and binding parameters. Argument count ({$user_param_count}) doesn't match needed parameter count ({$this->statement_object->param_count}).");
}
foreach ($this->params as $placeholder => $param)
{
if (!isset($params[$placeholder]))
{
throw new \RuntimeException("StatementWrapper error when setting and binding parameters. Required parameter '{$placeholder}' is not defined when trying to set parameter.");
}
$this->params[$placeholder] = $params[$placeholder];
}
$this->createParamTypeString();
$this->bindParam();
}
/**
* Fills parameter types string to the $references_param property.
*
* MySQLi_STMT::bind_param() requires us to specify parameter types
* when binding. Allowed parameter types are (as per 5.3.6):
*
* <code>
* i - integer
* d - double
* s - string
* b - blob (will be sent in packets)
* </code>
*
* This method detects if the parameter is integer or float (double)
* and defaults to string. To mark a parameter as blob, use class
* method markParamAsBlob().
*
* @see $references_params
* @see setAndBindParameters()
* @see markParamAsBlob()
*
*/
protected function createParamTypeString()
{
$this->references_params['types'] = '';
foreach ($this->params as $placeholder => $param)
{
if (in_array($placeholder, $this->blob_params))
{
$this->references_params['types'] .= 'b';
}
else if (is_integer($param))
{
$this->references_params['types'] .= 'i';
}
else if (is_float($param))
{
$this->references_params['types'] .= 'd';
}
else
{
$this->references_params['types'] .= 's';
}
}
}
/**
* Binds parameter references array using MySQLi_STMT::bind_param().
*
* This method is called each time the user provides new arguments.
* Assumes that parameter types string has already been generated.
*
* @see $references_params
* @see createParameterVariablesAndReferences()
*
*/
protected function bindParam()
{
call_user_func_array(array($this->statement_object, 'bind_param'), $this->references_params);
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Before reading the actually implementation:</strong></p>\n\n<p>What you doing is a <code>pdo</code>-like placeholder syntax with a <code>#</code> instead of a <code>:</code> and without the need to bind the parameters directly but only pass in a array.</p>\n\n<p>I can see the 'need' for something like this as binding parameters with pdo isn't quite what frameworks seems to want their users to do. <code>ZF, ezC/zetaC, SF</code> and so on to name samples.</p>\n\n<p>The <code>$statement</code> it's self is then able to <code>execute</code> and then <code>$row = $statement->fetch</code>.</p>\n\n<p>This strikes me as a little bit odd as most things that allow for <code>execution</code> also expect <code>prepare</code>ation when it comes to queries but thats just method naming.</p>\n\n<p>The statement is just one class acting as a query execution AND a result provider. That maybe could be splitted into two.</p>\n\n<h2>The implementation:</h2>\n\n<p><strong><code>__construct</code></strong></p>\n\n<p>You are doing <strong>quite</strong> a lot of work in the constructor. From a testing point that might be a problem, at least <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\" rel=\"nofollow\"><strong><code>misko disagrees with doing work in the constructor</code></strong></a>.</p>\n\n<blockquote>\n <p>mysqli_prepare() returns a statement object or FALSE if an error occurred.</p>\n</blockquote>\n\n<p>Check for that, not for <code>empty</code> and <code>is_a</code>. Also see: <code>instanceof</code> instead of is_a for that case.</p>\n\n<hr>\n\n<p><strong><code>execute</code></strong></p>\n\n<p><code>if(!empty($params))</code> for a <code>array</code> is equal to <code>if($params)</code></p>\n\n<p>and i don't like the \"how to do error handling switch\" if thats the base class of a framework. It should just work one way.. i guess. I can see the point of giving the user choice but then you should at least use return codes if you don't throw exceptions.</p>\n\n<p><strong><code>fetch*</code></strong></p>\n\n<p>The fetch functions feels like duplicate code</p>\n\n<p><strong><code>mysqli_stmt::attr_*</code></strong></p>\n\n<p>What's your usecase for those functions? Are those really needed?</p>\n\n<hr>\n\n<p>Apart from that the code seems kinda fine.. given how bad the <code>mysqli_stmt->bind*</code> functions are with their reliance on references. </p>\n\n<p>I haven't looked to deep into the <code>#foo param</code> replace logic but I'm not sure if <code>$this->statement_object->param_count != $placeholder_count</code> is the proper way to do error handling there. Can't i use the same placeholder twice? To i have to use all of them? If so why does it not make sure... and so on.</p>\n\n<p>Hoped that helped a little</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T14:07:03.577",
"Id": "4065",
"Score": "0",
"body": "thanks for the detailed review! Agreed on most part, Re the constructor: I agree that it looks bad, however - it doesn't do anything but initializing the class properties and instantiating the `MySQLi_STMT` class - agree on the `mysqli_prepare` and `fetch` duplicate code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T14:18:41.247",
"Id": "4066",
"Score": "0",
"body": "I wasn't sure on making a wrapper of `mysqli_stmt::attr_*` too, but I added it anyway since somebody might wanted to use it. I agree it's most likely YAGNI."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T14:19:44.747",
"Id": "4067",
"Score": "0",
"body": "@rick Well it does call `$this->statement_object = $mysqli->prepare($this->statement_string);` so it does quite a lot as it talks to the database at that point. Also sanitizing **could** be qualified as work too. I'm not too sure on that myself"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T13:40:44.237",
"Id": "2586",
"ParentId": "2583",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "2586",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T09:12:15.983",
"Id": "2583",
"Score": "2",
"Tags": [
"php",
"mysql",
"mysqli"
],
"Title": "MySQLi_STMT wrapper, allows placeholders"
}
|
2583
|
<p>I am trying to create a web app (CMS) as part of my research project, and I use the code below to load modules into a page. Please review this code.</p>
<pre><code>public function LoadModule($module,$position){
if(file_exists('modules/'.$module.'.tpl'))
{
//todo: might have to get a better thing for this !
$mod = 'modules/'.$module.'.tpl';
ob_start();
include($mod);
$mod = ob_get_clean();
$this->html = str_replace('__{'.$position.'}__', $mod ,$this->html);
}
else{
if(function_exists('LOGIT')){
LOGIT('$module - module not found.');
}
else {
$this->html = str_replace('__{'.$position.'}__', "$module Modlule not found" ,$this->html);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't know if it's a paste-issue, but you should intent your code ;)</p>\n\n<p>You are building the file-path twice. You should move that line:</p>\n\n<pre><code>$mod = 'modules/'.$module.'.tpl';\n</code></pre>\n\n<p>To the begining of the function (and give it a better name):</p>\n\n<pre><code>public function LoadModule($module,$position)\n{\n\n $absTemplatePath = 'modules/'.$module.'.tpl';\n if(file_exists($absTemplatePath ))\n {\n</code></pre>\n\n<p>That Line:</p>\n\n<pre><code>LOGIT('$module - module not found.');\n</code></pre>\n\n<p>should be (else <code>$module</code> wouldn't get replaced):</p>\n\n<pre><code>LOGIT(\"$module - module not found\");\n</code></pre>\n\n<p>If the template file does not include php-code you should use <code>file_get_contents</code> instead of <code>ob_start, include, ob_get_clean</code> (performance-wise). If you do have php-code in your templates, you might have a look at zend-framework's Zend_View.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T15:23:39.897",
"Id": "2589",
"ParentId": "2585",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "2589",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T13:09:14.573",
"Id": "2585",
"Score": "1",
"Tags": [
"php",
"php5"
],
"Title": "Loading module to a templated page"
}
|
2585
|
<p>I've been learning to program in Java and I decided to implement a doubly linked list as practice and as a bridge project before going on to learn C++. I know Java includes a <code>LinkedList</code> implementation, but I wrote this for practice. I have finished the code and it works correctly. However, I'd appreciate some feedback on style and things that I should do differently or not at all.</p>
<p>Also, note: I'm not really worried about a unified documentation style; I know it's a bit broken. I only added it out of courtesy to the people who may be reading my code. I'm more interested in feedback on my coding style.</p>
<p><strong><code>MyLinkedList</code></strong></p>
<pre><code>import java.util.NoSuchElementException;
public class MyLinkedList<T> {
protected MyNode<T> firstNode;
protected MyNode<T> lastNode;
protected int size;
/**
* Constructs a new Linked List
*/
public MyLinkedList() {
firstNode = new MyNode<T>();
lastNode = firstNode;
size = 0;
}
/**
* Adds an element to the linked list
*
* @param element
* to be added to linked list
*/
public void add(T content) {
if (size == 0)
firstNode.setContent(content);
else
lastNode = lastNode.spawnNode(content);
size++;
}
/**
* Adds an element to the beginning of the linked list
*
* @param content
* element to be added to linked list
*/
public void addFirst(T content) {
if (size == 0)
firstNode.setContent(content);
else {
MyNode<T> newFirst = new MyNode<T>(content);
MyNode<T> oldFirst = firstNode;
firstNode = newFirst;
newFirst.setNextNode(oldFirst);
oldFirst.setPreviousNode(newFirst);
}
size++;
}
/**
* Returns an arbitrary item from the linked list
*
* @param index
* Index of item to be retrieved from the linked list
* @return Item residing at index
*/
public T get(int index) {
return getNode(index).getContent();
}
/**
* Returns the first item in the linked list
*
* @return First item in the linked list
*/
public T getFirst() {
return firstNode.getContent();
}
/**
* Returns the last item in the linked list
*
* @return Last item in the linked list
*/
public T getLast() {
return lastNode.getContent();
}
/**
* Returns the node at a given index
* @param index Which node to retrieve
* @return Node at index
*/
private MyNode<T> getNode(int index) {
if (index < 0 || index >= size)
throw new NoSuchElementException(index < 0 ? "Negative index"
: "Index does not exist");
MyNode<T> which;
if (index <= size / 2) {
which = firstNode;
for (int i = 0; i < index; i++)
which = which.getNextNode();
} else {
which = lastNode;
for (int i = size - 1; i > index; i--)
which = which.getPreviousNode();
}
return which;
}
/**
* Inserts an element before an arbitrary point in the list
*
* @param index
* Index to element before
* @param content
* What to insert at index
*/
public void insertBefore(int index, T content) {
if (index == 0) {
addFirst(content);
return;
}
MyNode<T> currentOcc = getNode(index);
MyNode<T> prev = currentOcc.getPreviousNode();
MyNode<T> newGuy = new MyNode<T>(content);
newGuy.setNextNode(currentOcc);
newGuy.setPreviousNode(prev);
prev.setNextNode(newGuy);
currentOcc.setPreviousNode(newGuy);
size++;
}
/**
* Determines if the list is empty
*
* @return If the list is empty
*/
public boolean isEmpty() {
if (size == 0)
return true;
return false;
}
/**
* Removes the node (and consequently element) at index and "heals" the list
*
* @param index
* Location of element to be removed
*/
public void remove(int index) {
if (index == 0) {
removeFirst();
return;
}
if (index == size - 1) {
removeLast();
return;
}
MyNode<T> marked = getNode(index);
MyNode<T> before = marked.getPreviousNode();
MyNode<T> after = marked.getNextNode();
before.setNextNode(after);
after.setPreviousNode(before);
marked = null;
size--;
}
/**
* Removes first node (and consequently first element) from the list
*/
public void removeFirst() {
if (size != 1) {
@SuppressWarnings("unused")
MyNode<T> temp = firstNode;
firstNode = firstNode.getNextNode();
firstNode.setPreviousNode(null);
temp = null;
} else
firstNode.setContent(null);
size--;
}
/**
* Removes last node (and consequently last element) from the list
*/
public void removeLast() {
if (size != 1) {
@SuppressWarnings("unused")
MyNode<T> temp = lastNode;
lastNode = lastNode.getPreviousNode();
lastNode.setNextNode(null);
temp = null;
} else
lastNode.setContent(null);
size--;
}
/**
* Updates the content of a node
*
* @param index
* Location of node to update
* @param content
* New content for node
*/
public void set(int index, T content) {
getNode(index).setContent(content);
}
/**
* Returns size of node
*
* @return size of node
*/
public int size() {
return size;
}
}
</code></pre>
<p><strong><code>MyNode</code></strong></p>
<pre><code>public class MyNode<T> {
private T content;
private MyNode<T> nextNode;
private MyNode<T> previousNode;
/**
* Constructs a new node without adding content
*/
public MyNode() {
nextNode = null;
this.content = null;
previousNode = null;
}
/**
* Constructs a new node and sets its content
*
* @param content
* Content to occupy new node
*/
public MyNode(T content) {
nextNode = null;
this.content = content;
previousNode = null;
}
/**
* Returns this node
*
* @return This node
*/
public MyNode<T> get() {
return this;
}
/**
* Returns the content of the node
*
* @return The content of the node
*/
public T getContent() {
return content;
}
/**
* Returns the next node
*
* @return The next node
*/
public MyNode<T> getNextNode() {
return nextNode;
}
/**
* Returns the previous node
*
* @return The previous node
*/
public MyNode<T> getPreviousNode() {
return previousNode;
}
/**
* Determines if this is the last node
*
* @return If this is the last node
*/
public boolean isLast() {
if (nextNode == null)
return true;
return false;
}
/**
* Sets the content of this node
*
* @param content
* Content to be given to this node
*/
public void setContent(T content) {
this.content = content;
}
/**
* Sets the next node
*
* @param next
* The node to be defined as next
*/
public void setNextNode(MyNode<T> next) {
nextNode = next;
}
/**
* Sets the previous node
*
* @param previous
* Which node is to become the previous node
* @return the previous node
*/
public MyNode<T> setPreviousNode(MyNode<T> previous) {
previousNode = previous;
return previousNode;
}
/**
* Convenience method that creates a new node and links it after this node
*
* @precondition This is the last node in the list
* @param content
* @return
*/
public MyNode<T> spawnNode(T content) {
nextNode = new MyNode<T>(content);
nextNode.setPreviousNode(this);
return nextNode;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Firstly, MyNode isn't going to be used by any class outside of MyLinkedList. It would be better if you implemented it as a private class inside the same file as MyLinkedList. Its only purpose is as data storage for MyLinkedList, its not really an object in its own right.</p>\n\n<p>As part of that, I'd make all of member variables public and get rid of your getter/setter functions. The point of private access is to prevent outside code from mucking with it. But here the only code using MyNode's is MyLinkedList which is supposed to much with it. All those getters/setters just complicate the situation.</p>\n\n<pre><code>if (size == 0)\n firstNode.setContent(content);\nelse\n lastNode = lastNode.spawnNode(content);\n</code></pre>\n\n<p>Most people will say that you should always put { and } even in one line blocks. </p>\n\n<pre><code>public boolean isEmpty() {\n if (size == 0)\n return true;\n return false;\n}\n</code></pre>\n\n<p>Just use</p>\n\n<pre><code>return size == 0;\n</code></pre>\n\n<p>Its simpler and easier to read.</p>\n\n<pre><code> @SuppressWarnings(\"unused\")\n MyNode<T> temp = firstNode;\n firstNode = firstNode.getNextNode();\n firstNode.setPreviousNode(null);\n temp = null;\n</code></pre>\n\n<p>What you are you doing with temp? The warning is telling you that the code involving temp does nothing.</p>\n\n<p>In your constructor you create one empty node to start with, in several places in your code you have a special case to handle it by storing the first inserted value into that node. As far as I can tell you've managed to find all the case where its a problem. But there doesn't seem to be a good reason to do it that way.</p>\n\n<p>In general, your code is more complicated then it needs to be. For example you have both insertBefore and insertAfter. But insertAfter could have been implemented as <code>insertBefore(index + 1);</code> You have lots of different insert/remove methods when you really only want to have one. The others might be useful from an interface perspective, but they should all call into a single implementation. (Unless they can implement it way more efficiently)</p>\n\n<p>I suggest a method like the following</p>\n\n<pre><code>private link_together(MyNode<T> left, MyNode<T> right)\n{\n if(left != null)\n {\n left.next = right;\n }else{\n firstNode = right;\n }\n\n if(right != null)\n {\n right.previous = left;\n }else{\n lastNode = left;\n }\n}\n</code></pre>\n\n<p>This will link two nodes together. It will also handle the case where either of the nodes is null which means that the current node is either at the beginning or end of the list.</p>\n\n<p>Now insert becomes:</p>\n\n<pre><code> public void insertBefore(int index, T value)\n {\n Node<T> new_node = new Node<T>(value);\n Node<T> node_after = getNode(index);\n // if we are trying to insert at the end of the list\n // node_after will be null\n Node<T> node_before = node_after : node_after.previous : lastNode;\n link_together(node_before, new_node);\n link_together(new_node, node_after);\n size++;\n }\n</code></pre>\n\n<p>This function can be used to insert nodes anywhere in the list even at the beginning or end or in empty lists. In a similar way, remove also works.</p>\n\n<pre><code>public void remove(int index)\n{\n Node<T> node = getNode(index);\n Node<T> node_before = node.previous;\n Node<T> node_after = node.next;\n link_together(node_before, node_after);\n size--;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T06:25:48.413",
"Id": "4086",
"Score": "0",
"body": "Your `link_together` method seems to be wrong, it should be `if (left != null)` etc. Other than that a good review, +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T13:44:36.567",
"Id": "4093",
"Score": "0",
"body": "@Landel, that's what I get for doing code reviews on a language I don't use. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T18:43:00.493",
"Id": "4099",
"Score": "0",
"body": "Thank you. This is very helpful. It was a bit of a facepalm when I realized how badly I botched the isEmpty() method..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T18:55:38.343",
"Id": "4101",
"Score": "0",
"body": "I put the supressWarnings in because I need to store temp to set it to null after linking the list behind it. My research indicated that setting unneeded objects to null is a good way to \"hint\" to the Garbage Collector that the object is ready for deletion. Is this incorrect?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:25:31.210",
"Id": "4105",
"Score": "1",
"body": "@Techrocket9, you've misunderstood that advice. You have to set existing references to null. Creating a new reference and setting to that null does nothing. The garbage collector will keep an object alive as long as you can still access it. If you set all references to an object to null, then you can no longer access it and the GC can clean it up."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T22:53:32.813",
"Id": "2593",
"ParentId": "2588",
"Score": "10"
}
},
{
"body": "<p>I don't have much to add to Winston's post.</p>\n\n<pre><code>if (index < 0 || index >= size)\n throw new NoSuchElementException(index < 0 ? \"Negative index\"\n : \"Index does not exist\");\n</code></pre>\n\n<p>I'd handle both cases separate:</p>\n\n<pre><code>if (index < 0 ) throw new NoSuchElementException(\"Negative index\");\nif (index >= size) throw new NoSuchElementException(\"Index does not exist\");\n</code></pre>\n\n<p>Your <code>getNode</code> does three things and I'd extract getFromTail and getFromHead (as protected methods) for better <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">separation of concerns</a> and testability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T23:41:50.440",
"Id": "4082",
"Score": "0",
"body": "I'm of the opinion that you shouldn't test protected methods. I think you should only test the public interface of the object. The internal implementation including such things as heading from the beginning or end, shouldn't affect the test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T06:57:44.013",
"Id": "4087",
"Score": "0",
"body": "@Winston the main reason to extract is, that there are 2 different layers of abstraction in `getNode`. For testability: protected methods are \"public\" to inheriting classes, if inheritance is not intended one could use the `final` keyword. Then of course those methods are private and need not to be tested with blackbox tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T13:46:07.910",
"Id": "4094",
"Score": "0",
"body": "I agree that extracting those could be helpful. Just doing it in the name of testability I have trouble with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T18:44:47.437",
"Id": "4100",
"Score": "0",
"body": "I appreciate all the feedback. Thank's for your time and willingness to help me become a better programmer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T18:58:26.693",
"Id": "4102",
"Score": "0",
"body": "@Techrocket9 You're welcome :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T23:05:23.443",
"Id": "2594",
"ParentId": "2588",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "2593",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T14:44:57.623",
"Id": "2588",
"Score": "10",
"Tags": [
"java",
"linked-list"
],
"Title": "Remake of Java's doubly LinkedList"
}
|
2588
|
<p>Wondering if I could do this a little bit better. Currently, my DAL has a blank constructor that sets the connection string from the web.config.</p>
<pre><code>private string cnnString;
public DAL()
{
cnnString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
}
</code></pre>
<p>Then each method in here is mapped directly to a stored procedure, and they ALL look something like this:</p>
<pre><code>public bool spInsertFeedback(string name, string subject, string message)
{
int rows = 0;
SqlConnection connection = new SqlConnection(cnnString);
try
{
connection.Open();
SqlCommand command = new SqlCommand("[dbo].[spInsertFeedback]", connection);
command.CommandType = CommandType.StoredProcedure;
// params
SqlParameter messageName = new SqlParameter("@name", SqlDbType.VarChar);
messageName.Value = name;
SqlParameter messageSubject = new SqlParameter("@subject", SqlDbType.VarChar);
messageSubject.Value = subject;
SqlParameter messageText = new SqlParameter("@message", SqlDbType.VarChar);
messageText.Value = message;
// add params
command.Parameters.Add(messageName);
command.Parameters.Add(messageSubject);
command.Parameters.Add(messageText);
rows = command.ExecuteNonQuery();
}
catch
{
return (rows != 0);
}
finally
{
connection.Close();
}
return (rows != 0);
}
</code></pre>
<p>Obviously some return a <code>DataSet</code> or a list of an object or something, where as this one just returns whether or not any rows were affected.</p>
<p>However, each method does things this way, and I just feel like I have a lot of redundant code, and I'd like to simplify it. From the other classes, I'm calling the DAL like this:</p>
<pre><code>DAL dal = new DAL();
bool success = dal.spInsertFeedback(name, subject, message);
return Json(success);
</code></pre>
<p>Thanks guys.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T08:16:09.187",
"Id": "4117",
"Score": "0",
"body": "What language is this? Can you add a tag so it's obvious to people browsing the site?"
}
] |
[
{
"body": "<p>You could move your try / catch / return logic to a private method that takes an SqlCommand as a parameter.</p>\n\n<p>Also, since you are only using your finally block to close the connection, you might consider a using block instead: </p>\n\n<pre><code>private bool runSpCommand (SqlCommand command)\n{\n int rows = 0;\n\n using (SqlConnection connection = new SqlConnection(connectionString)) \n {\n connection.Open();\n command.Connection = connection;\n rows = command.ExecuteNonQuery();\n // connection closed on following line, even if there's an exception\n }\n\n return (rows != 0);\n\n}\n</code></pre>\n\n<p>I've omitted exception handling from this example, but it should be pretty clear. </p>\n\n<p>Also, in your calling code, you can do this:</p>\n\n<pre><code>// params \ncommand.Parameters.Add(\"@name\", SqlDbType.VarChar).Value = name;\ncommand.Parameters.Add(\"@subject\", SqlDbType.VarChar).Value = subject;\ncommand.Parameters.Add(\"@message\", SqlDbType.VarChar).Value = message; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T17:18:15.140",
"Id": "2592",
"ParentId": "2590",
"Score": "1"
}
},
{
"body": "<p>I would highly recommend using an ORM instead of writing your own DAL, and you'll be a much more productive programmer overall. NHibernate and Entity Framework are both good choices, or even Linq2Sql if it's a small project that's not performance critical. That way you can spend your time solving the problems that matter, not writing boilerplate code for \"plumbing\".</p>\n\n<p>It also opens the door to testability, which isn't possible with the code you've written; using an ORM you can substitute in-memory data structures or mocks in your unit tests to simulate the behavior of the database to the rest of your program. That's not really possible when you're using the <code>SqlClient</code> namespace directly and relying on stored procedures in your database.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T03:21:40.300",
"Id": "2596",
"ParentId": "2590",
"Score": "3"
}
},
{
"body": "<p>I would turn it into a generic method with this signature:</p>\n\n<pre><code>public bool ExecuteSp(string spName, List<MyParameter> parameters) {\n\n // ...\n\n SqlCommand command = new SqlCommand(spName, connection);\n\n // ...\n\n foreach(var p in parameters) {\n SqlParameter sqlParameter = new SqlParameter(p.Name, p.Type);\n sqlParameter.Value = p.Value;\n command.Parameters.Add(p); \n }\n // ...\n}\n</code></pre>\n\n<p>Using an ORM is much better of course.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T15:19:39.363",
"Id": "2606",
"ParentId": "2590",
"Score": "1"
}
},
{
"body": "<p>I would not recommend putting your dal code in a <code>try-catch</code> block. At least you should be logging or doing something about it, currently you're just returning false (or no value). If an exception occur, let it happen, or put a <code>try-catch</code> on the function that calls it. Remember that exceptions vary (did the db server stop? was the sql malformed? these all are different cases.)</p>\n\n<p>Using <code>using</code> is a better practice for all <code>IDisposable</code> objects, thus embrace it. If you run Visual Studio's code analysis tools (Ultimate Edition only I guess) it would also tell you to do so.</p>\n\n<p>My version of your code is similar to Jeff's (which I wanted to vote up but didn't have enough rep yet) with an exception, <code>SqlCommand</code> is also disposable and can/should be used with using block.</p>\n\n<pre><code>public bool spInsertFeedback(string name, string subject, string message)\n {\n int rows = 0;\n using (var connection = new SqlConnection(cnnString))\n {\n connection.Open();\n using (var command = new SqlCommand(\"[dbo].[spInsertFeedback]\", connection))\n {\n command.CommandType = CommandType.StoredProcedure;\n // params\n SqlParameter messageName = new SqlParameter(\"@name\", SqlDbType.VarChar);\n messageName.Value = name;\n SqlParameter messageSubject = new SqlParameter(\"@subject\", SqlDbType.VarChar);\n messageSubject.Value = subject;\n SqlParameter messageText = new SqlParameter(\"@message\", SqlDbType.VarChar);\n messageText.Value = message;\n\n // add params\n command.Parameters.Add(messageName);\n command.Parameters.Add(messageSubject);\n command.Parameters.Add(messageText);\n rows = command.ExecuteNonQuery();\n }\n }\n return (rows != 0);\n }\n</code></pre>\n\n<p>Also I would suggest you to use <code>connectionString</code> instead of <code>cnnString</code>, which is not a proper naming.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:07:25.610",
"Id": "2613",
"ParentId": "2590",
"Score": "4"
}
},
{
"body": "<pre><code> SqlConnection connection = new SqlConnection(cnnString);\n</code></pre>\n\n<p><strong>EDIT</strong> You can do this because the connections are pooled. As a result you won't open any more connections then necessary. Stylistically, I prefer passing around Connection objects, but that's your call.</p>\n\n<pre><code> catch\n {\n return (rows != 0);\n }\n</code></pre>\n\n<p>This is a very evil three lines of code. Firstly, you catch every sort of exception which is going to hide bugs. You'll never know if a particular exceptions happened. Secondly, you carry one pretty much ignoring the fact that the exception happened. This is very very bad. DO NOT DO THIS!</p>\n\n<pre><code> SqlCommand command = new SqlCommand(\"[dbo].[spInsertFeedback]\", connection);\n command.CommandType = CommandType.StoredProcedure;\n\n // params\n SqlParameter messageName = new SqlParameter(\"@name\", SqlDbType.VarChar);\n messageName.Value = name;\n SqlParameter messageSubject = new SqlParameter(\"@subject\", SqlDbType.VarChar);\n messageSubject.Value = subject;\n SqlParameter messageText = new SqlParameter(\"@message\", SqlDbType.VarChar);\n messageText.Value = message;\n\n // add params\n command.Parameters.Add(messageName);\n command.Parameters.Add(messageSubject);\n command.Parameters.Add(messageText);\n\n rows = command.ExecuteNonQuery();\n</code></pre>\n\n<p>I think what you really want is a simpler interface for this piece of the code. Something like:</p>\n\n<pre><code>SQLProcedureCall insertFeedback = new SQLProcedureCall(\"[dbo].[spInsertFeedback]\", connection);\ninsertFeedback.set(\"name\", name);\ninsertFeedback.set(\"subject\", subject);\ninsertFeedback.set(\"message\", message);\nreturn insertFeedback.Execute();\n</code></pre>\n\n<p>You should be able to easily define a class which implements that. That the duplication in your is effectively eliminated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T23:45:17.107",
"Id": "4108",
"Score": "0",
"body": "What's wrong with one connection per query? Since they all use the same conn string, connection pooling is done automatically at the SQL Server level."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T23:51:52.477",
"Id": "4109",
"Score": "0",
"body": "@Jeff Paulsen, hadn't considered that. I guess its just a stylistic preference to provide a SQLConnection object over a connection string to client code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T17:39:32.647",
"Id": "4136",
"Score": "0",
"body": "That global catch (for the method) doesn't really matter as long as the exception is logged. So it would depend on the OP whether he omitted exception logging for brevity or whether it really isn't there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T19:09:13.633",
"Id": "4138",
"Score": "0",
"body": "@Chris, not logging is the major problem. I think it better stylistically to only catch what we expect to happen. Anything else is probably a bug in our code and we should probably stop the entire request before we break something."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T23:26:20.537",
"Id": "2619",
"ParentId": "2590",
"Score": "1"
}
},
{
"body": "<p>The solution to replacing this code.... is to stop writing this code.</p>\n\n<p>These types of DALs are great targets for the rise of the Micro ORM. Including Dapper, Massive, Simple.Data, and PetaPoco to name a few.</p>\n\n<p>Personally I'm a fan of PetaPoco the most. It's available through Nuget. You have choices of Core or Full where Full includes T4 templates that allow you to generate models from your database (not for me but some people like this stuff) and Core (which is a dependency of the full package) facilitates all of your querying.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T17:37:25.533",
"Id": "2632",
"ParentId": "2590",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "2613",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T15:41:15.577",
"Id": "2590",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Data Access Layer Code"
}
|
2590
|
<p><strong>Overview</strong></p>
<p>I've written a class that will create C# code. The output is a single .cs file for each table in the default database (the database is defined inside a web.config file). I'm looking for a code review on this class alone, <em>not</em> on the generated code. This <code>DatabaseClassCreator</code> class uses the <code>DatabaseAccess</code> class for some of its database access. The <code>DatabaseAccess</code> class can be seen <a href="https://codereview.stackexchange.com/questions/2578/database-access-class">here</a> as I'm asking for a code review of that class as well. If you are not interested in seeing the <code>DatabaseAccess</code> class, there is one static method <code>ExecSQL</code>, which returns a single <code>DataTable</code> with the results of the passed SQL.</p>
<p>Two notes:</p>
<ol>
<li>This was developed and is being used for a ASP.NET project, which is the reason for the <code>BulletedList</code>.</li>
<li>This class has to work in a C# .NET 2 environment, so anything that's more modern would be interesting to me, but please note in your answer if the comments/feedback require a newer .NET version.</li>
</ol>
<p></p>
<pre><code>/// <summary>
/// This class will create c# class files to access spesific
/// tables in a database.
/// </summary>
public static class DatabaseClassCreator
{
/// <summary>
/// Create class files for all the non-system tables in the current
/// default database.
/// </summary>
/// <param name="OutputPath">The output location for the class files. This
/// is a fully qualified path.</param>
public static void CreateAllTables(string OutputPath)
{
BulletedList bl = new BulletedList();
CreateAllTables(bl, OutputPath);
}
/// <summary>
/// Create class files for all the non-system tables in the current
/// default database.
/// </summary>
/// <param name="StatusBulletList">A BulletedList where status information can be
/// added to.</param>
/// <param name="OutputPath">The output location for the class files. This
/// is a fully qualified path.</param>
public static void CreateAllTables(BulletedList StatusBulletList, string OutputPath)
{
DataTable table = ListDatabaseTables();
if (table == null)
{
ListItem liRowName = new ListItem();
liRowName.Text = "Database Error";
StatusBulletList.Items.Add(liRowName);
return;
}
// Loop through the tables and create the accessor classes
foreach (DataRow row in table.Rows)
{
if (row["TABLE_NAME"].ToString() != "syssegments" && row["TABLE_NAME"].ToString() != "sysconstraints")
{
ListItem liRowName = new ListItem();
liRowName.Text = row["TABLE_NAME"].ToString();
StatusBulletList.Items.Add(liRowName);
CreateSingleTable(StatusBulletList, OutputPath, row["TABLE_NAME"].ToString());
}
}
}
/// <summary>
/// Returns a DataTable containing all the table names in the default
/// database.
/// </summary>
/// <returns>DataTable listing the table names.</returns>
public static DataTable ListDatabaseTables()
{
string SQL;
DataTable table = null;
// Grab all the table names from the current database
SQL = "SELECT TABLE_NAME FROM information_schema.tables WHERE NOT TABLE_NAME='sysdiagrams' AND TABLE_SCHEMA = 'dbo' AND TABLE_TYPE= 'BASE TABLE'";
table = DatabaseAccess.ExecSQL(SQL);
return table;
}
/// <summary>
/// Output a class file for the requested table in the current default database
/// </summary>
/// <param name="OutputPath">The output location for the class files. This
/// is a fully qualified path.</param>
/// <param name="TableName">The table name</param>
public static void CreateSingleTable(string OutputPath, String TableName)
{
BulletedList bl = new BulletedList();
CreateSingleTable(bl, OutputPath, TableName);
}
/// <summary>
/// Output a class file for the requested table in the current default database
/// </summary>
/// <param name="OutputPath">The output location for the class files. This
/// is a fully qualified path.</param>
/// <param name="StatusBulletList">A BulletedList where status information can be
/// added to.</param>
/// <param name="TableName">The table name</param>
public static void CreateSingleTable(BulletedList StatusBulletList, string OutputPath, String TableName)
{
string SQL;
IDataReader reader = null;
DataTable schema = null;
List<TableFieldInfo> fields = new List<TableFieldInfo>();
// Grab the current table
SQL = "SELECT TOP 1 * FROM " + TableName;
reader = ExecSQLReader("", SQL);
// Get the table schema
if (reader != null)
schema = reader.GetSchemaTable();
// Grab the field information we need
if (schema != null)
{
foreach (DataRow myField in schema.Rows)
{
TableFieldInfo f = new TableFieldInfo();
f.name = myField["ColumnName"].ToString();
f.type = myField["ProviderSpecificDataType"].ToString();
f.allowNull = bool.Parse(myField["AllowDBNull"].ToString());
f.readOnly = bool.Parse(myField["IsReadOnly"].ToString());
f.maxSize = int.Parse(myField["ColumnSize"].ToString());
fields.Add(f);
string info = "---> " + f.name + " (" + f.type + ")";
if (f.readOnly)
info += " (RO)";
else
info += " (RW)";
if (f.allowNull)
info += " (Null)";
StatusBulletList.Items.Add(new ListItem(info));
}
}
else
{
ListItem liRowName = new ListItem();
liRowName.Text = "Schema Error";
StatusBulletList.Items.Add(liRowName);
}
// Clean the table name for the filesystem and c# names
TableName = TableName.Replace('(', '_').Replace(')', '_').Replace('~', '_'); ;
// Open the file
string filename = OutputPath + "\\DBT_" + TableName + ".cs";
StreamWriter sw = new StreamWriter(filename);
// Add File Comments
sw.WriteLine("// ");
sw.WriteLine("// This file is auto generated based on the database");
sw.WriteLine("// DO NOT MODIFY THIS FILE, EVER");
sw.WriteLine("// Inherit this class and make changes there");
sw.WriteLine("// DO NOT MODIFY THIS FILE, CHANGES WILL BE LOST");
sw.WriteLine("// ");
sw.WriteLine("");
// Add Using statements
sw.WriteLine("using System;");
sw.WriteLine("using System.Collections.Generic;");
sw.WriteLine("using System.Data;");
sw.WriteLine("using System.Data.SqlClient;");
sw.WriteLine("");
// Open the class
sw.WriteLine("public class DBT" + TableName + " : DatabaseAccess");
sw.WriteLine("{");
// Add accessors
foreach (TableFieldInfo f in fields)
{
if (getType(f.type) == "int")
sw.WriteLine("\tprivate " + getType(f.type) + " _" + f.name + " = -1;");
else if (getType(f.type) == "float")
sw.WriteLine("\tprivate " + getType(f.type) + " _" + f.name + " = -1;");
else if (getType(f.type) == "DateTime")
sw.WriteLine("\tprivate " + getType(f.type) + " _" + f.name + " = new DateTime(1753, 1, 1);");
else if (getType(f.type) == "byte[]")
sw.WriteLine("\tprivate " + getType(f.type) + " _" + f.name + " = new byte[1];");
else
sw.WriteLine("\tprivate " + getType(f.type) + " _" + f.name + ";");
sw.WriteLine("\tpublic " + getType(f.type) + " " + f.name);
sw.WriteLine("\t{");
sw.WriteLine("\t\tget { return _" + f.name + "; }");
string protect = "";
if (f.readOnly)
protect = "protected ";
if (f.maxSize == 0 || getType(f.type) != "string")
sw.WriteLine("\t\t" + protect + "set { _" + f.name + " = value; }");
else
{
sw.WriteLine("\t\t" + protect + "set");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\tif(value.Length <= " + f.maxSize.ToString() + ")");
sw.WriteLine("\t\t\t\t_" + f.name + " = value;");
sw.WriteLine("\t\t\telse");
sw.WriteLine("\t\t\t\t_" + f.name + " = value.Substring(0, " + (f.maxSize).ToString() + ");");
sw.WriteLine("\t\t}");
}
sw.WriteLine("\t}");
sw.WriteLine("");
}
// Add the Constructors
sw.WriteLine("\tprivate string _connectionString = \"\";");
sw.WriteLine("\tpublic DBT" + TableName + "()");
sw.WriteLine("\t{");
sw.WriteLine("\t}");
sw.WriteLine("");
sw.WriteLine("\tpublic DBT" + TableName + "(string ConnectionString)");
sw.WriteLine("\t{");
sw.WriteLine("\t\t_connectionString = ConnectionString;");
sw.WriteLine("\t}");
sw.WriteLine("");
sw.WriteLine("\tpublic DBT" + TableName + "(int itemID)");
sw.WriteLine("\t{");
sw.WriteLine("\t\tthis.Select(itemID);");
sw.WriteLine("\t}");
sw.WriteLine("");
sw.WriteLine("\tpublic DBT" + TableName + "(string ConnectionString, int itemID)");
sw.WriteLine("\t{");
sw.WriteLine("\t\t_connectionString = ConnectionString;");
sw.WriteLine("\t\tthis.Select(itemID);");
sw.WriteLine("\t}");
sw.WriteLine("");
// Add the insert method
StatusBulletList.Items.Add(new ListItem("<--- public void Insert()"));
sw.WriteLine("\tpublic void Insert()");
sw.WriteLine("\t{");
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true)
{
sw.WriteLine("\t\tif(_" + f.name + " != -1)");
sw.WriteLine("\t\t\treturn;");
sw.WriteLine("");
}
}
sw.Write("\t\tstring SQL = \"INSERT INTO " + TableName + " (");
int count = fields.Count;
foreach (TableFieldInfo f in fields)
{
count--;
if (f.readOnly != true)
{
string fieldName = f.name;
if (fieldName.ToUpper() == "DEFAULT")
fieldName = "[" + fieldName + "]";
if (count != 0)
sw.Write(fieldName + ", ");
else
sw.Write(fieldName);
}
}
sw.Write(") VALUES (");
count = fields.Count;
foreach (TableFieldInfo f in fields)
{
count--;
if (f.readOnly != true)
{
if (count != 0)
sw.Write("@" + f.name + ", ");
else
sw.Write("@" + f.name);
}
}
sw.WriteLine("); SELECT SCOPE_IDENTITY() AS ID;\";");
sw.WriteLine("\t\tList<SqlParameter> parms = new List<SqlParameter>();");
sw.WriteLine("\t\tDataTable table = null;");
sw.WriteLine("");
foreach (TableFieldInfo f in fields)
{
if (f.readOnly != true)
{
if (getType(f.type) == "DateTime")
{
sw.WriteLine("\t\tif(_" + f.name + " != new DateTime(1753, 1, 1))");
sw.WriteLine("\t\t\tparms.Add(new SqlParameter(\"@" + f.name + "\", _" + f.name + "));");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t\tparms.Add(new SqlParameter(\"@" + f.name + "\", null));");
}
else
{
sw.WriteLine("\t\tparms.Add(new SqlParameter(\"@" + f.name + "\", _" + f.name + "));");
}
}
}
sw.WriteLine("");
sw.WriteLine("\t\tif (_connectionString == \"\")");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\ttable = ExecSQL(SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\ttable = ExecSQL(_connectionString, SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\tif (table != null && table.Rows.Count == 1)");
sw.WriteLine("\t\t{");
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true)
sw.WriteLine("\t\t\t_" + f.name + " = int.Parse(table.Rows[0][\"ID\"].ToString());");
}
sw.WriteLine("\t\t}");
sw.WriteLine("\t}");
sw.WriteLine("");
// Add the update method
StatusBulletList.Items.Add(new ListItem("<--- public void Update()"));
sw.WriteLine("\tpublic void Update()");
sw.WriteLine("\t{");
sw.Write("\t\tstring SQL = \"UPDATE " + TableName + " SET ");
count = fields.Count;
foreach (TableFieldInfo f in fields)
{
count--;
if (f.readOnly != true)
{
string fieldName = f.name;
if (fieldName.ToUpper() == "DEFAULT")
fieldName = "[" + fieldName + "]";
if (count != 0)
sw.Write(fieldName + "=@" + f.name + ", ");
else
sw.Write(fieldName + "=@" + f.name + " ");
}
}
sw.Write("WHERE ");
foreach (TableFieldInfo f in fields)
{
string fieldName = f.name;
if (fieldName.ToUpper() == "DEFAULT")
fieldName = "[" + fieldName + "]";
if (f.readOnly == true)
sw.Write(fieldName + "=@" + f.name);
}
sw.WriteLine(";\";");
sw.WriteLine("\t\tList<SqlParameter> parms = new List<SqlParameter>();");
sw.WriteLine("");
foreach (TableFieldInfo f in fields)
{
if (getType(f.type) == "DateTime")
{
sw.WriteLine("\t\tif(_" + f.name + " != new DateTime(1753, 1, 1))");
sw.WriteLine("\t\t\tparms.Add(new SqlParameter(\"@" + f.name + "\", _" + f.name + "));");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t\tparms.Add(new SqlParameter(\"@" + f.name + "\", null));");
}
else
{
sw.WriteLine("\t\tparms.Add(new SqlParameter(\"@" + f.name + "\", _" + f.name + "));");
}
}
sw.WriteLine("");
sw.WriteLine("\t\tif (_connectionString == \"\")");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\tExecSQL(SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\tExecSQL(_connectionString, SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t}");
sw.WriteLine("");
// Add the select method
bool CanSelect = false;
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true && CanSelect == false)
{
StatusBulletList.Items.Add(new ListItem("<--- public bool Select(" + getType(f.type) + " " + f.name + ")"));
sw.WriteLine("\tpublic bool Select(" + getType(f.type) + " " + f.name + ")");
CanSelect = true;
}
}
if (CanSelect == true)
{
sw.WriteLine("\t{");
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true)
sw.WriteLine("\t\tstring SQL = \"SELECT * FROM " + TableName + " WHERE " + f.name + "=@" + f.name + "\";");
}
sw.WriteLine("\t\tList<SqlParameter> parms = new List<SqlParameter>();");
sw.WriteLine("");
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true)
{
sw.WriteLine("\t\tSqlParameter parm" + f.name + " = new SqlParameter(\"@" + f.name + "\", " + f.name + ");");
sw.WriteLine("\t\tparms.Add(parm" + f.name + ");");
}
}
sw.WriteLine("");
sw.WriteLine("\t\tDataTable table = null;");
sw.WriteLine("\t\tif (_connectionString == \"\")");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\ttable = ExecSQL(SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\ttable = ExecSQL(_connectionString, SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\tif (table != null && table.Rows.Count == 1)");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\tDataRow row = table.Rows[0];");
sw.WriteLine("");
foreach (TableFieldInfo f in fields)
{
if (getType(f.type) == "string")
sw.WriteLine("\t\t\t_" + f.name + " = row[\"" + f.name + "\"].ToString();");
else if (getType(f.type) == "int")
{
//sw.WriteLine("\t\t\t_" + f.name + " = int.Parse(row[\"" + f.name + "\"].ToString());");
sw.WriteLine("\t\t\tif(!int.TryParse(row[\"" + f.name + "\"].ToString(), out _" + f.name + "))");
sw.WriteLine("\t\t\t\t_" + f.name + " = -1;");
}
else if (getType(f.type) == "float")
{
//sw.WriteLine("\t\t\t_" + f.name + " = int.Parse(row[\"" + f.name + "\"].ToString());");
sw.WriteLine("\t\t\tif(!float.TryParse(row[\"" + f.name + "\"].ToString(), out _" + f.name + "))");
sw.WriteLine("\t\t\t\t_" + f.name + " = -1;");
}
else if (getType(f.type) == "bool")
{
//sw.WriteLine("\t\t\t_" + f.name + " = int.Parse(row[\"" + f.name + "\"].ToString());");
sw.WriteLine("\t\t\tif(!bool.TryParse(row[\"" + f.name + "\"].ToString(), out _" + f.name + "))");
sw.WriteLine("\t\t\t\t_" + f.name + " = false;");
}
else if (getType(f.type) == "DateTime")
{
sw.WriteLine("\t\t\tif(row[\"" + f.name + "\"].ToString() != \"\")");
sw.WriteLine("\t\t\t\tDateTime.TryParse(row[\"" + f.name + "\"].ToString(), out _" + f.name + ");");
sw.WriteLine("\t\t\telse");
sw.WriteLine("\t\t\t\t_" + f.name + " = new DateTime(1753, 1, 1);");
}
else if (getType(f.type) == "byte[]")
{
sw.WriteLine("\t\t\tif (row[\"Img\"].ToString() != \"\")");
sw.WriteLine("\t\t\t\t_" + f.name + " = (byte[])row[\"" + f.name + "\"];");
}
else
sw.WriteLine("\t\t\t//_" + f.name + " = row[\"" + f.name + "\"];");
}
sw.WriteLine("\t\t\treturn true;");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\treturn false;");
sw.WriteLine("\t\t}");
sw.WriteLine("\t}");
sw.WriteLine("");
}
// Add the SelectWhere method
StatusBulletList.Items.Add(new ListItem("<--- public static DataTable SelectWhere(string WhereClause, List<SqlParameter> parms)"));
sw.WriteLine("\tpublic static DataTable SelectWhere(string WhereClause, List<SqlParameter> parms)");
sw.WriteLine("\t{");
sw.WriteLine("\t\treturn SelectWhere(WhereClause, parms, \"\");");
sw.WriteLine("\t}");
sw.WriteLine("\tpublic static DataTable SelectWhere(string WhereClause, List<SqlParameter> parms, string connectionString)");
sw.WriteLine("\t{");
sw.WriteLine("\t\tstring SQL = \"SELECT * FROM " + TableName + " WHERE \" + WhereClause;");
sw.WriteLine("");
sw.WriteLine("\t\tDataTable table = null;");
sw.WriteLine("\t\tif (connectionString == \"\")");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\ttable = ExecSQL(SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\ttable = ExecSQL(connectionString, SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\treturn table;");
sw.WriteLine("\t}");
sw.WriteLine("");
// Add the delete method
if (CanSelect == true)
{
StatusBulletList.Items.Add(new ListItem("<--- public void Delete()"));
sw.WriteLine("\tpublic void Delete()");
sw.WriteLine("\t{");
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true)
{
sw.WriteLine("\t\tif(_" + f.name + " == -1)");
sw.WriteLine("\t\t\treturn;");
sw.WriteLine("");
}
}
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true)
sw.WriteLine("\t\tstring SQL = \"DELETE FROM " + TableName + " WHERE " + f.name + "=@" + f.name + "\";");
}
sw.WriteLine("\t\tList<SqlParameter> parms = new List<SqlParameter>();");
sw.WriteLine("");
foreach (TableFieldInfo f in fields)
{
if (f.readOnly == true)
{
sw.WriteLine("\t\tparms.Add(new SqlParameter(\"@" + f.name + "\", " + f.name + "));");
}
}
sw.WriteLine("");
sw.WriteLine("\t\tif (_connectionString == \"\")");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\tExecSQL(SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\tExecSQL(_connectionString, SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t}");
sw.WriteLine("");
}
// Add the Table method
StatusBulletList.Items.Add(new ListItem("<--- public static DataTable Table()"));
sw.WriteLine("\tpublic static DataTable Table()");
sw.WriteLine("\t{");
sw.WriteLine("\t\treturn Table(\"\");");
sw.WriteLine("\t}");
sw.WriteLine("\tpublic static DataTable Table(string connectionString)");
sw.WriteLine("\t{");
sw.WriteLine("\t\tstring SQL = \"SELECT * FROM " + TableName + ";\";");
sw.WriteLine("\t\tList<SqlParameter> parms = new List<SqlParameter>();");
sw.WriteLine("");
sw.WriteLine("\t\tif (connectionString == \"\")");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\treturn ExecSQL(SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t\telse");
sw.WriteLine("\t\t{");
sw.WriteLine("\t\t\treturn ExecSQL(connectionString, SQL, parms);");
sw.WriteLine("\t\t}");
sw.WriteLine("\t}");
// Close the class
sw.WriteLine("}");
// Close the file
sw.Close();
}
public static IDataReader ExecSQLReader(string DatabaseName, string SQL)
{
// Database access variables
Database database = null;
DbCommand command = null;
IDataReader reader = null;
try
{
if (DatabaseName != "")
database = DatabaseFactory.CreateDatabase(DatabaseName);
else
database = DatabaseFactory.CreateDatabase();
command = database.GetSqlStringCommand(SQL);
reader = database.ExecuteReader(command);
}
catch (Exception e)
{
// Remove stupid warning
Exception x = e;
e = x;
}
return reader;
}
private static string getType(string DBType)
{
string ret = DBType;
if (DBType == "System.Data.SqlTypes.SqlString")
ret = "string";
else if (DBType == "System.Data.SqlTypes.SqlInt16")
ret = "Int16";
else if (DBType == "System.Data.SqlTypes.SqlInt32")
ret = "int";
else if (DBType == "System.Data.SqlTypes.SqlFloat")
ret = "float";
else if (DBType == "System.Data.SqlTypes.SqlDouble")
ret = "float";
else if (DBType == "System.Data.SqlTypes.SqlDecimal")
ret = "float";
else if (DBType == "System.Data.SqlTypes.SqlBoolean")
ret = "bool";
else if (DBType == "System.Data.SqlTypes.SqlDateTime")
ret = "DateTime";
else if (DBType == "System.Data.SqlTypes.SqlByte")
ret = "byte";
else if (DBType == "System.Data.SqlTypes.SqlBinary")
ret = "byte[]";
return ret;
}
private class TableFieldInfo
{
public string name;
public string type;
public bool allowNull;
public bool readOnly;
public int maxSize;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T14:50:56.110",
"Id": "71597",
"Score": "0",
"body": "You probably want to be using T4 for this. http://msdn.microsoft.com/en-us/library/bb126445.aspx is a reasonable place to start."
}
] |
[
{
"body": "<p><strong>1)</strong> As already mentioned <strong>T4</strong> might be a better solution though I'm not sure whether it is available for earlier VS versions. </p>\n\n<p><strong>2)</strong> I would avoid using <code>string OutputPath</code> parameters, <code>Streams</code> are usually more handy. </p>\n\n<p><strong>3)</strong> Separate presentation and business logic code. Having <code>BulletedList</code> parameter in such a class seems to be completely wrong to me. </p>\n\n<p><strong>4)</strong> I think you should not even take this <code>BulletedList</code> (or anything similar) as parameter. This messages log is an <strong>output</strong> of your methods, not an <strong>input</strong>, so there is no point accepting it as parameter. Return it and remove method overloads which are not needed. </p>\n\n<p><strong>5)</strong> <strong>Naming convention</strong> - usual rules are lower camel case for parameters. </p>\n\n<p><strong>6)</strong> Define variables closer to their first assignment and do not assign them any value if this value will be overwritten anyway. This is mostly about <code>CreateSingleTable</code> method. <code>ListDatabaseTables</code> also has 5 lines of code instead of maximum 3 needed. </p>\n\n<p><strong>7)</strong> I would make <code>ListDatabaseTables()</code> method more strongly typed. Returning a <code>DataTable</code> gives me absolutely no idea how to use it. </p>\n\n<p><strong>8)</strong> I prefer writing such constructions: </p>\n\n<pre><code> if (f.readOnly)\n info += \" (RO)\";\n else\n info += \" (RW)\";\n</code></pre>\n\n<p>as: </p>\n\n<pre><code>info += f.readOnly ? \" (RO)\" : \" (RW)\";\n</code></pre>\n\n<p>This IMO shows more clearly that you're going to append <em>something</em> to <code>info</code> <strong>anyway</strong> and this <em>something</em> depends on <code>isReadonly</code> value. </p>\n\n<p><strong>9)</strong> I would replace this: </p>\n\n<pre><code>string info = \"---> \" + f.name + \" (\" + f.type + \")\";\nif (f.readOnly)\n info += \" (RO)\";\nelse\n info += \" (RW)\";\nif (f.allowNull)\n info += \" (Null)\"; \n</code></pre>\n\n<p>with this: </p>\n\n<pre><code>string info = string.Format(\"---> {0} ({1}) ({2}){3}\"\n , f.name\n , f.type\n , f.readOnly? \"RO\" : \"RW\"\n , f.allowNull ? \" (NULL)\" : string.Empty); \n</code></pre>\n\n<p>This shows more clearly which format will <code>info</code> variable have. Also this has only one assignment which is better than doing <code>+=</code> on string several times. </p>\n\n<p><strong>10)</strong> <code>sw.WriteLine(\"// Inherit this class and make changes there\");</code> I would prefer extending existing class instead of inheritance. Or at least you should <strong>allow</strong> extending it. In order to allow this generated classes are usually defined as <code>partial</code>. </p>\n\n<p><strong>11)</strong> A lot of repeats here: </p>\n\n<pre><code> if (getType(f.type) == \"int\")\n sw.WriteLine(\"\\tprivate \" + getType(f.type) + \" _\" + f.name + \" = -1;\");\n else if (getType(f.type) == \"float\")\n sw.WriteLine(\"\\tprivate \" + getType(f.type) + \" _\" + f.name + \" = -1;\");\n else if (getType(f.type) == \"DateTime\")\n sw.WriteLine(\"\\tprivate \" + getType(f.type) + \" _\" + f.name + \" = new DateTime(1753, 1, 1);\");\n else if (getType(f.type) == \"byte[]\")\n sw.WriteLine(\"\\tprivate \" + getType(f.type) + \" _\" + f.name + \" = new byte[1];\");\n else\n sw.WriteLine(\"\\tprivate \" + getType(f.type) + \" _\" + f.name + \";\");\n</code></pre>\n\n<p>It should be separated into at least two blocks: </p>\n\n<p><strong>a)</strong> write <code>private</code> + <code>type</code><br>\n<strong>b)</strong> determine default value and write it (if any) </p>\n\n<p><strong>12)</strong> You have <code>new DateTime(1753, 1, 1);</code> repeated several times in your code. I would consider this string as magic string and I think it should be extracted into constant. </p>\n\n<p><strong>13)</strong> <code>fieldName.ToUpper() == \"DEFAULT\"</code>. <code>string.Equals(...)</code> has a parameter to ignore case. </p>\n\n<p><strong>14)</strong> You have just written your own <code>string.Join(...)</code> here: </p>\n\n<pre><code> count = fields.Count;\n foreach (TableFieldInfo f in fields)\n {\n count--;\n if (f.readOnly != true)\n {\n if (count != 0)\n sw.Write(\"@\" + f.name + \", \");\n else\n sw.Write(\"@\" + f.name);\n }\n }\n</code></pre>\n\n<p><strong>15)</strong> <code>if (f.readOnly == true && CanSelect == false)</code> I do not think this is the case when <code>bool</code> variable should be compared against <code>true</code> or <code>false</code>. I would prefer <code>if (f.readOnly && !CanSelect)</code> </p>\n\n<p><strong>16)</strong> Do not write god methods/classes and do not instantiate god objects. <code>CreateSingleTable</code> is definitely a god method - it has almost 500 lines of code !!! Raptors will come for you as soon as they will finish with <code>goto</code> writers. Break down this method into ~5-10 smaller methods. </p>\n\n<p><strong>17)</strong></p>\n\n<pre><code>private static string getType(string DBType)\n{\n string ret = DBType;\n\n if (DBType == \"System.Data.SqlTypes.SqlString\")\n ret = \"string\";\n else if (DBType == \"System.Data.SqlTypes.SqlInt16\")\n ret = \"Int16\";\n else if (DBType == \"System.Data.SqlTypes.SqlInt32\")\n ret = \"int\";\n else if (DBType == \"System.Data.SqlTypes.SqlFloat\")\n ret = \"float\";\n else if (DBType == \"System.Data.SqlTypes.SqlDouble\")\n ret = \"float\";\n else if (DBType == \"System.Data.SqlTypes.SqlDecimal\")\n ret = \"float\";\n else if (DBType == \"System.Data.SqlTypes.SqlBoolean\")\n ret = \"bool\";\n else if (DBType == \"System.Data.SqlTypes.SqlDateTime\")\n ret = \"DateTime\";\n else if (DBType == \"System.Data.SqlTypes.SqlByte\")\n ret = \"byte\";\n else if (DBType == \"System.Data.SqlTypes.SqlBinary\")\n ret = \"byte[]\";\n\n return ret;\n}\n</code></pre>\n\n<p>Instead of such constructions I usually use collections which contain mappings between input condition and desired result. I would replace your 10 conditions with this: </p>\n\n<pre><code>Dictionary<string, string> dbTypeToDotNetTypeMappings =\n new Dictionary<string, string>();\n\ndbTypeToDotNetTypeMappings.Add(\"System.Data.SqlTypes.SqlString\", \"string\");\n// ... \ndbTypeToDotNetTypeMappings.Add(\"System.Data.SqlTypes.SqlBinary\", \"byte[]\");\n\nstring mappedType;\nif (dbTypeToDotNetTypeMappings.TryGetValue(dbType, out mappedType))\n return mappedType;\n\nreturn dbType;\n</code></pre>\n\n<p>This shows more clearly the fact that you have a lot of similar <code>input->output</code> transformations. Also it allows moving this conditions out of the code, to the configuration file for example. </p>\n\n<p><strong>18)</strong> <code>getType()</code> should be more strongly typed. It has to be <code>Type -> Type</code> mapping instead of <code>string -> string</code>.</p>\n\n<p><strong>19)</strong> </p>\n\n<pre><code> catch (Exception e)\n {\n // Remove stupid warning\n Exception x = e;\n e = x;\n }\n</code></pre>\n\n<p>The best way to get rid of warning is logging the exception. Otherwise use <code>#pragma</code>: </p>\n\n<pre><code>#pragma warning disable 168\n catch (Exception e)\n#pragma warning restore 168\n {\n\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:10:41.557",
"Id": "78009",
"Score": "1",
"body": "For point 19, you could do `catch (Exception)` if you do not need the variable `e`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:17:04.447",
"Id": "2614",
"ParentId": "2595",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "2614",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-24T23:42:18.570",
"Id": "2595",
"Score": "9",
"Tags": [
"c#",
"sql",
".net",
"asp.net",
".net-2.0"
],
"Title": "Database Class Creator"
}
|
2595
|
<p>Haskell is a purely functional programming language with strict static type checking and lazy evaluation. The combination of functional programming and static type checking allows rapid development of bug free and correct programs. The absence of side effects allows Haskell programs to be parallelized more easily than other programming languages. The main compiler is GHC, which is an open source product of more than twenty years of cutting edge research. Haskell also has strong support for integration with other languages, built-in concurrency and parallelism, debuggers, profilers, rich libraries, and an active community. Haskell makes it easier to produce flexible, maintainable high-quality software.</p>
<h2>Getting started</h2>
<ol>
<li>Download the <a href="http://hackage.haskell.org/platform/" rel="nofollow">Haskell Platform</a> for your platform. This includes the state-of-the-art Glasgow Haskell Compiler (GHC) and common developer tools and libraries.</li>
<li>Check out these Stack Overflow questions with links to popular websites, books, and tutorials:
<ul>
<li><a href="http://stackoverflow.com/questions/1012573/how-to-learn-haskell">How to learn Haskell</a></li>
<li><a href="http://stackoverflow.com/questions/16918/beginners-guide-to-haskell">Beginners Guide to Haskell?</a></li>
<li><a href="http://stackoverflow.com/questions/33264/book-recommendation-for-haskell">Book recommendation for Haskell?</a></li>
</ul></li>
<li>Have fun, and ask questions!</li>
</ol>
<h2>Community</h2>
<p>Other places for discussing Haskell, beyond the question & answer format of Stack Exchange sites:</p>
<ul>
<li><a href="http://haskell.org/" rel="nofollow">Haskell.org</a></li>
<li><a href="http://haskell.org/haskellwiki/Mailing_lists" rel="nofollow">Mailing lists</a></li>
<li><a href="http://www.reddit.com/r/haskell/" rel="nofollow">Haskell Reddit</a></li>
<li><a href="http://haskell.org/haskellwiki/IRC_channel" rel="nofollow">#haskell on freenode</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T04:05:14.110",
"Id": "2597",
"Score": "0",
"Tags": null,
"Title": null
}
|
2597
|
Haskell is a purely functional programming language, featuring static typing, lazy evaluation, and monadic effects. The primary implementation is GHC, a high-performance compiler with a runtime supporting many forms of parallelism and concurrency.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T04:05:14.110",
"Id": "2598",
"Score": "1",
"Tags": null,
"Title": null
}
|
2598
|
<p>I have two tables, one for jobs, and one for the names of industries (e.g. automotive, IT, etc).</p>
<p>In SQL I would just do:</p>
<pre><code>SELECT industryName, count(*)
FROM jobs
JOIN industry
ON jobs.industryId = industry.id
GROUP BY industryName
</code></pre>
<p>In LINQ I have the following, but it's three separate statements and I'm pretty sure this would be doable in one.</p>
<pre><code>var allIndustries =
from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
select i.industryName;
var industriesWithCount =
from i in allIndustries
group i by i into iGrouped
select new { Industry = iGrouped.Key, Count = iGrouped.Count() };
var industries = new Dictionary<string, int>();
foreach (var ic in industriesWithCount)
{
industries.Add(ic.Industry, ic.Count);
}
</code></pre>
<p>Is there a way to make this simpler or shorter?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T10:16:45.540",
"Id": "4089",
"Score": "0",
"body": "R u using Entity Framework to Linq to SQL?"
}
] |
[
{
"body": "<p>Your <code>j</code> and <code>i</code> variables are pretty plain and won't make this code fun to maintain (especially if it were a big block of code) </p>\n\n<p>You should use more descriptive variables.</p>\n\n<p>you should create a collection that groups the Jobs by their Industry and then select from that collection the industry name and the count of jobs in the collection with that name.</p>\n\n<pre><code>from job in dbConnection.jobs\njoin industry in dbConnection.industries on job.industryId equals industry.id\ngroup new {industry, job} by industry.Name\ninto jobsByIndustry\n\nselect new {\n industryName = jobsByIndustry.Key.Name,\n jobscount = jobsByIndustry.Count()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T14:05:25.163",
"Id": "47480",
"ParentId": "2599",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T05:01:46.870",
"Id": "2599",
"Score": "20",
"Tags": [
"c#",
"linq"
],
"Title": "LINQ to SQL Joining Entities"
}
|
2599
|
<p>I am trying to create some (I believe these are Integration not Unit) tests for code that interacts with a database and I am not sure this is the right approach.</p>
<p>I would appreciate any reviews and possible improvements.</p>
<p>Using: <strong>VS2010 Unit Testing Framework</strong></p>
<p>This is the function I want to test:</p>
<pre><code>public IDbConnection OpenThirdPartyDatabase(string path, string password)
{
var provider = GetProvider(path, password);
return DBObjectFactory.GetObject().GetConnection(provider.Name, true, true);
}
</code></pre>
<p>Functions used by <code>OpenThirdPartyDatabase</code></p>
<pre><code>private static IDBProvider GetProvider(string path, string password)
{
var providers = DBProviders.GetObject();
var providerExists = providers.Cast<IDBProvider>().Any(dbProvider => dbProvider.Name == "MyProviderName");
return providerExists ? providers.GetDBProvider("MyProviderName") : CreateProvider(path, password);
}
private static IDBProvider CreateProvider(string path, string password)
{
IDBProvider provider = new DBAccessProvider("MyProviderName", path, "", password);
DBProviders.GetObject().Add(provider);
return provider;
}
public IDbConnection GetConnection(string ProviderName, bool OpenConnection, bool UseConnectionPool)
{
IDBProvider dbProvider = DBProviders.GetObject().GetDBProvider(ProviderName);
if (dbProvider == null)
throw new UndeclaredDBProviderException(ProviderName);
else
{
IDbConnection newConnection = null;
if ((connectionPool.ContainsConnection(ProviderName)) && (UseConnectionPool))
newConnection = connectionPool.GetConnection(ProviderName);
else
{
newConnection = dbProvider.GetConnection();
if (UseConnectionPool)
connectionPool.AddConnection(ProviderName, newConnection);
}
if ((OpenConnection) && (newConnection.State == ConnectionState.Closed))
newConnection.Open();
return newConnection;
}
}
</code></pre>
<p><strong>Tests:</strong></p>
<pre><code>/// <summary>
/// Test Connection with valid path and password
/// </summary>
[TestMethod]
public void ThirdPartyConnection_Valid()
{
var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("Data\\test.mdb", "pass");
Assert.AreNotEqual(testConnection, null);
}
/// <summary>
/// Test Connection With Invalid Password
/// </summary>
[TestMethod]
[ExpectedException(typeof(OleDbException),"Not a valid password.")]
public void ThirdPartyConnection_ShouldThrowOleDbException_InvalidPassword()
{
var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("Data\\test.mdb", "invalidpassword");
}
/// <summary>
/// Test Connection with invalid path
/// </summary>
[TestMethod]
[ExpectedException(typeof(OleDbException))]
public void ThirdPartyConnection_ShouldThrowOleDbException_InvalidPath()
{
var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("InvalidPath\\Data\\test.mdb", "pass");
}
/// <summary>
/// Test Connection String
/// </summary>
[TestMethod]
public void ThirdPartyConnection_ConnectionString()
{
var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("Data\\test.mdb", "pass");
Assert.AreEqual(testConnection.ConnectionString,"Expected Connection String","Not expected Connection String");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T13:36:07.550",
"Id": "18150",
"Score": "0",
"body": "Integration tests are a scam ...\nvideo => http://www.infoq.com/presentations/integration-tests-scam\ntext => http://www.infoq.com/news/2009/04/jbrains-integration-test-scam"
}
] |
[
{
"body": "<p>I don't claim to be an expert, but here's my experience.</p>\n\n<p>Apart from that i see you are using a constant string <em>\"MyProviderName\"</em> in your code and you would do well to move that to a const string for easy refactoring and future changes.</p>\n\n<p>Also i suggest you use the more common <strong>\"ArgumentNullException\"</strong> vs creating your own custom <strong>\"UndeclaredDBProviderException\"</strong> as you want to capture that a null parameter was passed to the function.</p>\n\n<p>I would also suggest you run the code through FxCop and fix any errors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T04:14:20.717",
"Id": "2645",
"ParentId": "2601",
"Score": "3"
}
},
{
"body": "<p>Your test code looks very reasonable. KRam's comments are also appropriate, but I think you are definitely on the right track.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-16T21:00:27.130",
"Id": "3483",
"ParentId": "2601",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T09:40:36.943",
"Id": "2601",
"Score": "6",
"Tags": [
"c#",
".net",
"unit-testing"
],
"Title": "Unit (Integration) Test for code that interacts with a database"
}
|
2601
|
<p>I have a database that I need to query over and over as fast as possible. My queries execute pretty quickly, but there seems to be some additional lag. I have a feeling that this lag is due to the fact that I am initiating and de-initiating a connection the connection each time. Is there a way to avoid this?</p>
<p>I am not using libmysql (at least, not directly). I am using the "mysql50" package in Lazarus/FreePascal (similar to Delphi), which in turn uses libmysql (I think).</p>
<p>The purpose of this library is to pass along a query sent from MQL4 (a propitiatory C-like language for the financial exchange market), and return a single row from my MySQL database (to which it connects through a pipe).</p>
<p>I would really appreciate if someone took a look at my code and pointed out (or maybe even fixed) some inefficiencies.</p>
<pre><code>{$CALLING STDCALL}
library D1Query;
{$mode objfpc}{$H+}
uses
cmem,
Windows,
SysUtils,
profs_win32exceptiontrap,
mysql50;
var
sock: PMYSQL;
qmysql: st_mysql;
type
VArray = array[0..100] of Double;
PArray = ^VArray;
procedure InitSQL; stdcall;
begin
mysql_init(PMySQL(@qmysql));
sock :=
mysql_real_connect(PMysql(@qmysql), '.', 'root', 'password', 'data', 3306, 'mysql', CLIENT_MULTI_STATEMENTS);
if sock = nil then
begin
OutputDebugString(PChar(' Couldn''t connect to MySQL.'));
OutputDebugString(PChar(mysql_error(@qmysql)));
halt(1);
end;
end;
procedure DeInitSQL; stdcall;
begin
mysql_close(sock);
end;
function SQL_Query(QRY: PChar; output: PArray): integer; stdcall;
var
rowbuf: MYSQL_ROW;
recbuf: PMYSQL_RES;
i: integer;
nfields: LongWord;
begin
InitSQL();
if (mysql_query(sock, QRY) < 0) then
begin
OutputDebugString(PChar(' Query failed '));
OutputDebugString(PChar(' ' + mysql_error(sock)));
end;
recbuf := mysql_store_result(sock);
nfields := mysql_num_fields(recbuf);
rowbuf := mysql_fetch_row(recbuf);
if (rowbuf <> nil) then
begin
for i:=0 to nfields-1 do
output^[i] := StrToFloatDef(rowbuf[i], -666);
end;
mysql_free_result(recbuf);
DeInitSQL();
Result := i;
end;
exports
SQL_Query,
InitSQL,
DeInitSQL;
begin
end.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T09:54:33.327",
"Id": "4154",
"Score": "1",
"body": "I don't know Pascal but it's for sure the best to keep the connection open, especially if you have many queries to execute. It adds much overhead to one query."
}
] |
[
{
"body": "<p>The most important thing here is not to create and destroy the connection as part of executing your query. Force the calling code to create the connection first (or create it yourself if its not done) but dont destroy the connection until the library is unloaded. That should improve speed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T20:26:27.027",
"Id": "4458",
"ParentId": "2604",
"Score": "3"
}
},
{
"body": "<p>Since you're calling InitSQL() and DeInitSQL() inside SQL_QUERY function, each time you call SQL_QUERY you actually create the connection and destroy it. This causes an I/O overhead in the database. Add another parameter to SQL_QUERY isLastStmt and send true with the last statement to destroy \n <code>if isLAstStmt then DeInitSQL();</code></p>\n\n<p>Also add <code>if sock = nil then</code> just after the line <code>mysql_init(PMySQL(@qmysql));</code>\nin the InitSQL() procedure. This way if sock is nil the connection will be made. And considering the first step I mentioned about the destroy operation, the connection will be closed after execution of the last statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T19:37:38.150",
"Id": "25506",
"ParentId": "2604",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T12:55:18.253",
"Id": "2604",
"Score": "6",
"Tags": [
"mysql",
"pascal"
],
"Title": "Querying MySQL from an external application"
}
|
2604
|
<pre><code>long long combine(unsigned int high, unsigned int low) {
return ((unsigned long long) high) << 32 || low;
}
</code></pre>
<ol>
<li>Is there a better name for the operation?</li>
<li>Is the implicit cast from <code>unsigned long long</code> to <code>long long</code> a <code>reinterpret_cast</code>, or what happens if the <code>unsigned</code> number is too large for the <code>signed</code> data type?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T18:15:20.607",
"Id": "4097",
"Score": "6",
"body": "Also, note that you should be using a bitwise or operator `|` rather than a logical or operator `||`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T18:18:13.140",
"Id": "4098",
"Score": "0",
"body": "Irk! Obviously. Thanks you for spotting it. :)"
}
] |
[
{
"body": "<p>You should return <code>unsigned long long</code> and let the user decide what they want to do with the cast, especially if you want this to be generic.</p>\n\n<p>I'd prefer a name such as <code>u32tou64</code>, <code>uinttoull</code>, or something more descriptive than combine. A lot of this will depend on your own naming standards, though.</p>\n\n<p>Also, I'd consider being more pedantic:</p>\n\n<pre><code>return (((uint64_t) high) << 32) | ((uint64_t) low);\n</code></pre>\n\n<p>It's unlikely to make a difference because the code is essentially the same as yours, but it's easier to read and avoids extremely rare (but very troublesome to debug) casting issues. It may require a custom types header if your compiler doesn't support this type notation.</p>\n\n<p>Also, consider making it a macro. There's little benefit to having it as a function - the operation itself will take far less time than the function call setup, call, and return, so the performance of a macro will be much higher. Further, it isn't going to take up much more program space than a function call, so there's little to gain by leaving it a real function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T17:51:54.080",
"Id": "4095",
"Score": "1",
"body": "Also, it's quite possible that a union could be a more efficient way of doing this than a shift, although I would hope that most optimizing compilers make the distinction meaningless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T18:05:06.477",
"Id": "4096",
"Score": "2",
"body": "Thanks. I refrained from using unions because MS discourages them for alignment reasons (http://msdn.microsoft.com/en-us/library/ms724284%28v=VS.85%29.aspx, \"Remarks\", 3rd paragraph). An optimizing compiler should also inline my function. But thanks for the suggestion, I'll probably make it a macro anyways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T23:53:39.530",
"Id": "4110",
"Score": "7",
"body": "Since this is C++, an inline function should be pretty much the same as a macro."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T23:04:53.743",
"Id": "4172",
"Score": "0",
"body": "You should not be using UINT64, its so unportable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T02:39:17.370",
"Id": "4181",
"Score": "0",
"body": "@mathepic I always use a typesdef.h file or similar anyway. What typenames do you suggest are more portable for those that don't?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T06:51:30.733",
"Id": "4234",
"Score": "0",
"body": "@Adam Use `uint64_t` from `stdint.h` (a standard C99 header)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-21T16:10:13.577",
"Id": "205436",
"Score": "0",
"body": "This answer didn't say it explicitly, but it implies that `unsigned int` should be `uint32_t`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T17:47:51.710",
"Id": "2608",
"ParentId": "2607",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "2608",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T16:24:31.347",
"Id": "2607",
"Score": "8",
"Tags": [
"c++",
"integer",
"bitwise"
],
"Title": "Combining two 32-bit integers into one 64-bit integer"
}
|
2607
|
<p>I have a JSON object which holds some json_array like this: (with org.codehaus.jettison.json.*)</p>
<pre><code>json array:[{"C1":["S1","S2"]},{"C2":["S1","S2"]},{"C3":["S1","S2"]},{"C4":["S1","S2"]}]
</code></pre>
<p>I have to get two list,one for keys,another for the elements of each key.I have done like this:</p>
<pre><code>//sample: clusterIdList:[C1, C2, C3, C4] and serviceIdList:[S1, S2, S1, S2, S1, S2, S1, S2]
//get jsonarray by key = serviceCode
JSONArray array = incident.getJSONArray("serviceCode");
List<String> clusterIdList = new ArrayList<String>();
List<String> serviceIdList = new ArrayList<String>();
String key="";
for (int i = 0,length=array.length(); i < length; i++) {
JSONObject b = array.getJSONObject(i);
key = b.names().getString(0);
clusterIdList.add(key);
JSONArray sublist = b.getJSONArray(key);
for (int j = 0,sublistLength = sublist.length(); j < sublistLength; j++) {
serviceIdList.add(sublist.getString(j));
}
}
</code></pre>
<p>Is this a proper way to do this? or can it be improved? I am trying to improve my code quality and readability.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T10:19:46.057",
"Id": "4124",
"Score": "0",
"body": "Looks fine to me. The only thing I'd suggest is to move the declaration of the variable `key` into the loop: `String key = b.names().getString(0);`"
}
] |
[
{
"body": "<p>This can be argued, but I think you can write directly <code>i < array.length();</code> without noticeable slowdown (if length() does the right thing and is just a getter of a field). Makes the loop slightly more readable, IMHO. Or at least add spaces: <code>int i = 0, length = array.length();</code></p>\n\n<p>I had a glance at the Jettison site, and couldn't find a JavaDoc page. But if JSONArray implements the Iterable interface, you can use the foreach syntax, even more readable.</p>\n\n<p>I agree with the comment of RoToRa, too.</p>\n\n<p>Otherwise, code looks OK.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T11:40:41.157",
"Id": "2760",
"ParentId": "2609",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T19:10:31.110",
"Id": "2609",
"Score": "5",
"Tags": [
"java",
"json"
],
"Title": "Is there another way / proper way of parsing this JSON array ?"
}
|
2609
|
<p>I'm writing a file I/O DLL in C++ which is going to be used from VB6. The interface is already fixed, and uses INT64/Currency as the general integer data type.</p>
<p>Now I have this function:</p>
<pre><code>extern "C" LPWIN32_FIND_DATAW ZFILEIO_API GetFileInfoByIndex(INT64 index) {
return total_size >= 0
&& index <= file_vec->size()
&& index >= 0
? &file_vec->at(index)
: NULL;
}
</code></pre>
<p>where <code>file_vec</code> is of type <code>std::vector<WIN32_FIND_DATAW></code>. Its <code>at</code> member function takes a <code>size_t</code> argument, which is in my case an unsigned 32-bit integer. Therefore, MSVC++2010 warns me of possible data loss. I think nothing can happen in my code, but please correct me if I'm wrong. Also, do you know a method to avoid the warning (without shutting it off for other places in my code)?</p>
<p>And then there's another question; I would like to return the <code>WIN32_FIND_DATAW</code> struct by value, not as a pointer, but that's not possible because then I can't return NULL for illegal requests. Can I return such a pointer to my internal data to a VB6 application?</p>
|
[] |
[
{
"body": "<pre><code>#pragma warning(disable:4xxx)\nyourcode();\n#pragma warning(default:4xxx)\n</code></pre>\n\n<p>Where 4xxx is the warning code. </p>\n\n<p>Have a look at the <a href=\"http://msdn.microsoft.com/en-us/library/2c8f766e%28v=vs.80%29.aspx\" rel=\"noreferrer\">msdn article</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T20:56:41.120",
"Id": "4103",
"Score": "3",
"body": "Thanks. I usually do it with the warning push and warning pop pragmas ... I wonder whether I can really suppress the cause of the warning, however."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T20:25:50.703",
"Id": "2612",
"ParentId": "2610",
"Score": "5"
}
},
{
"body": "<p>Your types are not the same, and you're relying on implicit conversion. The compiler is warning you because not all implicit conversions in this case will be valid. If you know that the conversion is valid in your case, then you should do the conversion explicitly. It's sensible to check the condition you're relying on:</p>\n\n<pre><code>extern \"C\" LPWIN32_FIND_DATAW ZFILEIO_API GetFileInfoByIndex(INT64 index) {\n assert(index <= SIZE_MAX);\n\n return total_size >= 0 \n && index <= file_vec->size() \n && index >= 0 ? &file_vec->at(static_cast<size_t>(index)) : NULL;\n}\n</code></pre>\n\n<p>The check can be either an assert or throw an exception, depending on how confident you are that this condition cannot (even theoretically) be hit in your code. You may also want to make sure that the range of <code>index</code> is checked at a higher level in the code where it can throw a more meaningful exception, e.g. in the constructor of the corresponding type. Even if you do this, keeping an additional check in the code just prior to the cast is useful, because it verifies to a future maintainer that the cast is valid.</p>\n\n<p>If the compiler still complains when you have the explicit cast in place, then I think your only option is to temporarily silence the warning. I still prefer the cast solution even in this case, since it's obvious to the reader that something potentially dangerous is being done.</p>\n\n<p>Note that <code>SIZE_MAX</code> is not defined in the C++ standard AFAICT. It's likely to be available on your platform, but if not there's almost certainly another way of getting the same information, namely the maximum value of <code>size_t</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-21T20:13:44.937",
"Id": "4614",
"Score": "1",
"body": "As an example example of the last sentence `std::numeric_limits<size_t>::max()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T11:46:32.063",
"Id": "441131",
"Score": "1",
"body": "`SIZE_MAX` is in the C++ standard library since C++11."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T08:26:33.620",
"Id": "2622",
"ParentId": "2610",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "2622",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T19:53:37.683",
"Id": "2610",
"Score": "6",
"Tags": [
"c++",
"integer",
"vb6"
],
"Title": "Avoiding the 'possible loss of data' compiler warning"
}
|
2610
|
<p>I'm trying to optimize a simple Euclidian distance function in C. It's for a DLL, and calculates distances from one point to many. I have:</p>
<p>Version 1:</p>
<pre><code>int CalcDistance (int y1, int x1, int *y2, int *x2, int nb , int *distances)
{
double dx,dy = 0;
for (int i = 0;i<nb;i++)
{
dx = x2[i] - x1;
dy = y2[i] - y1;
distances[i]=(int)sqrt((dx*dx)+(dy*dy));
}
return nb;
}
</code></pre>
<p>Version 2:</p>
<pre><code>int CalcDistance (int y1, int x1, int *y2, int *x2, int nb , int *distance)
{
int dx,dy =0;
for (int i = 0;i<nb;i++)
{
dx = x2[i] - x1;
dy = y2[i] - y1;
distances[i]=(int)sqrt((double)(dx*dx)+(dy*dy));
}
return nb;
}
</code></pre>
<p>Essentially, I don't need extra high precision, so that's why I'm cutting down to ints, not doubles. For my specific use case, the final distance will not be larger than what an int (Int32) can hold.</p>
<p>I was taken aback by how slow version 2 was. I figured that in Version 1 calculating <code>dx</code> and <code>dy</code> would implicitly cast to <code>double</code> twice, whereas in version 2 I'm just explicitly casting once. What's happening? And ultimately, what could be even faster?</p>
<p>(And I tried <code>_hypot</code>, which was oddly the slowest of all...)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T01:01:55.853",
"Id": "4111",
"Score": "0",
"body": "what kind of size is nb typically?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T08:24:17.167",
"Id": "4119",
"Score": "0",
"body": "What is the reason for ordering the parameters y, x? I would think that x, y would be the natural order. Unless this is used in an environment where y,x is the norm it could be a source of mistakes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T09:50:56.670",
"Id": "4123",
"Score": "0",
"body": "@phq: I hadn't noticed I had carried that over to here. The original function creator had written \"Lat,Lon\", even though the values sent were not latitude and longitude but really coordinates from a planar projection, where latitude is really a Y coordinate, and longitude an X coordinate. It bugged me, so I replaced them with their correspondents. I realize now I should have simply made the call to the function with the right order and make it (x,y). There is no impact in the actual function here either way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T20:08:00.810",
"Id": "4139",
"Score": "0",
"body": "@KeithNicholas I finally have the answer. It's a wide range, from a few hundreds to 400-500k. There's no typical case, but I'm guessing a very ballpark median would be about 75k."
}
] |
[
{
"body": "<pre><code>dstances[i]=(int)sqrt((dx*dx)+(dy*dy));\n</code></pre>\n\n<p>This only converts to double once. it will do all the math integer style and and then convert it to a double just before calling sqrt.</p>\n\n<pre><code> distances[i]=(int)sqrt((double)(dx*dx)+(dy*dy));\n</code></pre>\n\n<p>This is actually the same as:</p>\n\n<pre><code> distances[i]=(int)sqrt( ((double)(dx*dx)) + (dy*dy)); \n</code></pre>\n\n<p>not:</p>\n\n<pre><code> distances[i]=(int)sqrt((double)( (dx*dx)) + (dy*dy) ); \n</code></pre>\n\n<p>As a result it will convert dx*dx to double, then convert dy*dy to double then add them and the pass it off to sqrt.</p>\n\n<p>In modern computers floating point numbers are really fast, in some cases even faster then integers. As a result, you well be much better off to use double throughout rather then converting from ints to doubles and back again. The conversion between int and double is expensive so avoiding it may actually be your best bet.</p>\n\n<p>A common trick used in algorithms which need to work with distances is to rework the algorithm so that you can use the square of the distance. That way you can avoid the expensive sqrt call. This works because x*x < y*y iff x < y. Be careful though, whether or not you can do this depends on what you are doing with that distance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T01:37:21.590",
"Id": "4112",
"Score": "0",
"body": "The \"keep the square only\" trick is neat, one of my favourites. But this isn't a case where it can work. Thanks for the casting explanations :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T23:35:26.763",
"Id": "2620",
"ParentId": "2615",
"Score": "6"
}
},
{
"body": "<p>Even if the result fits in an int, dx*dx might overflow. Better cast before multiplying </p>\n\n<pre><code>sqrt((double)dx*dx+(double)dy*dy); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T20:49:45.673",
"Id": "4141",
"Score": "0",
"body": "I checked my max values, you're correct, it can overflow. Good catch."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T13:23:20.157",
"Id": "2629",
"ParentId": "2615",
"Score": "4"
}
},
{
"body": "<p>If you really need the distance, I have no idea, but if you just need it to compare distances, you can omit the sqrt-function, which is oftten pretty costly. Of course you should rename the function for that purpose. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T02:38:01.957",
"Id": "2643",
"ParentId": "2615",
"Score": "0"
}
},
{
"body": "<p>Depending on the x,y values, you could consider using floats instead of doubles. This should help a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T09:57:13.063",
"Id": "2651",
"ParentId": "2615",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2620",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:49:30.010",
"Id": "2615",
"Score": "4",
"Tags": [
"performance",
"c",
"casting"
],
"Title": "Euclidian distance - optimization and casting"
}
|
2615
|
<p>F# is a succinct, expressive, and efficient functional and object-oriented language for .NET, which helps you write simple code to solve complex problems. It is a descendant from the <a href="https://en.wikipedia.org/wiki/ML_(programming_language)" rel="nofollow">ML family</a> of programming languages.</p>
<p>For more information about F#, visit the <a href="http://www.fsharp.net" rel="nofollow">F# homepage at MSDN</a>.</p>
<p>See also <a href="http://stackoverflow.com/questions/734525/getting-started-with-f">Getting Started with F#</a> for lots more information, including links to blogs, videos, books, "hello world"s, downloads, and more.</p>
<p>For tips and tricks on transitioning to functional languages (especially F#) there is also <a href="http://fsharpforfunandprofit.com/" rel="nofollow">F# For Fun and Profit</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:55:00.947",
"Id": "2616",
"Score": "0",
"Tags": null,
"Title": null
}
|
2616
|
F# is a succinct, expressive, and efficient functional and object-oriented language for .NET
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-25T21:55:00.947",
"Id": "2617",
"Score": "0",
"Tags": null,
"Title": null
}
|
2617
|
<p>I have 3 questions, all of them are concerned with binary coded decimal (BCD) conversion. My coding snippets are listed as follows. But I don't like my algorithm because it takes too long when dealing with tons of data.</p>
<p>Any suggestions to improve the performance? Would you please show me an efficient and fast way to do that?</p>
<ol>
<li><p>The value is expressed with 4-bits binary coded decimals (BCD), which was originally stored in a character buffer (for example, pointed by a pointer <code>const unsigned char *</code>). </p>
<blockquote>
<pre><code>BCD*2; 1001 0111 0110 0101=9765
"9" "7" "6" "5"
</code></pre>
</blockquote>
<pre><code>unsigned int BCDn( unsigned int n, const unsigned char * data )
{
unsigned int uResult = 0;
unsigned char ucTmp;
int iTmp1,iTmp2;
for (unsigned int i=0;i<n;i++)
{
ucTmp = data[i];
iTmp1 = (ucTmp & 0xf0) >> 4;
iTmp2 = ucTmp & 0x0f;
uResult += (iTmp1*10+iTmp2) * static_cast<unsigned int>(pow(100.0,static_cast<int>(n-1-i)));
}
return uResult;
}
</code></pre></li>
<li><p>The value is expressed by <code>n</code> binary integer (n* 8-bits). The first bit (MSB) defines
the sign of binary integer; "0" signifies that it's a positive integer, and "1" for negative one. In the case of negative number, the other bits show the complement number that is added 1.</p>
<blockquote>
<pre><code> MSB LSB
I*2; 00101101 1001100=19999
I*2; 10101101 10011100=(-1)*(0101101 10011100
=(-1)*(1010010 01100100) (after complement)
=-21092
</code></pre>
</blockquote>
<pre><code>int SINTn(unsigned int n, const unsigned char *data)
{
int nResult;
bool bNegative = false;
if ((data[0] & 0x80)!= 0)
isNegative = true;
nResult = data[0] & 0x7f;
for (unsigned int i=1;i<n;i++)
nResult = nResult * 0x100 + data[i];
if (bNegative)
nResult = nResult - static_cast<int>(pow(2.0,static_cast<int>(n*8-1)));
return nResult
}
unsigned int UINTn(unsigned int n, const unsigned char *data)
{
unsigned int uResult = 0;
for (unsigned int i=0;i<n;i++)
uResult = uResult * 0x100 + data[i];
return uResult;
}
</code></pre></li>
<li><p><code>R*n.m</code></p>
<p>The value is expressed by n-bytes (n*8 bits) binary number, the first bit (MSB)
defines the sign of it; "0" means positive and "1" means negative. The number m means
that the binary number should be multiplied by 10-m to get the value.</p>
<blockquote>
<pre><code> MSB LSB
R*4.0: 00000000 00000000 00000111 10110101=1973
R*4.2: 00000000 00000000 00000111 10110101=1973*10-2=19.73
R*4.5: 10000000 00000000 00000111 10110101=-1973*10-5= -0.01973
R*2.0: 10101101 10011100 =-11676
</code></pre>
</blockquote>
<pre><code>double REALnm(unsigned int n, unsigned int m, const unsigned char * data)
{
double dResult;
bool bNegative = false;
if ((data[0] & 0x80)!= 0)
isNegative = true;
dResult = data[0] & 0x7f;
for (unsigned int i=1;i<n;i++)
dResult = dResult * 0x100 + data[i];
if (bNegative) dResult *= -1.0;
dResult *= pow(10.0, (-1.0) * m);
return dResult;
}
</code></pre></li>
</ol>
|
[] |
[
{
"body": "<p>You can avoid pow by doing something like this:</p>\n\n<pre><code>unsigned int BCDn( unsigned int n, const unsigned char * data )\n{\n unsigned int uResult = 0;\n unsigned char ucTmp;\n int iTmp1,iTmp2;\n\n unsigned int factor = 1;\n for (unsigned int i=n-1;i>=0;i--)\n {\n ucTmp = data[i];\n iTmp1 = (ucTmp & 0xf0) >> 4;\n iTmp2 = ucTmp & 0x0f;\n uResult += (iTmp1*10+iTmp2) * factor;\n factor *= 100;\n }\n\n return uResult; \n}\n</code></pre>\n\n<p>Basically count backwards, and then you only need to multiply the factor each time. Similar tricks should work for the other methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T14:30:08.117",
"Id": "2630",
"ParentId": "2623",
"Score": "2"
}
},
{
"body": "<p>it can be a lot simpler...</p>\n\n<pre><code>#include \"seatest.h\"\n\nunsigned int BCDn( unsigned int n, const unsigned char * data )\n{\n unsigned int uResult = 0;\n unsigned int i;\n\n for (i=0;i<n;i++) \n {\n uResult = (uResult * 100) + ((data[i] >> 4) * 10 ) + ( data[i] & 0x0F); \n }\n\n return uResult; \n}\nvoid test_max_bcd_convert()\n{ \n unsigned char bcd_data[]= { 0x97, 0x65 };\n\n assert_int_equal(9765, BCDn(2, bcd_data));\n\n}\n\nvoid test_fixture_bcd( void )\n{\n test_fixture_start(); \n run_test(test_max_bcd_convert); \n test_fixture_end(); \n}\n\nvoid all_tests( void )\n{\n test_fixture_bcd(); \n}\n\nint main( int argc, char** argv )\n{\n run_tests(all_tests); \n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T21:35:17.643",
"Id": "2636",
"ParentId": "2623",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T09:44:53.647",
"Id": "2623",
"Score": "5",
"Tags": [
"c++",
"optimization",
"performance",
"converting",
"bitwise"
],
"Title": "Decoding binary coded decimal (BCD) value"
}
|
2623
|
<p>I'm new to coding, and especially to OOP PHP. I'll highly appreciate if you expert programmers could review following code and give me your opinion to make it better. Also, how you see this code, is it too horrible and ugly?</p>
<pre><code><?php
include_once("config.inc.php");
class user{
var $mysqli;
var $username;
var $userid;
function __construct($mysqli) {
session_start();
$this->mysqli = $mysqli;
}
function valid_length($input){
if ((strlen($input) > 4 ) AND (strlen ($input) < 16) ){
return true;
} else {
return false;
}
}
function valid_email($email){
if (preg_match("/^[0-9a-z]+(([\.\-_])[0-9a-z]+)*@[0-9a-z]+(([\.\-])[0-9a-z-]+)*\.[a-z]{2,4}$/i" , $email)) {
return true;
} else {
return false;
}
}
function alpha_numeric($input){
if (eregi("^([0-9a-z])+$", $input)){
return true;
}else{
return false;
}
}
function username_exists($username){
if ($stmt = $this->mysqli->prepare("SELECT username FROM users WHERE username=?")) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$stmt->close();
}
return ($count > 0 ? true : false);
}
function signup($username, $password, $email, $capt_error){
//validate username.
if(!$this->valid_length($username)){
$this->signup_error = "Username should be 5 - 15 characters. <br />";
}else if(!$this->alpha_numeric($username)){
$this -> signup_error ="Only letters, numbers";
} else if($this->username_unallowed($username)){
$this -> signup_error ="Not allowed.";
} else if ($this->username_exists($username)){
$this -> signup_error ="Username already exists. <br />";
}
//validate password.
if (!$this->valid_length($password) ){
$this -> signup_error .="Password should be 5 - 15 characters. <br />";
}
//validate email.
if (!$this->valid_email($email) ){
$this -> signup_error .="Invalid email.";
}else if($this->email_exists($email)) {
$this -> signup_error .="Email exists.<br />";
}
//captcha error
if($capt_error == 1){
$this -> signup_error .="Invalid captcha. <br />";
}
//no any error, proceed.
if ($this->signup_error == ""){
$hashed_password = $this->hash_password($password);
if ($this->insert_new_user($username, $enc_password, $email)){
$_SESSION['username']=$username;
header("Location: welcome.php");
}else {
$this->signup_error = "Unknown error. <br />";
}
}
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T07:22:12.253",
"Id": "4186",
"Score": "3",
"body": "This isn't enough for a full answer, but I'd recommend not adding `?>` to the end of files like this. If there is any extra whitespace after the closing PHP tag, it will be output to the browser when all you intended to do was include a class for internal (non-presentation) use. This sort of thing can be _excruciatingly_ difficult to track down when you're not sure why there's an extra space in an arbitrary spot on a page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T03:35:16.237",
"Id": "17014",
"Score": "0",
"body": "There are many IF statements in this code - you don't want that. Most IF statements can be refactored as inheritance. Reading up on Polymorphism might help."
}
] |
[
{
"body": "<p>Why not use the built-in PHP e-mail validation?</p>\n\n<pre><code>filter_var($email, FILTER_VALIDATE_EMAIL)\n</code></pre>\n\n<p>Why do</p>\n\n<pre><code>if (lol())\n return true;\nelse\n return false;\n</code></pre>\n\n<p>when you can do</p>\n\n<pre><code>return lol();\n</code></pre>\n\n<p>Same goes for <code>lol() ? true : false</code> which you do too.</p>\n\n<p>Furthermore the signup_error stuff is ugly. I'd suggest exceptions. At least make signup_error into an array instead, and just add new elements when you get an error. You can join() the array when outputting.</p>\n\n<p>Also, you risk $count not being defined if $stmt fails.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T11:51:11.963",
"Id": "4126",
"Score": "0",
"body": "thanks for the reply, how about over-all structure of my code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T12:00:52.063",
"Id": "4127",
"Score": "0",
"body": "@jcb I added some more comments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T12:08:43.797",
"Id": "4128",
"Score": "0",
"body": "Thanks, my idea was that when i pass the variable to a function, for example \"valid_email\", the function valid_email will either return true value or false. Then based on the returned true or false, i can do something, for example ` if ($this->valid_email($email) ){}`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T11:45:02.113",
"Id": "2625",
"ParentId": "2624",
"Score": "7"
}
},
{
"body": "<p>I've got a few suggestions, but all in all this code is a long way from being horrible and ugly.</p>\n\n<p>You're using PHP 4-style class members (<code>var $mysqli</code>) when you could be using PHP 5 members with access control (<code>public</code>, <code>private</code> etc.) The same goes for methods, which should be qualified with <code>public</code> or <code>private</code> to indicate who should be able to have access to them.</p>\n\n<p>In general, you should make all data members of a class <code>private</code> unless there's a really good reason for them to be public. The <code>$mysqli</code> handle, for example, is purely an implementation detail and no client of the class should need to have access to it.</p>\n\n<p>The <code>$userid</code> member doesn't seem to be used at all, that I can see. I'm assuming it's an incomplete implementation.</p>\n\n<p>The biggest problem is it's not clear to me what the <code>user</code> class does. Aim to give each class a small, well-defined set of responsibilities. At the moment the class appears to be a collection of all the code that is used for working with users, whether or not it has anything to do with the concept of a user as such. For example, the <code>alpha_numeric</code> function is a completely generic concept that you might want to use elsewhere, so it doesn't belong on the <code>user</code> class. Nor does <code>valid_email</code>. The <code>valid_length</code> method should probably be private.</p>\n\n<p>When you design a class, it can be helpful to start from a description of just the public interface. Decide what you want people to be able to do with instances of your class. Aim for something that can be described simply and will be obvious to other people working with the code. Any functionality that doesn't fit into this interface should be in a separate class. Write documentation and / or unit tests to this interface, and you'll see whether it makes sense to a user. Once you've got the public interface fixed, you can add whatever private methods you need to make that work, but resist the temptation to change the public interface unless you've discovered something really important that you didn't think of before.</p>\n\n<p>Another small detail is that your indentation is very inconsistent. I don't know if that's an artifact of copying and pasting to the site.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T12:23:13.257",
"Id": "4129",
"Score": "0",
"body": "Thank you very much for spending your precious time to reply me. As I mentioned, I just have started to learn the OOP style PHP, and I was concerned about the overall structure. This is an example class to deal with users registeration, some of functions are missing in it as i just copied some parts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T12:26:49.980",
"Id": "4130",
"Score": "0",
"body": "I just found out that if i use only `function` i can access it outside the class, for example on signup.php page, i can call `$user->signup();` etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T12:06:49.253",
"Id": "2626",
"ParentId": "2624",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "2626",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T11:06:16.633",
"Id": "2624",
"Score": "5",
"Tags": [
"php",
"beginner",
"validation"
],
"Title": "Validating username fields and showing CAPTCHA"
}
|
2624
|
<p>The Demo for what I have made is located <a href="http://jsfiddle.net/maniator/pajsR/145/" rel="nofollow noreferrer">here</a></p>
<p>Basically I am trying to make a self playing JavaScript baseball game with the use of no libraries.</p>
<p>Is there anything I could improve on in the code?</p>
<pre><code>var writeDown = {
delay: 110,
add: null,
div: document.getElementById('playArea'),
log: function() {
var args = arguments;
if (args.length == 0) {
args = [''];
}
var div = this.div;
setTimeout(function() {
//console.log(args[0]);
div.innerHTML = args[0] + "<br/>" + div.innerHTML;
}, this.delay);
if (this.add == null) {
this.add = this.delay;
}
this.delay += this.add;
},
updateDiv: function(msg, div) {
setTimeout(function() {
//console.log(msg, div);
div.innerHTML = msg;
}, this.delay);
},
updateDiv_delay: function(msg, div) {
setTimeout(function() {
document.getElementById(div).innerHTML = msg;
}, this.delay);
},
updateDiv_color: function(color, div) {
setTimeout(function() {
//console.log(color, div);
document.getElementById(div).style.background = color;
}, this.delay);
}
}
var Diamond = function(d_name, d_id) {
var name = d_name;
var diamond = document.getElementById(d_id);
var bases = {
first: false,
second: false,
third: false,
home: false
};
var players = {
first: false,
second: false,
third: false,
home: false
};
this.clear = function() {
bases = {
first: false,
second: false,
third: false,
home: false
};
players = {
first: false,
second: false,
third: false,
home: false
};
this.updateBases();
writeDown.updateDiv('', diamond);
}
this.onBase = function(base_amt, PlayerName) {
var return_runs = 0;
switch (base_amt) {
case 0:
return 0;
break;
case 1:
if (bases.first) {
if (bases.second) {
if (bases.third) {
writeDown.log(name + ": BASES LOADED, " + players.third + " scored");
return_runs += 1;
}
else {
writeDown.log(name + ": BASES LOADED");
bases.third = true;
}
players.third = players.second;
players.second = players.first;
players.first = PlayerName;
}
else {
writeDown.log(name + ": Man on 1st and 2nd");
players.second = players.first;
players.first = PlayerName;
bases.second = true;
}
}
else {
writeDown.log(name + ": Man on 1st");
players.first = PlayerName;
bases.first = true;
}
break;
case 2:
if (bases.first) {
writeDown.log(name + ": Man on 2nd, and Third");
bases.first = false;
if (bases.third) return_runs += 1;
bases.third = true;
}
if (bases.second) {
return_runs += 1;
if (bases.third) {
writeDown.log(name + ": Man on 2nd, 2 runs scored (" + players.second + ", " + players.third + ")");
bases.third = false;
return_runs += 1;
}
else {
writeDown.log(name + ": Man on 2nd, run scored (" + players.second + ")");
}
}
if (bases.third) {
return_runs += 1;
bases.third = false;
writeDown.log(name + ": Man on 2nd, run scored (" + players.third + ")");
}
else {
writeDown.log(name + ": Man on 2nd");
bases.second = true;
}
players.third = players.first;
players.second = PlayerName;
players.first = null;
break;
case 3:
if (bases.first) {
writeDown.log(name + ": " + players.first + " Scored from 1st");
bases.first = false;
return_runs += 1;
}
if (bases.second) {
writeDown.log(name + ": " + players.second + " Scored from 2nd");
bases.second = false;
return_runs += 1;
}
if (bases.third) {
writeDown.log(name + ": " + players.third + " Scored from 3rd");
return_runs += 1;
}
else {
writeDown.log(name + ": Man on 3rd");
bases.third = true;
}
players.third = PlayerName;
players.second = null;
players.first = null;
break;
case 4:
if (bases.first) {
writeDown.log(name + ": " + players.first + " Scored from 1st");
bases.first = false;
return_runs += 1;
}
if (bases.second) {
writeDown.log(name + ": " + players.second + " Scored from 2nd");
bases.second = false;
return_runs += 1;
}
if (bases.third) {
writeDown.log(name + ": " + players.third + " Scored from 3rd");
bases.third = false;
return_runs += 1;
}
players.third = null;
players.second = null;
players.first = null;
writeDown.log(name + ": " + PlayerName + " Scored from home");
return_runs += 1;
break;
}
var man_on = "",
base_names = ['first', 'second', 'third'];
for (var i = 0; i < 4; i++) {
if (players[base_names[i]] != null && players[base_names[i]]) {
man_on += players[base_names[i]] + " is on " + base_names[i] + " base <br/>";
}
}
writeDown.updateDiv(man_on, diamond);
this.updateBases();
return return_runs;
}
this.updateBases = function() {
for (base in bases) {
if (bases[base] == true) {
writeDown.updateDiv_color('#F00', base);
}
else {
writeDown.updateDiv_color('#AAA', base);
}
}
}
this.playGame = function(TeamA, TeamB, innings) {
var score_div = document.getElementById('score');
writeDown.updateDiv(TeamA.name + ": <span id='" + TeamA.name + "'>" + TeamA.getScore() + "</span><br/>" + TeamB.name + ": <span id='" + TeamB.name + "'>" + TeamB.getScore() + "</span><hr>" + "Outs: <span id='outs'>0</span><br/>" + "Inning: <span id='inning'>1</span>", score_div);
for (var i = 0; i < innings; i++) {
writeDown.log("<br/><b>INNING " + (i + 1) + "</b><br/>");
writeDown.updateDiv_delay("Top of " + (i + 1), 'inning');
if (TeamA.teamUp()) {
writeDown.updateDiv_delay("Bottom of " + (i + 1), 'inning');
writeDown.log(TeamA.name + " are out <br/>");
this.clear();
TeamA.resetOuts();
writeDown.log("");
if (TeamB.teamUp()) {
writeDown.log(TeamB.name + " are out<br/><br/>");
this.clear();
TeamB.resetOuts();
writeDown.log("");
}
}
}
}
}
var Player = function(pitcher, name) {
var name = (name == undefined) ? "Nothing" : name;
var balls = 0;
var strikes = 0;
this.getName = function() {
return name;
}
this.atBat = function() {
var pitch = pitcher.show_pitch();
var random = Math.floor(Math.random() * 1000);
var swing_rate = 500 - (75 * strikes);
if (random < swing_rate) { //swing
strikes += 1;
writeDown.log(name + " swung and missed.");
writeDown.log(name + " has " + strikes + " strikes.");
if (strikes >= 3) {
strikes = 0;
balls = 0;
writeDown.log(name + " struck out");
return {
out: 1,
type: 0
};
}
}
else if (random < 880) { //wait for pitch
writeDown.log(name + " watches the pitch.");
if (pitch == "Strike") {
strikes += 1;
writeDown.log(name + " has " + strikes + " strikes.");
if (strikes >= 3) {
strikes = 0;
balls = 0;
writeDown.log(name + " struck out");
return {
out: 1,
type: 0
};
}
}
if (pitch == "Ball") {
balls += 1;
writeDown.log(name + " has " + balls + " balls.");
if (balls >= 4) {
balls = 0;
strikes = 0;
writeDown.log(name + " has been walked");
return {
out: 0,
type: 1
};
}
}
}
else if (random <= 1000) { //hit ball
balls = 0;
strikes = 0;
var hit = "Single";
if (random > 940 && random < 970) {
hit = "Double";
}
else if (random >= 970 && random < 995) {
hit = "Triple";
}
else if(random >= 995){
hit = "Homerun";
}
writeDown.log(name + " hit a " + hit);
var hit_type = 1;
if (hit == "Double") hit_type = 2;
if (hit == "Triple") hit_type = 3;
if (hit == "Homerun") hit_type = 4;
writeDown.log(name + " going to base");
return {
out: 0,
type: hit_type
};
}
//writeDown.log(name + " waiting for next pitch");
return this.atBat();
}
}
var Pitcher = function(team) {
var types = ["Ball", "Strike"];
var Team = team;
this.show_pitch = function() {
var random = Math.floor(Math.random() * (types).length);
writeDown.log();
writeDown.log(Team.name + " pitcher threw the ball.");
return types[random];
}
}
var Team = function() {
var amt_of_players = 9;
var players = [];
var pitcher = new Pitcher(this);
var otherPitcher = null;
var outs = 0;
var score = 0;
var stadium = null;
var player_up_to = 0;
this.name = "Nobody's";
this.createTeam = function(TeamName, Opponent, Diamond) {
stadium = Diamond;
otherPitcher = Opponent.getPitcher();
this.name = (TeamName == undefined) ? "Nothing" : TeamName;
for (var i = 0; i < amt_of_players; i++) {
players[i] = new Player(otherPitcher, "Player " + (i + 1) + " on " + this.name);
}
return this;
}
this.teamUp = function() {
for (var i = player_up_to; i < players.length; i++) {
var atBat = players[i].atBat();
outs += atBat.out;
score += stadium.onBase(atBat.type, players[i].getName());
writeDown.updateDiv_delay(score, this.name);
writeDown.updateDiv_delay(outs, 'outs');
if (outs >= 3) {
player_up_to = (i + 1) % players.length; //start with next player;
return true;
}
}
if (outs >= 3) {
player_up_to = 0;
return true;
}
else {
player_up_to = 0;
return this.teamUp();
}
}
this.getScore = function() {
return score;
}
this.resetOuts = function() {
outs = 0;
writeDown.updateDiv_delay(outs, 'outs');
}
this.getPitcher = function() {
return pitcher;
}
}
var TeamA = new Team();
var TeamB = new Team();
var Stadium = new Diamond("Citi Field", 'move');
TeamA.createTeam("Yankees", TeamB, Stadium);
TeamB.createTeam("Mets", TeamA, Stadium);
Stadium.playGame(TeamA, TeamB, 9);
writeDown.log("GAME OVER!");
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T17:32:18.883",
"Id": "4135",
"Score": "2",
"body": "I'm strangely conflicted, the architect in me wants to say choosing to use zero frameworks is reinventing the wheel to the max and you don't get to leverage a hammer that's gone through 500 design phases to hammer nails, that you have your hammer that was only built in a couple phases. But then the other side of me sees the value of reaching for the maximum for performance since this is a game we're talking about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-30T21:07:10.527",
"Id": "63392",
"Score": "0",
"body": "Is the only way batters can get out is by striking out? I didn't see any ground outs, fly outs, or double plays for that matter. I'm not a javascript guy, but I wrote something similar this weekend in python. https://bitbucket.org/jgrigonis/baseball_simulator/overview I didn't take it as far as you, so far I just have the game class that handles game state changing events."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-06T02:23:48.077",
"Id": "113085",
"Score": "0",
"body": "Well done. Just one thing...if the home team (second team listed) is ahead when it comes to the bottom of the 9th, that team does not hit. They already won."
}
] |
[
{
"body": "<pre><code>var writeDown = {\n delay: 110,\n add: null,\n div: document.getElementById('playArea'),\n log: function() {\n var args = arguments;\n if (args.length == 0) {\n args = [''];\n }\n var div = this.div;\n setTimeout(function() {\n //console.log(args[0]);\n div.innerHTML = args[0] + \"<br/>\" + div.innerHTML;\n }, this.delay);\n</code></pre>\n\n<p>What are you doing with the arguments? You seem to be taking a roundabout method to have log optionally take a single parameter. But it's not clear why logging without any arguments would make any sense.</p>\n\n<pre><code> if (this.add == null) {\n this.add = this.delay;\n }\n this.delay += this.add;\n</code></pre>\n\n<p>You've done this by scheduling a series of events to happen later and later from now. That's kinda clever but not something that you should do in a JavaScript context. A better way would be to structure your code so that a single function is called repeatedly to perform logic so that the processing is ongoing rather than done all upfront.</p>\n\n<pre><code> },\n\n updateDiv: function(msg, div) {\n setTimeout(function() {\n //console.log(msg, div);\n div.innerHTML = msg;\n }, this.delay);\n },\n\n updateDiv_delay: function(msg, div) {\n setTimeout(function() {\n document.getElementById(div).innerHTML = msg;\n }, this.delay);\n },\n</code></pre>\n\n<p>These very similar functions as well as the similar code above is begging to be combined.</p>\n\n<pre><code> updateDiv_color: function(color, div) {\n setTimeout(function() {\n //console.log(color, div);\n document.getElementById(div).style.background = color;\n }, this.delay);\n }\n}\n\n\nvar Diamond = function(d_name, d_id) {\n\n var name = d_name;\n var diamond = document.getElementById(d_id);\n\n var bases = {\n first: false,\n second: false,\n third: false,\n home: false\n };\n</code></pre>\n\n<p>When elements have a sequential interpretation, you are usually better of using numbers rather than names. Bases should be an array not an object. </p>\n\n<pre><code> var players = {\n first: false,\n second: false,\n third: false,\n home: false\n };\n</code></pre>\n\n<p>Instead of storing players like this, put everything in the bases array. Use null or false for no player, and the player's name otherwise.</p>\n\n<pre><code> this.clear = function() {\n bases = {\n first: false,\n second: false,\n third: false,\n home: false\n };\n players = {\n first: false,\n second: false,\n third: false,\n home: false\n };\n this.updateBases();\n writeDown.updateDiv('', diamond);\n }\n</code></pre>\n\n<p>You should use the clear function inside this constructor so that you don't have to duplicate its contents.</p>\n\n<pre><code> this.onBase = function(base_amt, PlayerName) {\n</code></pre>\n\n<p>Either use variable_like_this or VariablesLikeThis or variablesLikeThis. Avoid mixing styles. Also base_amt isn't really clear what it means.</p>\n\n<pre><code> var return_runs = 0;\n switch (base_amt) {\n ...\n</code></pre>\n\n<p>Your code to determine the new bases and runs is way too complicated. Your code should look something like:</p>\n\n<pre><code> for each base\n if man on base, move forward base_amt places\n if move is past home, score a run\n otherwise set new position\n</code></pre>\n\n<p>You should never need to write such repetitive code as you wrote above.</p>\n\n<pre><code> var man_on = \"\",\n base_names = ['first', 'second', 'third'];\n\n for (var i = 0; i < 4; i++) {\n if (players[base_names[i]] != null && players[base_names[i]]) {\n man_on += players[base_names[i]] + \" is on \" + base_names[i] + \" base <br/>\";\n }\n }\n</code></pre>\n\n<p>If you take my advice about using arrays instead of objects for keeping track of bases this code will be much simpler.</p>\n\n<pre><code> writeDown.updateDiv(man_on, diamond);\n this.updateBases();\n return return_runs;\n }\n\n this.updateBases = function() {\n for (base in bases) {\n if (bases[base] == true) {\n</code></pre>\n\n<p>Don't == true, just use if(bases[base]</p>\n\n<pre><code> writeDown.updateDiv_color('#F00', base);\n }\n else {\n writeDown.updateDiv_color('#AAA', base);\n }\n }\n }\n\n\n this.playGame = function(TeamA, TeamB, innings) {\n var score_div = document.getElementById('score');\n writeDown.updateDiv(TeamA.name + \": <span id='\" + TeamA.name + \"'>\" + TeamA.getScore() + \"</span><br/>\" + TeamB.name + \": <span id='\" + TeamB.name + \"'>\" + TeamB.getScore() + \"</span><hr>\" + \"Outs: <span id='outs'>0</span><br/>\" + \"Inning: <span id='inning'>1</span>\", score_div);\n\n for (var i = 0; i < innings; i++) {\n writeDown.log(\"<br/><b>INNING \" + (i + 1) + \"</b><br/>\");\n writeDown.updateDiv_delay(\"Top of \" + (i + 1), 'inning');\n if (TeamA.teamUp()) {\n</code></pre>\n\n<p>As far as I can tell teamUp never returns false. Its also deceiving because I'd expect something like that in an if to be answering a question not running a complete half-inning. Neither the name nor how it's used hint that the function does that.</p>\n\n<pre><code> writeDown.updateDiv_delay(\"Bottom of \" + (i + 1), 'inning');\n writeDown.log(TeamA.name + \" are out <br/>\");\n this.clear();\n TeamA.resetOuts();\n writeDown.log(\"\");\n if (TeamB.teamUp()) {\n writeDown.log(TeamB.name + \" are out<br/><br/>\");\n this.clear();\n TeamB.resetOuts();\n writeDown.log(\"\");\n }\n }\n }\n }\n\n}\n\nvar Player = function(pitcher, name) {\n var name = (name == undefined) ? \"Nothing\" : name;\n var balls = 0;\n var strikes = 0;\n\n this.getName = function() {\n return name;\n }\n\n this.atBat = function() {\n var pitch = pitcher.show_pitch();\n var random = Math.floor(Math.random() * 1000);\n var swing_rate = 500 - (75 * strikes);\n\n if (random < swing_rate) { //swing\n strikes += 1;\n writeDown.log(name + \" swung and missed.\");\n writeDown.log(name + \" has \" + strikes + \" strikes.\");\n if (strikes >= 3) {\n strikes = 0;\n balls = 0;\n writeDown.log(name + \" struck out\");\n return {\n out: 1,\n type: 0\n };\n }\n }\n else if (random < 880) { //wait for pitch\n writeDown.log(name + \" watches the pitch.\");\n if (pitch == \"Strike\") {\n strikes += 1;\n writeDown.log(name + \" has \" + strikes + \" strikes.\");\n if (strikes >= 3) {\n strikes = 0;\n balls = 0;\n writeDown.log(name + \" struck out\");\n return {\n out: 1,\n type: 0\n };\n }\n }\n if (pitch == \"Ball\") {\n balls += 1;\n writeDown.log(name + \" has \" + balls + \" balls.\");\n if (balls >= 4) {\n balls = 0;\n strikes = 0;\n writeDown.log(name + \" has been walked\");\n return {\n out: 0,\n type: 1\n };\n }\n }\n</code></pre>\n\n<p>You have code checking for strike outs in two places. You should move that code out of the if(random) block so that it can be shared.</p>\n\n<pre><code> }\n else if (random <= 1000) { //hit ball\n balls = 0;\n strikes = 0;\n var hit = \"Single\";\n if (random > 940 && random < 970) {\n hit = \"Double\";\n }\n else if (random >= 970 && random < 995) {\n hit = \"Triple\";\n }\n else if(random >= 995){\n hit = \"Homerun\";\n }\n writeDown.log(name + \" hit a \" + hit);\n var hit_type = 1;\n if (hit == \"Double\") hit_type = 2;\n if (hit == \"Triple\") hit_type = 3;\n if (hit == \"Homerun\") hit_type = 4;\n writeDown.log(name + \" going to base\");\n return {\n out: 0,\n type: hit_type\n };\n }\n\n //writeDown.log(name + \" waiting for next pitch\");\n return this.atBat();\n }\n}\n</code></pre>\n\n<p>This function would be simpler if you separated out the logic deciding whether it was a strike/ball/single/double/triple/home run into a separate function and just decided what the consequences would be.</p>\n\n<pre><code>var Pitcher = function(team) {\n var types = [\"Ball\", \"Strike\"];\n var Team = team;\n this.show_pitch = function() {\n var random = Math.floor(Math.random() * (types).length);\n writeDown.log();\n writeDown.log(Team.name + \" pitcher threw the ball.\");\n return types[random];\n }\n}\n\n\nvar Team = function() {\n\n var amt_of_players = 9;\n var players = [];\n var pitcher = new Pitcher(this);\n var otherPitcher = null;\n var outs = 0;\n var score = 0;\n var stadium = null;\n var player_up_to = 0;\n\n this.name = \"Nobody's\";\n\n this.createTeam = function(TeamName, Opponent, Diamond) {\n stadium = Diamond;\n otherPitcher = Opponent.getPitcher();\n this.name = (TeamName == undefined) ? \"Nothing\" : TeamName;\n for (var i = 0; i < amt_of_players; i++) {\n players[i] = new Player(otherPitcher, \"Player \" + (i + 1) + \" on \" + this.name);\n }\n return this;\n }\n</code></pre>\n\n<p>Passing Opponent is slightly odd here. It implies that a team can only have a single opponent which isn't true to how teams work.</p>\n\n<pre><code> this.teamUp = function() {\n for (var i = player_up_to; i < players.length; i++) {\n var atBat = players[i].atBat();\n outs += atBat.out;\n score += stadium.onBase(atBat.type, players[i].getName());\n writeDown.updateDiv_delay(score, this.name);\n writeDown.updateDiv_delay(outs, 'outs');\n if (outs >= 3) {\n player_up_to = (i + 1) % players.length; //start with next player;\n return true;\n }\n }\n\n if (outs >= 3) {\n player_up_to = 0;\n return true;\n }\n else {\n player_up_to = 0;\n return this.teamUp();\n }\n }\n\n this.getScore = function() {\n return score;\n }\n\n this.resetOuts = function() {\n outs = 0;\n writeDown.updateDiv_delay(outs, 'outs');\n }\n\n this.getPitcher = function() {\n return pitcher;\n }\n}\n\nvar TeamA = new Team();\nvar TeamB = new Team();\nvar Stadium = new Diamond(\"Citi Field\", 'move');\n\nTeamA.createTeam(\"Yankees\", TeamB, Stadium);\nTeamB.createTeam(\"Mets\", TeamA, Stadium);\n\nStadium.playGame(TeamA, TeamB, 9);\n\nwriteDown.log(\"GAME OVER!\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T05:44:35.773",
"Id": "4148",
"Score": "0",
"body": "@Winston, how would you do the log?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T05:48:01.593",
"Id": "4149",
"Score": "0",
"body": "@Winston and the only reason i need to pass the Opponent is because my `Player` objects need to know who the opposing pitcher is, how else can i do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T13:36:51.753",
"Id": "4160",
"Score": "0",
"body": "@Neal, re: log in terms of dealing with arguments or in terms of your ever-building arrays?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T13:37:29.850",
"Id": "4161",
"Score": "0",
"body": "@Neal, I'd pass the pitcher as an argument to your teamUp method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T14:37:07.753",
"Id": "4163",
"Score": "0",
"body": "@Winston, my intention was for each team to have their own pitcher, so the opposite team has to know the opposing pitcher"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T14:37:20.327",
"Id": "4164",
"Score": "0",
"body": "@Winston, everything about the log"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T00:34:58.820",
"Id": "4179",
"Score": "0",
"body": "@Neal, for the log, instead of all the `arguments` code, use the same technique that you used for the player's name. Instead of delaying I suggest either storing all the updates in an array and then reading those out or restructuring your code so that it simulates the game as it displays it rather then all upfront."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T00:35:45.997",
"Id": "4180",
"Score": "0",
"body": "@Neal, the player doesn't need to know the pitcher until its atBat is called. You don't need to store it in the constructor. Instead, pass it as an argument to atBat."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-31T17:25:58.733",
"Id": "19551",
"Score": "0",
"body": "Winston -- any way you want to dissect my newest query? ^_^"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-11T17:21:48.183",
"Id": "233966",
"Score": "0",
"body": "Winston -- I have made _some_ improvements (if you care to comment on them) here: http://codereview.stackexchange.com/q/125392/3163 :-)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-05-26T22:50:09.150",
"Id": "2637",
"ParentId": "2631",
"Score": "13"
}
},
{
"body": "<p>biggest thing thats going to make a difference to your programming style / quality from the looks of it :- functions</p>\n\n<p>break the code up into a lot more little useful functions. A lot of the awkwardness of the code is because you haven't done this.</p>\n\n<p>look for the repeated code / code with the same structure but slight variations, look at how you could wrap it up in a little function.</p>\n\n<p>in programming terms there's a concept called levels of perspective. there are 3 levels, conceptual / specification / implementation ( I wrote something about it here <a href=\"http://designingcode.blogspot.com/2006/12/its-matter-of-perspective.html\" rel=\"nofollow\">http://designingcode.blogspot.com/2006/12/its-matter-of-perspective.html</a>) </p>\n\n<p>basically you are mixing specification with implementation and it makes the code a bit messy. </p>\n\n<p>so </p>\n\n<p>yhe code should look something like this (perhaps) at the specification perhaps:-</p>\n\n<pre><code>if( pitch == pitches.BALL) // or more probably as part of a switch/case\n{\n if( this.reachedBallLimit() )\n {\n this.walk();\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T04:02:08.147",
"Id": "2644",
"ParentId": "2631",
"Score": "2"
}
},
{
"body": "<p>Javascript is not my primary language, and neither am I game a programmer. With that being said this is mostly pseudo-codeish way as to how I would structure the game loop</p>\n\n<pre><code>var game = Coaches.StartGame()\n\nwhile(game.IsPlaying)\n{\n var pitcher = game.CurrentPitcher;\n var batter = game.CurrentBatter;\n\n\n var ball = pitcher.Pitch();\n var swing = batter.HandlePitch(ball);\n\n var decision = Umpire.HandleSwing(swing);\n\n var isInningOver = Umpire.CallInning(decision, game);\n\n if(isInningOver)\n {\n var isGameOver = Umpire.CallGame(decision, game);\n\n if(isGameOver)\n {\n game = Umpire.EndGame(game);\n }\n else\n {\n game = Coaches.AdvaceInning(game);\n }\n }\n else\n { \n var field = Coaches.SendBaseRunners(decision, game)\n game = Umpire.Advance(field); \n //theoretically at this point you could need to check whether game/inning ended\n //from base runners getting thrown out if you want to support that \n game = Coaches.NextBatter(game);\n }\n}\n</code></pre>\n\n<p>Following this you have coaches starting a game and fielding players, with the Umpire affiliating the game.</p>\n\n<p>This allow will allow you to have the logic of the game without any <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility principle</a> violations that none of the methods I've shown above would ever need to change for any reason other than their specific logic.</p>\n\n<p>This is different from your current setup where there is shared responsibility such as the atBat method that is both scoring the bat outcome and scoring the game. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-30T22:17:03.020",
"Id": "18230",
"Score": "0",
"body": "Other than replacing your while loop with a `window.setTimeout()` loop (to not cause the \"this script is taking too long\" popup), this is exactly how I would do it. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-02T18:02:00.373",
"Id": "18298",
"Score": "0",
"body": "@BillBarry thanks for the feedback, I'm glad to see my thoughts were on track. I've never done any programming like this in JS personally so that input about the setTimeout would never have entered my mind until I would likely have gotten that unresponsive warning and went digging."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T15:30:07.217",
"Id": "2660",
"ParentId": "2631",
"Score": "5"
}
},
{
"body": "<p>Bearing in mind that this post is more than seven years old, there are <a href=\"https://codereview.meta.stackexchange.com/q/1510/120114\">zombies</a> I should be spending my time on instead of this, and you have likely learned much about JavaScript since then(<strong>Edit</strong>: it appears you have a gold badge for JS on SO so it seems like you <em>have</em> learned a lot), there is something that I feel should be mentioned that hasn't already.... For posterity. </p>\n\n<p>As <a href=\"https://www.thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/\" rel=\"nofollow noreferrer\">this post</a> explains, the methods should be declared on the prototypes instead of in the constructor functions. That way the memory usage will be dramatically less. </p>\n\n<p>Take for example the constructor function for <code>Player</code> - it can be simplified to the following, with the variables declared inside set on <code>this</code>.</p>\n\n<pre><code>var Player = function(pitcher, name) {\n this.name = (name == undefined) ? \"Nothing\" : name;\n this.balls = 0;\n this.strikes = 0;\n}\n</code></pre>\n\n<p>Then add the methods on the prototype:</p>\n\n<pre><code>Player.prototype.getName = function() {\n return this.name;\n}\nPlayer.prototype.atBat = function() {\n ...\n</code></pre>\n\n<p>While there are only two <code>Player</code> objects it would still be beneficial to do this, in order to reduce memory consumption.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T03:18:44.657",
"Id": "204380",
"ParentId": "2631",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2637",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-05-26T15:51:19.963",
"Id": "2631",
"Score": "27",
"Tags": [
"javascript",
"game",
"dom"
],
"Title": "Self-playing Baseball game"
}
|
2631
|
<p>I am new to the world of coding as well as CSS. This is my first attempt to put together a page that required a negative value. I am aware that it is recommended that paddings do not use negative values and it is acceptable for margins to use negative values however am unsure if my use of negative values is acceptable.</p>
<p><strong>Notes</strong></p>
<ul>
<li>I am using an internal stylesheet so that I can easily and quickly change values rather than switching between files.</li>
<li>This is the first time I used a reset stylesheet by using import</li>
</ul>
<p>I appreciate any constructive criticisms as well as what I can do better with my coding.</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="en-us" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Sample</title>
<link rel="icon" type="image/png" href="" />
<link rel="stylesheet" type="text/css" href="" />
<style type="text/css" media="all">
@import url('http://meyerweb.com/eric/tools/css/reset/reset.css');
body {
font-family: Georgia;
font-size: 1em;
}
#wrapper {
/* background-color: #FAEBD7; */
width: 960px;
margin: 0px auto;
}
#innerwrapper {
/* background-color: #CDC0B0; */
overflow: auto;
}
#header {
/* background-color: #8B8378; */
}
#logo {
background-color: #000000;
float: left;
width: 100px;
height: 70px;
color: #ffffff;
text-align: center;
padding-top: 30px;
}
#topnav {
/* background-color: #8B8970; */
float: right;
margin-top: 50px;
width: 300px;
text-align: right;
}
#status {
/* background-color: #808080; */
width: 100px;
position: relative;
top: -80px;
left: 800px;
text-align: center;
}
#topnav ul {
word-spacing: 5px;
}
#topnav ul li {
display: inline;
}
#separator {
border-bottom: 1px dashed gray;
margin-top: 20px;
}
#content {
/* background-color: #68838B; */
overflow: hidden;
margin-top: 60px;
}
#innercontent {
/* background-color: #778899; */
float: left;
width: 600px;
}
#rightcol {
/* background-color: #CDCDB4; */
float: right;
width: 300px;
}
#rightcol p + p {
margin-top: 1em;
}
#footer {
/* background-color: #CDB7B5; */
margin-top: 20px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="innerwrapper">
<div id="header">
<div id="logo">logo</div>
<div id="topnav">
<ul>
<li>about</li>
<li>browse</li>
<li>join</li>
<li>faq</li>
<li>contact</li>
</ul>
</div>
<div id="status">login</div>
</div>
</div>
<div id="separator"></div>
<div id="content">
<div id="innercontent">
Lorem ipsum dolor sit amet, at elementum neque vestibulum sollicitudin semper neque, vitae metus. Nibh ligula mi. Faucibus rutrum elit turpis, nec congue quam ipsum felis neque et, wisi amet, architecto eros congue. Maecenas suspendisse tellus arcu eget pharetra, rhoncus aenean sapien morbi nec arcu, vivamus aliquet lorem amet at, vestibulum purus sociis varius id. Imperdiet id magnis turpis beatae aliquet, vestibulum dolor nec eget eu cras lobortis, vel rerum, risus sed et, libero et non eros commodo. Taciti eu leo sollicitudin malesuada, nibh duis amet aenean, odio aptent ultrices. Tristique morbi nunc ullamcorper ut curabitur. Et a in ut sem varius, sem rutrum vehicula sem sed, at diam amet erat vel. Et sit in ante felis vitae sit.
Quam eget sed elit natoque velit, enim mauris mauris urna, integer amet tellus illo ipsum, dolor fermentum cursus enim mollis tristique porttitor. Non dignissim. Sit ligula leo tincidunt, justo ut ut placerat quisque non, risus nonummy. Ultrices mauris congue aliquam aliquam felis, at placerat, amet vestibulum dictumst pellentesque iaculis risus. Sem sed impedit nullam ultrices lorem aliquam, nulla tellus consequatur in ornare magna. Viverra amet pede in in ornare eu, id arcu. Justo mus suspendisse praesent et, amet mattis convallis ullamcorper felis, fermentum nibh at ac, ullamcorper ipsum auctor et maecenas, aliquam molestiae in qui. Massa elit suspendisse penatibus molestie libero dolor, non leo vitae, sollicitudin a, platea tristique iaculis, tortor augue non est. Ante rutrum quis pellentesque lacinia convallis non, vestibulum nibh nunc luctus nibh a, in amet, iaculis dui ornare pede laoreet eu. Cursus integer vehicula quis, justo eget purus mattis donec vestibulum nunc, nunc vel eros lectus.
</div>
<div id="rightcol">
<p>paragraph1</p>
<p>paragraph2</p>
</div>
</div>
<div id="footer">footer</div>
</div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T21:05:41.333",
"Id": "4143",
"Score": "0",
"body": "http://jsbin.com/ufuze3/"
}
] |
[
{
"body": "<p>Your use of negative values in this example is perfectly acceptable; you're locating a <code>relative</code> positioned element.</p>\n\n<p>You could improve the structure of the page with the addition of headers (e.g. change <code><div id=\"logo\">logo</div></code> to <code><h1>logo</h1></code>; use <code><hr /></code> rather than <code><div id=\"separator\"></div></code>; etc.). <em>Build</em> the page without any style to start with, then start <em>designing</em> it.</p>\n\n<p>Importing the reset CSS is okay, but there's no reason not to copy it locally as well.</p>\n\n<p>And I know this just a mock-up page, but don't forget to flesh out <code>font-family</code>. If you like Georgia, I'd go for <code>font-family: Constantia, \"Lucida Bright\", Lucidabright, \"Lucida Serif\", Lucida, \"DejaVu Serif,\" \"Bitstream Vera Serif\", \"Liberation Serif\", Georgia, serif;</code> (which comes from Aaron Boodman's <a href=\"http://blogs.sitepoint.com/eight-definitive-font-stacks/\">8 Definitive Web Font Stacks</a> article).</p>\n\n<p>All up, I'd say you're absolutely on the right track!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T09:53:44.760",
"Id": "4153",
"Score": "0",
"body": "@Sam - Thanks. In terms of professionalism, how would you rate my coding? Also I didn't quite follow what you meant by `but there's no reason not to copy it locally as well`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T05:49:10.377",
"Id": "4184",
"Score": "0",
"body": "Just that you're importing a stylesheet from meyerweb.com, and I'd usually copy something like that to reside next to the rest of the site's stylesheets (and then run them all through some sort of combining utility, to reduce the number of client requests). Of course, you do point out that you're using internal styles for ease of development, so I guess the `@import` is in the same vein."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T05:56:07.363",
"Id": "4185",
"Score": "0",
"body": "As for professionalism (and taking the comments I made above into consideration), I'd say that your code is probably a bit above average. The main things I notice to be lacking are HTML strucuture, and some more advanced typographical considerations (which is far too big a topic to go into in a comment!)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T05:35:11.397",
"Id": "2648",
"ParentId": "2633",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "2648",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T18:26:21.780",
"Id": "2633",
"Score": "6",
"Tags": [
"html",
"css"
],
"Title": "CSS with negative values"
}
|
2633
|
<p>This is a Perl program intended for my chemistry class. Since I am just learning to write in Perl, which is my first language, can you tell me if you think that this is well written? If not, could you tell me what is wrong with it or what could be improved?</p>
<pre><code>## Name:Titration
## Beginning of Program
#Input Variables
system "clear"; # Clear the Screen
print "Milliliters Solute: ";
chomp ($milliliters_solute=<>);
print "Milliliters Solvent: ";
chomp ($milliliters_solvent=<>);
print "Molarity of Solvent: ";
chomp ($molarity_solvent=<>);
print "Moles of Solute: ";
chomp ($moles_solute=<>);
print "Moles of Solvent: ";
chomp ($moles_solvent=<>);
system "clear"; # Clear the Screen
#Calculate Answer
$liters_solute=$milliliters_solute/1000;
$liters_solvent=$milliliters_solvent/1000;
$molarity=($liters_solute/$liters_solvent)*($molarity_solvent/1)*($moles_solvent/$moles_solute);
#Print Answer
system "clear"; # Clear the Screen
print "Molarity is $molarity \n";
## End of Program
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T23:37:53.773",
"Id": "4144",
"Score": "2",
"body": "Why are you dividing by one? Also, you don't need to clear the screen before and after calculating the answer because you don't output anything there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T23:43:02.060",
"Id": "4146",
"Score": "1",
"body": "For a test program, it may be enough. If you ever plan to add more functionality, then you may want to begin using Alan's advise, and then making things modular (like using functions, etc.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T09:00:58.157",
"Id": "4152",
"Score": "0",
"body": "pleas, Anonymous, it's Perl. PERL is what they wrote in the 90s ;) Also, it's wrong: http://perldoc.perl.org/perlfaq1.html#What%27s-the-difference-between-%22perl%22-and-%22Perl%22%3f"
}
] |
[
{
"body": "<p>One suggestion, use</p>\n\n<p><code>use warnings;</code></p>\n\n<p><code>use strict;</code></p>\n\n<p>Will force you to be a better perl programmer, by enforcing more rigidity to your scripts, and have the intepreter catch any nasty issues that might be otherwise hard to debug.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T23:37:26.893",
"Id": "2639",
"ParentId": "2638",
"Score": "13"
}
},
{
"body": "<p>There isn't much to it but as a first program in any language it looks fine - reasonable use of comments (could be a little more verbose with them but it isn't really necessary for such a short application), code is readable.</p>\n\n<p>If I were to suggest a single change it would be to learn to style things in functions rather than a pure linear flow of code. This will make your code easier to reuse later and for more complicated programs, easier to reuse portions within them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T23:37:57.877",
"Id": "2640",
"ParentId": "2638",
"Score": "1"
}
},
{
"body": "<p>Beyond what's been mentioned, I can suggest following a few formatting conventions to make your life easier in the long run:</p>\n\n<ul>\n<li><p>Keep lines to a reasonable length, inserting line breaks at logical points where necessary. This helps avoid having to scroll horizontally, as well as improving readability. 80 columns is generally accepted as the standard right margin for most code.</p></li>\n<li><p>Insert spaces around infix operators to improve legibility:</p>\n\n<pre><code>$liters_solute = $milliliters_solute / 1000;\n</code></pre></li>\n<li><p>Don't put extra whitespace around escapes in strings, because...well, it's extra, and it's significant, and while it doesn't really matter here (at the end of a line), it's a good thing to pay attention to in the future.</p>\n\n<pre><code>print \"Molarity is $molarity\\n\";\n</code></pre></li>\n<li><p>Don't put extra whitespace before function arguments:</p>\n\n<pre><code>chomp($milliliters_solute = <>);\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T04:30:00.993",
"Id": "2646",
"ParentId": "2638",
"Score": "7"
}
},
{
"body": "<p>Use these. At first they will make things harder, because you'll get a few error messages, you'll need to declare all variables with <code>my</code>, etc. But very quickly they will make your life better.</p>\n\n<pre><code>use strict;\nuse warnings;\n</code></pre>\n\n<p>Whenever you see repetitive code, consider writing a <a href=\"http://perldoc.perl.org/perlsub.html\">subroutine</a>.</p>\n\n<pre><code>sub get_user_input {\n my $message = shift;\n print $message, ': ';\n chomp(my $reply = <>);\n return $reply;\n}\n</code></pre>\n\n<p>Example usage.</p>\n\n<pre><code>my $milliliters_solute = get_user_input('Milliliters Solute');\nmy $milliliters_solvent = get_user_input('Milliliters Solvent');\n</code></pre>\n\n<p>Good luck with your studies. One of my favorite teachers went by the name <strong>The Mole Man</strong> -- you can tell what subject he taught.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T11:37:22.733",
"Id": "2654",
"ParentId": "2638",
"Score": "11"
}
},
{
"body": "<p>You've made an excellent start. Your comments are clear and your variable names are good.</p>\n\n<p>I've made a much fancier version of your code that you might find useful to look at.</p>\n\n<p>First thing I did was add a 'she-bang' line: <code>#!/blah/blah/blah</code>. On unix systems, this is used to identify the interpreter. On windows its mostly useless, but windows perls can detect command line options that may be specified there.</p>\n\n<p>Next I laid in some POD describing your program. My chemistry knowledge sucks, so I probably screwed up the description horribly. </p>\n\n<p>Then I added the 'strict' and 'warnings' pragmas, which make perl much pickier about things that are often indicators of bugs.</p>\n\n<p>Next I put in some stuff to handle printing a usage message when someone says <code>script --help</code> or <code>script -?</code>. Now the script will print some useful info.</p>\n\n<p>Then I took a bunch of repeated stuff (your print/chomp input collection) and wrapped it into subroutines. </p>\n\n<p>I also wrapped up the calculation, but used a common idiom that gives subroutines named, rather than positional parameters. This is good thing to do when you have many parameters to pass.</p>\n\n<p>Finally, I slipped in a subroutine to handle displaying the results. I used an interesting bit of relatively advanced technology to format the output.</p>\n\n<pre><code>#!/usr/bin/perl\n\n=head1 Name\n\ntitration\n\n=head1 SYNOPSIS\n\nA simple titration calculator.\n\nInteractively requests information from the user and \ncalculates the molarity of a solution.\n\n=cut\n\nuse strict;\nuse warnings;\n\nuse Pod::Usage;\nuse Getopt::Long;\n\n\n# Handle command line args / help requests.\nmy $help;\n\nGetOptions( 'help|?' => \\$help )\n or pod2usage(2);\n\npod2usage(0) if ($help);\n\n# The real program. I go back and forth over having a 'main' sub like a C program.\n\nmy %raw_data = collect_user_data();\n\nmy $molarity = calculate_molarity(\n ml_solvent => $raw_data{'Milliliters Solvent'},\n ml_solute => $raw_data{'Milliliters Solute'},\n molarity_solvent => $raw_data{'Molarity Solvent'},\n moles_solvent => $raw_data{'Moles Solvent'},\n moles_solute => $raw_data{'Moles Solvent'},\n);\n\ndisplay_result( \"Molarity is $molarity\" );\n\nexit;\n\n# Subroutines ------------------------------------------\n\n# Print an message and get a response.\nsub get_user_response {\n my $question = shift;\n\n chomp $question; # Make sure we don't have any messy newlines.\n print \"$question: \";\n\n my $answer = <STDIN>;\n chomp $answer;\n\n return $answer;\n}\n\n\n# Ask for all the user data and store them in a hash.\nsub collect_user_data {\n\n system \"clear\"; # Clear the Screen\n\n my %data;\n\n for my $unit (\n 'Milliliters Solute', 'Milliliters Solvent',\n 'Molarity Solvent',\n 'Moles Solute', 'Moles Solvent'\n ) {\n $data{$unit} = get_user_response( \"Please enter the $unit\" );\n }\n\n system \"clear\"; # Clear the Screen\n\n return %data;\n}\n\nsub display_result {\n\n system \"clear\"; # Clear the Screen\n\n # this is confusing magic that prints each argument with a trailing \"\\n\".\n # Understand this and you have learned MUCH.\n print map \"$_\\n\", @_;\n}\n\n# Do the molarity calculation\n# Expects name / value pairs of arguments.\n# \n# Arguments must include:\n# molarity_solvent\n# ml_solute \n# ml_solvent \n# moles_solvent \n# moles_solute\n\nsub calculate_molarity {\n my %arg = @_;\n\n my $molarity = $arg{molarity_solvent}\n * ( $arg{ml_solute} / $arg{ml_solvent} )\n * ( $arg{moles_solvent} / $arg{moles_solute} )\n ;\n\n return $molarity;\n}\n</code></pre>\n\n<p><strong>\"Oh, gee, thanks, but how the heck am I going to understand this?\"</strong> you may be thinking. Well, perldoc is a great help. As is asking questions. <a href=\"http://perldoc.perl.org/\">perldoc.perl.org</a> is a great resource for searching and reading Perl's documentation.</p>\n\n<p>Check out the perlvar article for information on special variables. Of the many available, four are worth learning IMO. (<code>$_</code>, <code>@_</code>, <code>$!</code> and <code>$@</code>, if you care) For everything else, there's perlvar.</p>\n\n<p>perlfunc is the function reference. My favorite section as a newbie to Perl was <a href=\"http://perldoc.perl.org/perlfunc.html#Perl-Functions-by-Category\">Functions by Category</a>.</p>\n\n<p>Don't forget about Stack Overflow, and most especially <a href=\"http://perlmonks.org/\">Perlmonks.org</a>. These sites are great places to ask for help. Perlmonks is the great grand-daddy of SO, and such sites, it's decade-plus library of Q&A has a lot to offer, plus the people there are very friendly and helpful. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-16T22:09:47.577",
"Id": "10823",
"Score": "0",
"body": "I usually use `say for @_;` instead of `print map \"$_\\n\", @_;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-01T22:15:27.387",
"Id": "13390",
"Score": "0",
"body": "Still stuck with Perl 5.8 in too many places to start reaching for `say`. One day I will be able to rely on my Perl interpreter being reasonably modern. At least I no longer have to target anything older than 5.6."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T02:26:07.890",
"Id": "2672",
"ParentId": "2638",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T23:34:18.737",
"Id": "2638",
"Score": "14",
"Tags": [
"beginner",
"perl"
],
"Title": "Chemistry titration calculator"
}
|
2638
|
<p>I am implementing RSA in java using BigInteger and I have a method to return a random relative prime number based on the modulus m. </p>
<p>The method looks like this:</p>
<pre><code>BigInteger prime = new BigInteger(m.bitLength(),rnd);
while (prime.compareTo(BigInteger.ZERO) <= 0 || !prime.gcd(m).equals(BigInteger.ONE) )
{
prime = new BigInteger(m.bitLength(),rnd);
}
</code></pre>
<p>Is there anyway to make this more efficient? I dont know if recreating an object like this is bad or not.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T15:24:34.547",
"Id": "4166",
"Score": "0",
"body": "At least you can rewrite it as a do ... while loop. Could you be more precise about efficiency? What concrete problems do you have?"
}
] |
[
{
"body": "<p>What is m.bitLength, and how often do you get a <= 0 or an gcd-1? </p>\n\n<p>Why do you think creating an object in the loop could be bad? Performance? Memory wise? </p>\n\n<p>An object is ready for garbage collection as soon as it is unreachable and out of scope. </p>\n\n<p>So the second object, if the first one fits the condition, will hide the first one - the first one is out of scope, and unreachable. </p>\n\n<p>For a cheap object like a BigInteger, you may worry if you produce millions and millions of Objects in one second, over and over again. Maybe then, if you experience a performance problem, you can measure and find out, where it happens. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T02:30:59.433",
"Id": "2642",
"ParentId": "2641",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2642",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T01:45:46.960",
"Id": "2641",
"Score": "4",
"Tags": [
"java",
"performance",
"primes",
"cryptography"
],
"Title": "A random relative prime number based on the modulus"
}
|
2641
|
<p>I would love some feedback on this little utility function:</p>
<pre><code>/**
* Copy $src to $dest, renaming it if the desired destination already exists. The
* string '.versionX' is inserted before the file extension if a file must be
* renamed, with X incremented as needed.
*
* @return boolean true if copy was successful, false otherwise.
*/
public static function copy_with_rename($src, $dest)
{
if (file_exists($dest))
{
// See if it's the same.
$existingFileHash = sha1_file($dest);
$new_file_hash = sha1_file($src);
if ($existingFileHash != $new_file_hash)
{
// File of same name exists, but is different.
$last_dot_pos = strrpos($dest,'.');
$file_count = 2;
// So find a new name.
do
{
$base_name = substr($dest, 0, $last_dot_pos);
$ext = substr($dest, strlen($base_name)); // with dot
$new_name = $base_name.'.version'.$file_count.$ext;
$file_count++;
} while (file_exists($new_name) && sha1_file($src)!=sha1_file($new_name));
// And then try the copy again, with the new name.
return file::copy_with_rename($src, $new_name);
} else
{
return true;
}
} else
{
$dest_dir = dirname($dest);
// Create (to any depth) the destination directory, if required.
if (!file_exists($dest_dir))
{
mkdir($dest_dir, 0777, true);
}
// And finally do the actual copy.
return copy($src, $dest);
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Original Answer:</strong></p>\n\n<p>I'd put in some extra brackets in your while-loop for radability:</p>\n\n<pre><code>while ( file_exists($new_name) \n && (sha1_file($src) != sha1_file($new_name))\n );\n</code></pre>\n\n<p>And you shouldn't set file-permissions to <code>777</code> by default (<code>660</code> or even less). Everything else looks quite ok in my eyes (although I don't like the <code>do/while</code> construct, but I guess that's more a personal thing)</p>\n\n<p><strong>Update for comment:</strong></p>\n\n<pre><code>$srcSH1 = sha1_file($sec);\ndo\n{\n // ...\n}\nwhile ( file_exists($new_name) \n && (sha1_file($new_name) != $srcSH1)\n );\n</code></pre>\n\n<p>You should move out the sha_file($src) as this doesn't change but is recalculated each iteration. And that's the case why I don't like <code>do/while</code>. Splits the <code>$srcSH1</code> and the while-condition where it is used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T03:29:35.583",
"Id": "4210",
"Score": "0",
"body": "Thanks for reviewing! I might just change the while() to do the two clauses separately, for easier reading:\n\n $already_exists = file_exists($new_name);\n $is_different = sha1_file($src) != sha1_file($new_name);\n} while ($already_exists && $is_different);\n\nI know what you mean about do-while: I guess it's just not all *that* widely used (and familiar), so it can take a moment to see what's happening. But in this case, it's the cleanest way.\n\nAnd I'll change the permissions to 600 (don't know why the default for mkdir() is 0700; I was using this on Windows anyway, so didn't think about it)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T03:30:16.660",
"Id": "4211",
"Score": "0",
"body": "(erg. forgot that comments have crap formatting!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T09:04:14.277",
"Id": "4214",
"Score": "0",
"body": "@Sam: It's fine to have that kind of statements in while-loops. Just make sure to format the loop correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T23:50:31.813",
"Id": "4229",
"Score": "0",
"body": "Good point about moving the hash out of the loop — and then it can also be used in the if clause above."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T10:39:45.470",
"Id": "2692",
"ParentId": "2647",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T04:42:44.190",
"Id": "2647",
"Score": "4",
"Tags": [
"php"
],
"Title": "Copy a file, renaming it if the destination already exists."
}
|
2647
|
<blockquote>
<p><strong><em>There's a follow-up:</strong> <a href="https://codereview.stackexchange.com/questions/3197/waiting-for-a-lock-to-release-with-manualresetevent-and-quartz">Waiting for a lock to release with ManualResetEvent and Quartz.</a></em></p>
</blockquote>
<p>I've written a simple Lock-Mechanism which is saving the states of the locks in a database. Now I need to wait for a <code>Lock</code> to release or timeout after a certain amount of time (blocking the main thread, this is intentional). My implementation is looking like this:</p>
<pre><code>/// <summary>Waits for the lock to be released within the given timeout.</summary>
/// <param name="lockName">The name of the lock.</param>
/// <param name="timeout">The timeout in seconds.</param>
/// <returns>True if the Lock was released.</returns>
public bool waitForLock(String lockName, Int32 timeout)
{
// IsLocked(String) does query the database for the status
while(locker.IsLocked(lockName) && timeout > 0)
{
Threading.Thread.Sleep(1000);
timeout--;
}
return !locker.IsLocked(lockName);
}
</code></pre>
<p>I always get a little bit itchy if I have to use <code>Thread.Sleep</code>, but I'm not sure why.</p>
<p>Is something wrong with this design/approach and will it bite me later? Or is there a better way to handle this?</p>
<p><strong>Edit:</strong> Further clarifications: I have full control over the <code>locker</code> and anything affiliated with it. The main intention for this is to make sure that certain operations will not overlap, each of these operations should be taking well less then 5 seconds. The load on the server is not really an issue, because the realistic maximum number of clients simultaneous waiting for a lock could be 10 (in my case).</p>
<p>The blocking of the thread is not as intentional is I have stated. The best thing would be if I could keep the message pumping still active, but I fail to see how I can achieve that goal in combination with polling the database (and without the need to introduce a timer with a callback).</p>
<p><strong>Edit2:</strong> The locked part is not the database, the database is only holding the status of the locks. I'm using this locking system to make sure that no operation protected by this can execute at the same time on different client machines.</p>
|
[] |
[
{
"body": "<p>The function might block up to one second too long (if the lock is released, just after it enters Sleep).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T10:26:47.297",
"Id": "4155",
"Score": "0",
"body": "This may or may not be noticeable depending on how it's used. (lock held for minuets with infrequent collisions or locks held for fractions of a second with frequent collisions)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T10:06:43.970",
"Id": "2652",
"ParentId": "2650",
"Score": "4"
}
},
{
"body": "<ul>\n<li><p>1sec may be fine, but the best choice will depend on it's usage characteristics. I recommend trying different values on a test system under expected production load.</p></li>\n<li><p>Sleep does not perform standard COM and SendMessage pumping. If you are not calling this on the main GUI thread then that's fine, otherwise the application may appear unresponsive.</p></li>\n<li><p>I'm a little uneasy about the use of the timeout as a loop count. Sleep is only guaranteed to not return before the timeout and may sleep longer. I suppose it's probably not likely to be a real issue though.</p></li>\n<li><p>It's normal for method names in C# to be PascalCased rather than cammelCased.</p></li>\n</ul>\n\n<p>I also have some points about the locker object, but I'm not sure how much control you have over it.</p>\n\n<ul>\n<li><p>Your usage of IsLocked() seems to imply that it attempts to acquire the lock, but the name implies that it only checks that you already have it. Maybe <code>GetLock()</code> or <code>AcquireLock()</code> would be a better name.</p></li>\n<li><p>Are locks released if not renewed periodically? If the application holding the lock closes it's db connection/terminates abruptly, will the lock be released in a timely fashion without intervention?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T12:03:29.340",
"Id": "4158",
"Score": "0",
"body": "I'm aware that `Sleep` will block everything, but I fail to see another solution in such a use-case (see my edit). The camelCase is a typo, sorry, I'll leave it in as future reference. `IsLocked()` does only check for the status, it's not intended to acquire it in any way. And your note with the releasing of the locks is a good call at something I haven't spend much thought about by now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T23:11:37.237",
"Id": "4174",
"Score": "0",
"body": "@Bobby, what do you intend to do once your method returns? If you want to acquire the lock then you would be better off with something that checks and acquires as a single atomic operation to prevent excess checks, or worse, a race condition. If you do not intend to acquire the lock it should be fine, but be aware that the lock could be re-acquired by another user by the time you leave the method."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T10:20:27.150",
"Id": "2653",
"ParentId": "2650",
"Score": "3"
}
},
{
"body": "<p>An easier answer might be to use a <code>ManualResetEvent</code>. You can block the current thread for a timeout period until another thread signals the <code>ManualResetEvent</code>. </p>\n\n<p><a href=\"http://philiprieck.com/blog/archive/2004/01/27/WaitHandleSample.aspx\" rel=\"nofollow\">http://philiprieck.com/blog/archive/2004/01/27/WaitHandleSample.aspx</a></p>\n\n<p><a href=\"http://www.yoda.arachsys.com/csharp/threads/waithandles.shtml\" rel=\"nofollow\">http://www.yoda.arachsys.com/csharp/threads/waithandles.shtml</a></p>\n\n<p>Basically, blocking thread calls <code>mre.Wait()</code>, processing thread works until it calls <code>mre.Set()</code>. No sleeping, none of this other stuff. </p>\n\n<p>An important note, always <code>Dispose</code> of your <code>ManualResetEvent</code>s. Leaking handles is a bad call, this object reaches out into the COM world. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T12:48:38.880",
"Id": "4159",
"Score": "0",
"body": "Very nice. But do you have an idea how I could poll the database in the other thread to signal something back? The only thing which comes into my mind is a simple timer which gets called `x` times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T13:51:20.053",
"Id": "4162",
"Score": "0",
"body": "What you are looking for is a way to for one thread to sit and wait while another pools the db, then execute something once data is retrieved from the db? Have you considered using something like MSMQ for events instead of pooling the db? You could use an actor based model as well. What about just having the main thread pool and when it finds a new record, spin off a new thread to process it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T23:22:29.157",
"Id": "4175",
"Score": "0",
"body": "I like the idea of a separate thread, but would recommend also putting the operation dependent on the lock into the background thread rather than just the lock check. The results of the operation can be marshaled back to the main GUI thread to update the user. This would also remove the need for the `ManualResetEvent`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T01:22:49.870",
"Id": "9682",
"Score": "0",
"body": "@ANeves Does that help?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T09:27:22.090",
"Id": "9706",
"Score": "0",
"body": "Quite! I tried editing, but there really wasn't more to it to improve and the system wouldn't let me correct your post with only whitespace changes. ;) [[previous comment deleted]]"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T12:19:14.137",
"Id": "2657",
"ParentId": "2650",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "2657",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T08:08:14.483",
"Id": "2650",
"Score": "11",
"Tags": [
"c#",
"locking"
],
"Title": "Waiting for a lock to release with Thread.Sleep()?"
}
|
2650
|
<p>I'm wondering if I could handle the following situation with a single function or regex call. Given the folowing input:</p>
<pre><code>Some text
> Foo
> Bar
>> Baz
> Foo
</code></pre>
<p>The output should be:</p>
<pre><code>Some text
<blockquote>
Foo
Bar
<blockquote>
Baz
</blockquote>
Foo
</blockquote>
</code></pre>
<p>The following two functions do handle this situation, but I think there must be a more elegant way to handle it. I thought about regular expressions, but could not think of any pattern that replaces the input with the output (see above).</p>
<pre class="lang-php prettyprint-override"><code><?php
function toArray($str, $currLevel = 0, $i = 0) {
$return = array();
$lines = explode("\n", $str);
for($j = count($lines); $i < $j; $i++) {
$line = trim($lines[$i]);
$level = preg_replace('/^((?:>|\s)+).*/','\1', $line);
$level = substr_count($level, '>');
if($level == $currLevel) {
array_push($return, preg_replace('/^((?:>|\s)+)(.*)/','\2', $line));
}
else if($level > $currLevel) {
array_push($return, toArray(join("\n", $lines), $currLevel + 1, &$i));
} else if($level < $currLevel) {
$i--;
return $return;
}
}
return $return;
}
function toQuote($lines) {
$return = "<blockquote>\n";
foreach($lines as $line) {
if(is_array($line)) {
$return .= toQuote($line);
}
else {
$return .= $line . "\n";
}
}
$return .= "</blockquote>\n";
return $return;
}
$str = <<<INPUT
Some text
> Foo
> Bar
>> Baz
> Foo
INPUT;
echo toQuotes(toArray($str));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T03:35:45.920",
"Id": "4212",
"Score": "0",
"body": "Don't know if it's of any help, but Markdown does this; however, only with a newline after the inner quote."
}
] |
[
{
"body": "<p>This isn't much more elegant, but maybe you like it:</p>\n\n<pre><code>$text = \"Some text\n\n> Foo\n> Bar\n>> Baz\n> Foo\n\";\n\nfunction clean($text) {\n $result = \"\";\n $lines = explode(\"\\n\", $text);\n foreach($lines as $key => $line) {\n $lines[$key] = preg_replace('/(>)+ /', '', $line);\n }\n return join(\"\\n\", $lines);\n}\n\nfunction quotes($text, $level = 1) {\n $search = str_repeat(\">\", $level);\n $fstpos = strpos($text, $search);\n $sndpos = strrpos($text, $search);\n $sndpos = strpos($text, \"\\n\", $sndpos);\n $middle = substr($text, $fstpos, $sndpos + 1);\n if($fstpos === false or $sndpos === false)\n return clean($middle, $search);\n $fst = clean(substr($text, 0, $fstpos), $search);\n $snd = clean(substr($text, $sndpos), $search);\n return $fst . \"<blockquote>\\n\" . quotes($middle, $level + 1) . \"</blockqoute>\" . $snd;\n}\n\necho quotes($text);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T23:43:10.257",
"Id": "2793",
"ParentId": "2655",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T11:42:45.450",
"Id": "2655",
"Score": "4",
"Tags": [
"php"
],
"Title": "Wrap email quotes with html element"
}
|
2655
|
<p>I am learning C++ on my own and was hoping for some feedback on this simple text-to-binary converter. The program runs and I haven't encountered any errors with it yet. Any input is welcome. </p>
<pre><code>#include <iostream>
#include <string>
#include <bitset>
using namespace std;
int main()
{
char letter = ' ', playAgain = 'y';
string word = " ";
cout << "\t**Text To Binary Convertor**\n\n";
while (playAgain == 'y'){
cout << "Please enter a character, word, or phrase: ";
getline (cin, word, '\n');
cout << "\nThe binary value for " << word << " is \n";
for (unsigned int wordPosition = 0; wordPosition < word.size(); ++wordPosition){
letter = word[wordPosition];
bitset <8> binary(letter);
cout << binary;
}
cout << "\n\nWould you like to try again? (y/n)";
cin >> playAgain;
if (playAgain != 'y'){
cout << "\n\nExiting program.";
playAgain = 'n';
}
cin.ignore();
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks good overall. Just a couple comments...</p>\n\n<p>When writing C++ code, you generally use \"endl\" instead of \"\\n\" to terminate lines.</p>\n\n<pre><code>cout << \"hi\" << endl;\n</code></pre>\n\n<p>Also, to print out the ascii value of the character you don't necessary the \"char\" value into another variable. In your case, you are copying it twice. You can print an ascii value directly from the string by using a cast.</p>\n\n<pre><code>cout << (unsigned short)word[wordPosition] << endl;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T16:19:32.953",
"Id": "4167",
"Score": "8",
"body": "`\"\\n\"` to terminate lines is just fine. It speeds things up too by not forcing needless flushes. And your cast is more-or-less equivalent to the original example with a named variable. Casts copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T16:21:06.957",
"Id": "4168",
"Score": "2",
"body": "And the compiler should get rid of the extra copy. Plus I don't think he's printing ASCII values numerically, I think he's printing them in base-2 (individual bits)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T16:29:39.497",
"Id": "4169",
"Score": "0",
"body": "@Ben Thanks for the code review site. And thanks to all for your help. Sorry about this misplaced post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T06:31:13.347",
"Id": "70110",
"Score": "0",
"body": "-1 for the same reasons as Lightness."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T16:13:00.593",
"Id": "2662",
"ParentId": "2661",
"Score": "2"
}
},
{
"body": "<p>I don't see anything obviously wrong with the code, so that's a good start.</p>\n\n<p>You're using a very unusual brace indentation style. Wikipedia calls it <a href=\"http://en.wikipedia.org/wiki/Indent_style#Banner_style\">Banner Style</a> but I don't think I've ever seen it before.</p>\n\n<p>You're checking for <code>playAgain != 'y'</code> in two different places, which is redundant and could lead to bugs if one of them is modified. I'd move that whole second block outside of the main loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T16:40:05.037",
"Id": "4170",
"Score": "0",
"body": "Thanks - I'm not sure where the indentation style I am using came from. I've been using a number of books from the library and on-line sources. Now that I look at the books again, they don't use that style. weird."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T16:34:27.517",
"Id": "2663",
"ParentId": "2661",
"Score": "8"
}
},
{
"body": "<p>As already mentioned, your code is looking okay. Here are my additions:</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">It's best not to use <code>using namespace std</code></a>.</p></li>\n<li><p>Variables should be declared/initialized on their own line:</p>\n\n<pre><code>char letter = ' ';\nchar playAgain = 'y';\n</code></pre></li>\n<li><p>You don't need a newline between every line of code. This will just make your program appear longer and harder to read. Just separate lines into groups based on purpose.</p></li>\n<li><p>Variable declarations/initializations should be placed as close in scope as possible to where they will be first used:</p>\n\n<pre><code>std::cout << \"Please enter a character, word, or phrase: \";\nstd::string word; // declaration is first used here\ngetline(std::cin, word, '\\n');\n</code></pre></li>\n<li><p>Your main loop could use <code>for (;;)</code>. This is essentially an infinite loop, <em>but</em> it should do a <code>break</code> at the end if the user inputs a value other than 'Y':</p>\n\n<pre><code>for (;;)\n{\n // do stuff\n\n std::cout << \"\\n\\nWould you like to try again? Y/N)\";\n char playAgain;\n playAgain = std::toupper(playAgain);\n std::cin >> playAgain;\n std::cin.ignore();\n\n if (playAgain != 'Y')\n {\n break;\n }\n\n // playAgain is 'y', so do stuff again\n}\n</code></pre></li>\n<li><p>Prefer to use <code>std::string::size_type</code> for the inner <code>for</code>-loop as it's the type returned from <code>std::string::size()</code>.</p>\n\n<p>Or if you have C++11, use a <a href=\"http://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-based <code>for</code> loop</a> instead:</p>\n\n<pre><code>for (auto iter& : word)\n{\n letter = iter;\n\n // ...\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T11:00:24.240",
"Id": "70147",
"Score": "0",
"body": "anything wrong with `for(char playAgain='y';playAgain=='y';std::cin >> playAgain,std::cin.ignore())` I think there is something to be said for putting the control flow up at the top, since that is what it is for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T01:13:32.963",
"Id": "29576",
"ParentId": "2661",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "2663",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T15:57:03.817",
"Id": "2661",
"Score": "14",
"Tags": [
"c++",
"converting",
"console"
],
"Title": "Simple text-to-binary converter written in C++"
}
|
2661
|
<p>I am learning OOP and have written a class for Likes. There is a load, add, delete method and I think this code can be improved since there is a lot of duplication. Please let me know how I can improve on this code and secure this code:</p>
<p>fileA.php:</p>
<pre><code>include_once dirname(__FILE__) . "/like.class.php";
$like = new Like($db);
if (isset($_POST['add'])):
$like->addLikes();
elseif (isset($_POST['delete'])):
$like->unLikes();
else:
$like->loadLikes();
endif;
</code></pre>
<p>like.class.php</p>
<pre><code> public function loadLikes() {
$sql = //sql query
try
{
$imageid = $_POST['imageid'];
$imageid = htmlentities($imageid, ENT_QUOTES);
$author = $_POST['author'];
$author = htmlentities($author, ENT_QUOTES);
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
$count = $this->countLikes($imageid);
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($row['like'] == '1') {
$like = (array('like' => true));
$response = json_encode(array_merge($count, $like));
echo $response;
return TRUE;
}
elseif ($row['like'] == '2') {
$like = (array('unlike' => true));
$response = json_encode(array_merge($count, $like));
echo $response;
return TRUE;
}
else {
$error = "Invalid";
$response = json_encode(array('like' => false, 'text' => $error));
echo $response;
return FALSE;
}
}
}
else {
$like = (array('unlike' => true));
$response = json_encode(array_merge($count, $like));
echo $response;
return FALSE;
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
public function addLikes() {
$sql = //sql query
try
{
$imageid = $_POST['imageid'];
$imageid = htmlentities($imageid, ENT_QUOTES);
$author = $_POST['author'];
$author = htmlentities($author, ENT_QUOTES);
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
if ($query->rowCount() > 0) {
//update like
$this->updLikes();
}
else {
//insert like
$this->insertLikes();
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
</code></pre>
<p>I have only posted two methods because the other methods in the class all follow the same pattern. Is there anyway I can code this more efficiently reducing duplication? Any other pointers would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T18:04:04.493",
"Id": "4189",
"Score": "0",
"body": "You don't have to enclose your `array`s in `()`. `$like = array('unlike' => true);` is easier to read and type. You should also stick to a standard when writing your syntax, using `TRUE` and `true` looks sloppy."
}
] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ol>\n<li>Keep your try-blocks small</li>\n<li>Always check if your request-parameters are valid</li>\n<li>If you have duplicated code, put it into a private function</li>\n<li>If you're returning data-structures with only some fields changing in your function, define a default strcture and modify the needed values. Return at the end (see 9.)</li>\n<li>Always return all fields with json, thus keep the data-structure always the same</li>\n<li>There is no need to create variables only to echo/return them</li>\n<li><code>false</code> should be written in lower case, as almost everyone does it ;)</li>\n<li>Try to keep the exit-points (return) of a function as little as possible</li>\n<li>Not done bellow, but generally aim for a seperation of database access, application logic (this class) and output (the calle)</li>\n<li>All execution-paths of a function should return the same data-type (as java/c/... enforce you to do)</li>\n</ol>\n\n<p>For example, create a (private) function to clean the parameters:</p>\n\n<pre><code>private private function getCleanParameters()\n{\n return array(\n ':imageid' = htmlentities($_POST['imageid'], ENT_QUOTES),\n ':author' => htmlentities($htmlentities($author, ENT_QUOTES), ENT_QUOTES)\n );\n}\n</code></pre>\n\n<p>Before binding them to your sql-query, you should check them:</p>\n\n<pre><code>private function checkParameters(array $parameters)\n{\n foreach($parameters as $value)\n {\n if(empty($value))\n {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>That'd make your <code>addLikes</code> method to something like this:</p>\n\n<pre><code>public function addLikes()\n{\n $params = $this->getCleanParameters();\n\n if(!$this->checkParameters($params))\n {\n return false;\n }\n\n try\n {\n // Assuming you're perfroming an 'exists'-check here. \n // Could be done at the database-side\n $query = $this->_db->prepare($this->_checkSqlQuery)\n ->execute($params);\n ($query->rowCount() > 0)\n ? $this->updLikes()\n : $this->insertLikes();\n }\n catch(PDOException $ex)\n {\n // Why echo here and not in try? \n // Relying on the 'fact' that the called methods will echo something?\n // Also, the try-block does not return anything, but the catch-block does.\n echo json_encode(array('like' => false, 'text' => $ex));\n return false;\n }\n\n}\n</code></pre>\n\n<p>For the <code>loadLikes()</code> method almost the same rules would apply:</p>\n\n<pre><code>public function loadLikes()\n{\n $params = $this->getCleanParameters();\n $reponse = array(\n // What's the point of having like & unlike at the same time?\n // If you're using unlike as error, better introduce a dedicated field for it\n // better always send all fields as json.\n 'like' => false,\n 'unlike' => false,\n 'error' => false\n 'text' => '',\n 'count' => 0\n );\n\n if(!$this->checkParameters($params))\n {\n $response['error'] = true;\n $response['text'] = 'Invalid Parameters';\n echo json_encode($response);\n return false;\n }\n\n // all your if-statements,... only modifying $response\n\n echo json_encode($reponse);\n return $response['error'];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T01:14:35.183",
"Id": "2687",
"ParentId": "2664",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "2687",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T19:18:31.413",
"Id": "2664",
"Score": "3",
"Tags": [
"php",
"classes",
"object-oriented"
],
"Title": "Improve OOP code"
}
|
2664
|
<p>I have a very good grasp of the syntax and features of F# as well as some of the concepts that mesh well with the language. However, I do not have enough experience writing it to feel comfortable that the way I am handling the language is appropriate. </p>
<p>Ignoring the fact that I do not provide proper escaping functionality for the file format, is there any way I could write this code better? I know that this is a trivial example, but I fear that I might be making things too hard on myself with this code.</p>
<p>Also, is there a way that I could write this more robustly so that adding in an escape sequence for the ";" character would be easier?</p>
<pre><code>module Comments
open System.IO
type Comment = { Author: string; Body: string }
let parseComment (line:string) =
match line.Split(';') with
| [|author; body|] -> Some({Author=author; Body=body})
| _ -> None
let filterOutNone maybe = match maybe with | Some(_) -> true | _ -> false
let makeSome some = match some with | Some(v) -> v | _ -> failwith "error"
let readAllComments () =
File.ReadAllLines("comments.txt")
|> Array.map parseComment
|> Array.filter filterOutNone
|> Array.map makeSome
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T23:06:29.203",
"Id": "4173",
"Score": "2",
"body": "I don't know F#, but does it not have mapMaybe like haskell does? And what about list comprehensions for all those maps and filters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-09T09:22:14.240",
"Id": "15665",
"Score": "2",
"body": "Would help if the question described the problem that the code is intended to solve."
}
] |
[
{
"body": "<p>Look into <a href=\"http://msdn.microsoft.com/en-us/library/ee370619.aspx\"><code>Array.choose</code></a>. Using that function cuts the length of your code in half, because you have basically reinvented it. (I did the same at some point ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T17:06:07.513",
"Id": "4253",
"Score": "0",
"body": "Thanks for the tip :) I would upvote your answer if I had the privileges to do so on this site."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T13:26:09.610",
"Id": "2681",
"ParentId": "2665",
"Score": "6"
}
},
{
"body": "<p>Your <code>makeSome</code> function is confusingly named. The word \"make\" suggests that it will create a <code>Some</code>, but what it actually does is take a <code>Some</code> and then return its value. So it should be called something like <code>getValueFromSome</code> or <code>getValueFromOption</code>. However none of that matters since it's just a reimplementation of the built-in <code>Option.get</code> function, so you should use that.</p>\n\n<p>That being said you actually don't need this function at all if you use <code>Array.choose</code> as wmeyer suggests (which you should). Still if you ever do need this function in a different context, you should use <code>Option.get</code> rather than reimplementing it yourself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T16:03:07.130",
"Id": "2684",
"ParentId": "2665",
"Score": "2"
}
},
{
"body": "<p>Most of your code can be replaced with a comprehension:</p>\n\n<pre><code>type Comment = { Author: string; Body: string }\n\nlet readAllComments () = \n [|for line in System.IO.File.ReadAllLines(\"comments.txt\") do\n match line.Split ';' with\n | [|author; body|] -> yield {Author=author; Body=body}\n | _ -> ()|]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-09T09:25:21.617",
"Id": "9850",
"ParentId": "2665",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "2681",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T22:08:14.470",
"Id": "2665",
"Score": "6",
"Tags": [
"parsing",
"f#"
],
"Title": "Is there any way to improve (shorten) this F# code?"
}
|
2665
|
<p>I have this code which looks for query words in a given text. I preprocess the give text and store it in an inverted-index (dictionary with word as key and position in text as value). Searching for a query words then becomes contant time operation. </p>
<p>The below code also prints the surrounding text which contains the maximum number of queries.</p>
<p>Please help me understand the shortcomings (coding style, naming conventions, performance issues) of the code.</p>
<pre><code># -*- coding: cp1252 -*-
from collections import defaultdict
class c_Highlight():
"""Highlight Class to find and print relevant snippet of a text"""
Grammar_Suffix = ['ing' ,'ly', 'ed', 'ious', 'ies', 'ive', 'es', 's', 'ment']
Punctuation = [',', '!', '.', '?', '"', '\n']
def __init__(self):
self.InvertedIndex = defaultdict( list )
def m_Read_File( self, f_name ):
"""
Function to Read a file, if the text is to be read from file
Args: FileName
Returns: List of words
"""
list_words = []
try:
f = open(f_name)
for line in f:
line = line.strip()
list_words.extend( line.split())
f.close()
except IOError as (errno, strerror):
print "File I/O Error({0}): {1}".format(errno, strerror)
exit(0)
return list_words
def __m_Stem( self, word ):
"""
Function to remove Suffix from the end of a word.
Input: Word
Returns: Cropped Word
"""
word = word.lower()
for suffix in c_Highlight.Grammar_Suffix:
if word.endswith(suffix):
word = word[:-len(suffix)]
break
for punctuation in c_Highlight.Punctuation:
while word.endswith(punctuation):
word = word[:-len(punctuation)]
return word #can be empty list
def m_Create_InvertedIndex( self, words ):
"""
Function to parse the input words and store them in a InvertedIndex
The Key is the word itself and Value is the position of the word in the text
Input: List of Words
Return: None
"""
idx = 0
for word in words:
word = self.__m_Stem(word)
self.InvertedIndex[word].append(idx)
idx = idx+1
def m_Search_Query( self, search_query, length ):
"""
Function to search for query words in the InvertedIndex
Input: List of query words, and the number of words in the text
Return: Integer List of length same as the number of words. Each index indicates
if the word is present in the query or not. So if List[i]==0, the word is not present
and if List[i]==2, then the 2nd word in the query is present at location i in the input text.
"""
words_present = []
idx = 1
for x in range(length):
words_present.append(0)
for word in search_query:
word = self.__m_Stem(word)
if word in self.InvertedIndex:
for word_index in self.InvertedIndex[word]:
words_present[word_index] = idx
idx = idx + 1
return words_present
def m_Find_Snippet( self, words_present, num_words, MaxWindow ):
"""
Function to find a snippet of input text with has the most number of query
words present.
Input: Integer List, length, and number of words to be present in the snippet
Return: begin, end position of the window and the count of query words present
in the snippet
"""
begin = 0
count = 0
end = 0
max_count = -1
Snippet_End = 0
Snippet_Begin = 0
num_words = len(words_present)
try:
while begin < num_words:
if words_present[begin]!=0:
count = 0
end = begin
end_done = min((MaxWindow + begin), num_words)
while end < end_done:
if words_present[end]!=0:
count+=1
end+=1
if end == num_words:
end-=1
if count > max_count:
max_count = count
Snippet_Begin = begin
Snippet_End = end
begin+=1
while Snippet_End > 0:
if words_present[Snippet_End]!=0:
break
Snippet_End-=1
except IndexError:
print "Tying to access out of bound index in method m_Find_Snippet"
return Snippet_Begin, Snippet_End, max_count
def m_Sentence_End( self, word ):
for suffix in ['.', '!', '?']:
if word.endswith(suffix):
return 1
return 0
def m_Print_Snippet( self, Snippet_Begin, Snippet_End, raw_data, words_present ):
"""
Function to generate the output text.
Input: begin and end position of snippet
Returns: Beautifies the snippet and returns the new start and end position of the snippet
"""
start = Snippet_Begin
new_start = Snippet_Begin
end = Snippet_End
num_sentence = 0
flag = 0
num_words = len(raw_data)
try:
start_done = min( 20, Snippet_Begin )
while (Snippet_Begin - start) <= start_done:
if self.m_Sentence_End( raw_data[start] ):
num_sentence += 1
new_start = start+1
if num_sentence == 2:
flag = 1
break
start -= 1
if flag == 1:
Snippet_Begin = start + 1
elif flag == 0:
if start_done == Snippet_Begin:
Snippet_Begin = start + 1
else:
Snippet_Begin = new_start
num_sentence = 0
new_end = Snippet_End
flag = 0
end_done = min( 20, num_words - Snippet_End )
while (end - Snippet_End) < end_done:
if self.m_Sentence_End( raw_data[end] ):
num_sentence+=1
new_end = end
if num_sentence == 2:
flag = 1
break
end += 1
if flag == 1:
Snippet_End = end
elif flag == 0:
if end_done == (num_words - Snippet_End):
Snippet_End = num_words - 1
else:
Snippet_End = new_end
except IndexError:
print "Tying to access out of bound index in method m_Print_Snippet"
output_text = []
query_start = 0
try:
for x in range( Snippet_Begin, Snippet_End+1 ):
if words_present[x]!=0:
if query_start == 0:
output_text.append('[[HIGHLIGHT]]'+raw_data[x])
query_start = 1
else:
output_text.append(raw_data[x])
else:
if query_start == 1:
w = output_text.pop()
output_text.append(w+'[[ENDHIGHLIGHT]]')
output_text.append(raw_data[x])
query_start = 0
else:
output_text.append(raw_data[x])
if words_present[x]!=0:
w = output_text.pop()
output_text.append(w+'[[ENDHIGHLIGHT]]')
except IndexError:
print "Trying to access out of bound index in method m_Print_Snippet"
return ' '.join(output_text)
def m_Highlight_doc( doc, query ):
"""
Args:
doc-string that is a document to be c_Highlighted
query-string that contains the search query
Return:
Text Snippet
"""
WINDOW_LENGTH = 35
text = doc.split()
query = query.split()
num_words = len(text)
Search = c_Highlight()
Search.m_Create_InvertedIndex(text)
words_present = Search.m_Search_Query(query, num_words)
begin, end, count = Search.m_Find_Snippet( words_present, num_words, WINDOW_LENGTH )
if count <= 0:
return "Query Not Found"
else:
return Search.m_Print_Snippet( begin, end, text, words_present )
</code></pre>
|
[] |
[
{
"body": "<pre><code># -*- coding: cp1252 -*-\nfrom collections import defaultdict\n\nclass c_Highlight():\n</code></pre>\n\n<p>Prefixed like c_ and m_ are frowned upon as useless.</p>\n\n<pre><code>\"\"\"Highlight Class to find and print relevant snippet of a text\"\"\"\n\nGrammar_Suffix = ['ing' ,'ly', 'ed', 'ious', 'ies', 'ive', 'es', 's', 'ment']\nPunctuation = [',', '!', '.', '?', '\"', '\\n']\n</code></pre>\n\n<p>The official python style guide recommends ALL CAPS for constants like this</p>\n\n<pre><code>def __init__(self):\n self.InvertedIndex = defaultdict( list )\n</code></pre>\n\n<p>The official python style guide recommends all_lower_case_with_underscores for variable names</p>\n\n<pre><code>def m_Read_File( self, f_name ):\n \"\"\"\n Function to Read a file, if the text is to be read from file\n Args: FileName\n Returns: List of words\n \"\"\"\n\n list_words = []\n try:\n f = open(f_name)\n for line in f:\n line = line.strip()\n list_words.extend( line.split())\n f.close()\n</code></pre>\n\n<p>This can be better if you use with</p>\n\n<pre><code>with open(f_name) as f:\n for line in f:\n line = line.strip()\n list_words.extend(line.split())\n</code></pre>\n\n<p>This will close the file even an exception is thrown.</p>\n\n<pre><code> except IOError as (errno, strerror):\n print \"File I/O Error({0}): {1}\".format(errno, strerror)\n exit(0)\n</code></pre>\n\n<p>exit(0) means the program succeeded in this case it didn't.</p>\n\n<pre><code> return list_words\n</code></pre>\n\n<p>Since this function doesn't manipulate any object attributes, it might be better as a separate utility function.</p>\n\n<pre><code>def __m_Stem( self, word ):\n \"\"\"\n Function to remove Suffix from the end of a word.\n Input: Word\n Returns: Cropped Word\n \"\"\"\n word = word.lower()\n for suffix in c_Highlight.Grammar_Suffix: \n if word.endswith(suffix):\n word = word[:-len(suffix)]\n break\n</code></pre>\n\n<p>I recommend use return word[:-len(suffix)] instead.</p>\n\n<pre><code> for punctuation in c_Highlight.Punctuation:\n while word.endswith(punctuation):\n word = word[:-len(punctuation)]\n</code></pre>\n\n<p>You don't break here like you did before</p>\n\n<pre><code> return word #can be empty list\n</code></pre>\n\n<p>Since your words appear to be strings, this comment is just wrong.</p>\n\n<pre><code>def m_Create_InvertedIndex( self, words ):\n \"\"\"\n Function to parse the input words and store them in a InvertedIndex\n The Key is the word itself and Value is the position of the word in the text\n Input: List of Words\n Return: None\n \"\"\"\n idx = 0\n for word in words:\n word = self.__m_Stem(word)\n self.InvertedIndex[word].append(idx)\n idx = idx+1\n</code></pre>\n\n<p>Use <code>enumerate</code></p>\n\n<pre><code>for idx, word in enumerate(words):\n word = self.__m_Stem(word)\n self.InvertedIndex[word].append(index)\n</code></pre>\n\n<p>See? much cleaner.</p>\n\n<pre><code>def m_Search_Query( self, search_query, length ):\n \"\"\"\n Function to search for query words in the InvertedIndex\n Input: List of query words, and the number of words in the text\n Return: Integer List of length same as the number of words. Each index indicates\n if the word is present in the query or not. So if List[i]==0, the word is not present\n and if List[i]==2, then the 2nd word in the query is present at location i in the input text. \n \"\"\"\n</code></pre>\n\n<p>Requiring the user pass in the length of the input text seems strange. The class itself knows the length of the input text and the user probably doesn't.</p>\n\n<pre><code> words_present = []\n idx = 1\n for x in range(length):\n words_present.append(0)\n</code></pre>\n\n<p>Use: <code>word_present = [0] * length</code> to create words_present, it'll be faster and clearer.</p>\n\n<pre><code> for word in search_query:\n word = self.__m_Stem(word)\n if word in self.InvertedIndex:\n for word_index in self.InvertedIndex[word]:\n words_present[word_index] = idx\n idx = idx + 1\n</code></pre>\n\n<p>You only increment <code>idx</code> when a match is found. This seems strange as I'd expect the idx to correspond the indexes in search_query. Also returning a list like this seems strange as its pretty much as hard to find values in this list as it is to find the words in the first place.</p>\n\n<pre><code> return words_present\n\n\ndef m_Find_Snippet( self, words_present, num_words, MaxWindow ):\n \"\"\"\n Function to find a snippet of input text with has the most number of query\n words present.\n Input: Integer List, length, and number of words to be present in the snippet\n Return: begin, end position of the window and the count of query words present\n in the snippet\n \"\"\"\n begin = 0\n count = 0\n end = 0\n max_count = -1\n Snippet_End = 0\n Snippet_Begin = 0\n</code></pre>\n\n<p>Python style guide recommaeds this_style for local variables.</p>\n\n<pre><code> num_words = len(words_present)\n try:\n while begin < num_words:\n if words_present[begin]!=0:\n count = 0\n end = begin\n end_done = min((MaxWindow + begin), num_words)\n while end < end_done:\n if words_present[end]!=0:\n count+=1\n end+=1\n</code></pre>\n\n<p>You are really counting from <code>begin</code> to <code>end_done</code> use a for loop.</p>\n\n<pre><code> if end == num_words:\n end-=1\n</code></pre>\n\n<p>You should be able to get rid of this ugliness when you use a for loop above</p>\n\n<pre><code> if count > max_count:\n max_count = count\n Snippet_Begin = begin\n Snippet_End = end\n</code></pre>\n\n<p>I suggest restructuring this code to use a generator. The generator would generate the snippets begin/ends and the calling code could use max to pick the best one.</p>\n\n<pre><code> begin+=1\n</code></pre>\n\n<p>Use a for loop for begin. If you find yourself wanting to use a while loop, slap yourself and use a for loop.</p>\n\n<pre><code> while Snippet_End > 0:\n if words_present[Snippet_End]!=0:\n break\n Snippet_End-=1 \n</code></pre>\n\n<p>Again, use a for loop. Whenever you are counting, you should use a for loop. Also, do this when you first construct the snippet, not now.</p>\n\n<pre><code> except IndexError:\n print \"Tying to access out of bound index in method m_Find_Snippet\"\n</code></pre>\n\n<p>Why are catching an index error? An IndexError is usually indicative of a bug in your code. All you accomplish by putting this here is making your code harder to debug by not showing the stack trace and by continuing on so you don't notice the bug.</p>\n\n<pre><code> return Snippet_Begin, Snippet_End, max_count\n\n\ndef m_Sentence_End( self, word ):\n for suffix in ['.', '!', '?']:\n if word.endswith(suffix):\n return 1\n return 0\n</code></pre>\n\n<p>Use <code>True</code> and <code>False</code> not 1 and 0.</p>\n\n<pre><code>def m_Print_Snippet( self, Snippet_Begin, Snippet_End, raw_data, words_present ):\n \"\"\"\n Function to generate the output text. \n Input: begin and end position of snippet\n Returns: Beautifies the snippet and returns the new start and end position of the snippet \n \"\"\"\n</code></pre>\n\n<p>You explain Snippet_Begin and Snippet end which were obvious. But you don't bother to explain what raw_data means.</p>\n\n<pre><code> start = Snippet_Begin\n new_start = Snippet_Begin\n end = Snippet_End\n num_sentence = 0\n flag = 0\n num_words = len(raw_data)\n try:\n start_done = min( 20, Snippet_Begin )\n while (Snippet_Begin - start) <= start_done:\n if self.m_Sentence_End( raw_data[start] ):\n num_sentence += 1\n new_start = start+1\n if num_sentence == 2:\n flag = 1\n break\n start -= 1\n</code></pre>\n\n<p>If you must count, you must use a for loop! Also don't use 1 for <code>True</code>. I'm also very suspicous of boolean flags. I think they are delayed gotos. </p>\n\n<pre><code> if flag == 1:\n</code></pre>\n\n<p>Use <code>if flag:</code></p>\n\n<pre><code> Snippet_Begin = start + 1\n elif flag == 0:\n</code></pre>\n\n<p>If the flag can only <code>True</code> or <code>False</code> just use <code>else</code></p>\n\n<pre><code> if start_done == Snippet_Begin:\n Snippet_Begin = start + 1\n else:\n Snippet_Begin = new_start\n\n num_sentence = 0\n new_end = Snippet_End\n flag = 0\n end_done = min( 20, num_words - Snippet_End )\n while (end - Snippet_End) < end_done:\n if self.m_Sentence_End( raw_data[end] ):\n num_sentence+=1\n new_end = end\n if num_sentence == 2:\n flag = 1\n break\n end += 1\n\n if flag == 1:\n Snippet_End = end\n elif flag == 0:\n if end_done == (num_words - Snippet_End):\n Snippet_End = num_words - 1\n else:\n Snippet_End = new_end\n\n\n except IndexError:\n print \"Tying to access out of bound index in method m_Print_Snippet\"\n</code></pre>\n\n<p>Again, don't do this. Don't do this. DON'T DO THIS!</p>\n\n<pre><code> output_text = []\n query_start = 0\n\n try:\n for x in range( Snippet_Begin, Snippet_End+1 ):\n if words_present[x]!=0:\n if query_start == 0:\n output_text.append('[[HIGHLIGHT]]'+raw_data[x])\n</code></pre>\n\n<p>Its probably faster to use StringIO rather then appending into a list</p>\n\n<pre><code> query_start = 1\n else:\n output_text.append(raw_data[x])\n else:\n if query_start == 1:\n w = output_text.pop()\n output_text.append(w+'[[ENDHIGHLIGHT]]')\n output_text.append(raw_data[x])\n query_start = 0\n else:\n output_text.append(raw_data[x])\n\n if words_present[x]!=0:\n w = output_text.pop()\n output_text.append(w+'[[ENDHIGHLIGHT]]')\n\n except IndexError:\n print \"Trying to access out of bound index in method m_Print_Snippet\"\n</code></pre>\n\n<p>...</p>\n\n<pre><code> return ' '.join(output_text)\n\n\ndef m_Highlight_doc( doc, query ):\n\"\"\"\nArgs:\n doc-string that is a document to be c_Highlighted\n query-string that contains the search query\n\nReturn:\n Text Snippet\n\"\"\"\n\nWINDOW_LENGTH = 35\ntext = doc.split()\nquery = query.split()\nnum_words = len(text)\nSearch = c_Highlight()\nSearch.m_Create_InvertedIndex(text)\nwords_present = Search.m_Search_Query(query, num_words)\nbegin, end, count = Search.m_Find_Snippet( words_present, num_words, WINDOW_LENGTH )\nif count <= 0:\n return \"Query Not Found\"\nelse:\n return Search.m_Print_Snippet( begin, end, text, words_present )\n</code></pre>\n\n<p>m_Print_Snippet is a fairly complicated function. It can be simplified. Here my simplified version. (Its not tested probably broken, but may give you clues as to how you can simplify your code)</p>\n\n<pre><code>def rewind_to_sentance_start(self, words, current_start):\n minimum_start = max(0, current_start - 20)\n num_sentence = 0\n new_start = minimum_start\n for possible_start in range(current_start, minimum_start, -1):\n word = words[possible_start]\n if self.m_Sentence_End(word):\n num_sentence += 1\n current_start = possible_start\n\n if num_sentence == 2:\n return possible_start + 1\n return new_start\n\ndef forward_to_sentance_end(self, words, current_end):\n maximum_end = min(len(words)-1, current_end + 20)\n num_sentence = 0\n new_end = maximum_end\n for possible_end in range(current_end, minimum_end, 1):\n word = words[possible_end]\n if self.m_Sentence_End(word):\n num_sentence += 1\n current_end = possible_end\n\n if num_sentence == 2:\n return possible_end + 1\n return new_end\n\n\ndef m_Print_Snippet( self, Snippet_Begin, Snippet_End, raw_data, words_present ):\n \"\"\"\n Function to generate the output text. \n Input: begin and end position of snippet\n Returns: Beautifies the snippet and returns the new start and end position of the snippet \n \"\"\"\n\n Snippet_Begin = rewind_to_sentance_start(raw_data, Snippet_Begin)\n Snippet_End = forward_to_sentance_end(raw_data, Snippet_End)\n\n\n output = StringIO.StringIO()\n query_start = 0\n\n snippet_words = raw_data[Snippet_Begin:Snippet_End]\n words_present = map(bool, words_present[Snippet_Begin:Snippet_End])\n # map(bool makes sure that they are really bools in there\n for highlighted, data in itertools.groupby( zip(words_present, snippet_words), operator.itemgetter(0) ):\n if highlighted:\n output.write('[[HIGHLIGHT]]')\n output.write(' '.join(word for present, word in data))\n if highlighted:\n output.write('[[ENDHIGHLIGHT]]')\n\n return output.getvalue()\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li>Any portion of the logic of a function thats at all complex should be broken out into its own function. </li>\n<li>Python itertools has many useful tools for moving the logic out of your function into it making your code clearer</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T01:29:51.690",
"Id": "2670",
"ParentId": "2668",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T00:18:25.350",
"Id": "2668",
"Score": "3",
"Tags": [
"python",
"search"
],
"Title": "Review Request: Python code that searches query words in a given text"
}
|
2668
|
<p>I'm looking for (and be as brutal as you like) ways to improve the code or the algorithm (I'm aware there should be comments) - I'm a recreational programmer and would like to be improving my skills. My next step is to get the <code>targetNumber</code> value from a nearby file without losing the current count.</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Count to a particular target</title>
</head>
<body>
<h1 id="myDiv">Starting</h1>
<script type="text/javascript">
currentValue = 100;
targetValue = 1500;
function count() {
if (currentValue > targetValue) {
currentValue -= 1
} else if (currentValue < targetValue) {
currentValue += 1
}
document.getElementById('myDiv').innerHTML = 'Total wordcount:'+ currentValue.toString();
changeTime = 20;
if (Math.abs(currentValue - targetValue) < 980) {
changeTime = 1000 - Math.abs(currentValue - targetValue);
}
setTimeout(count,changeTime/2);
}
count()
</script>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T00:02:09.870",
"Id": "4176",
"Score": "0",
"body": "Whoops - did not know there was such a thing *blush* - what's the protocal here, do I delete and repost or will it just get transfered by a passing admin?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T00:04:00.163",
"Id": "4177",
"Score": "0",
"body": "@Joe Reddington I would just delete and repost over there. We don't have the ability to vote for this to be migrated to codereview at the moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-29T14:08:14.653",
"Id": "4803",
"Score": "0",
"body": "If you're serious about learning better Javascript, here's a great place to start looking: http://javascript.crockford.com/"
}
] |
[
{
"body": "<pre><code>function count(from, to, targetElem) {\n targetElem.innerHTML = 'Total wordcount: ' + from;\n\n if (from == to) return;\n\n from < to ? from++ : from--; \n\n var changeTime = Math.max(20, 1000 - Math.abs(from - to)) / 2;\n\n setTimeout(function() {count(from, to, target);}, changeTime);\n}\n\ncount(50, 0, document.getElementById(\"t\"));\n</code></pre>\n\n<p>A few notes:</p>\n\n<ul>\n<li>avoid global variables to conserve state - use function arguments instead</li>\n<li><em>always</em> use <code>var</code> to declare variables. Otherwise they are in the global scope and you don't want this</li>\n<li>added error checking (i.e. whether values are numeric and target is valid) might not be a bad idea, I left it out for clarity here</li>\n<li><code>return</code> early on known conditions, this reduces complexity in the function body </li>\n<li>the ternary operator <code>condition ? ifTrue : ifFalse</code> can be used in other ways than assigning a value</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T18:31:13.513",
"Id": "4191",
"Score": "1",
"body": "Hmm, I'd consider `from < to ? from++ : from--;` bad style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T07:41:28.323",
"Id": "4201",
"Score": "0",
"body": "@RoToTa: Yes, you could say that. It's not really clean. Then again, it's crystal-clear what it does. An `if (from < to) from++ else from--;` would also be posible - I just wanted to stay on one line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T14:00:33.443",
"Id": "4218",
"Score": "0",
"body": "How about `from += (from < to) ? +1 : -1;` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T14:04:23.240",
"Id": "4219",
"Score": "0",
"body": "@RoToRa: If you think that's clearer. ;-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T10:17:28.157",
"Id": "2680",
"ParentId": "2669",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "2680",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-27T23:57:06.567",
"Id": "2669",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Count to target with JavaScript"
}
|
2669
|
<p>I am trying to design a program that will read a XML file and based on the tag name will perform certain requirements checks. I feel that there is probably a better way of doing this and any comments or suggestions are welcomed.</p>
<p>Thank you.</p>
<pre><code>public enum AccountCheckType
{
UserIsMemberOfGroup,
DomainUserExists,
DomainGroupExists
}
public class AccountManager
{
public bool DomainGroupExists(string groupName)
{
//Todo: Implement this
return false;
}
public bool DomainUserExists(string userName)
{
//Todo: Implement this
return false;
}
public bool UserIsMemberOfGroup(string userName,string groupName)
{
//Todo: Implement this
return false;
}
}
public class AccountRequirement:Requirement
{
#region Declarations
private readonly AccountManager manager = new AccountManager();
private readonly AccountCheckType checkType;
private string accountName;
private string groupName;
#endregion
#region Constructor/Deconstructor
/// <summary>
/// Initializes a new instance of the <see cref="AccountRequirement"/> class.
/// </summary>
public AccountRequirement(string accountName,AccountCheckType checkType)
{
if(string.IsNullOrEmpty(accountName))
{
throw new ArgumentException("Account name cannot be null or empty.");
}
if(checkType==AccountCheckType.UserIsMemberOfGroup)
{
throw new ArgumentException("Checktype cannot be equal to UserIsMemberOfGroup");
}
this.accountName = accountName;
this.checkType = checkType;
}
/// <summary>
/// Initializes a new instance of the <see cref="AccountRequirement"/> class.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="groupName">Name of the group.</param>
public AccountRequirement(string userName,string groupName)
{
if(string.IsNullOrEmpty(userName))
{
throw new ArgumentException("Username cannot be null or empty.");
}
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentException("Groupname cannot be null or empty.");
}
this.checkType = AccountCheckType.UserIsMemberOfGroup;
}
#endregion
public override RequirementStatus PerformCheck()
{
switch (checkType)
{
case AccountCheckType.DomainGroupExists:
CurrentStatus = manager.DomainGroupExists(groupName) ? OnPass : OnFail;
return CurrentStatus;
case AccountCheckType.DomainUserExists:
CurrentStatus = manager.DomainUserExists(accountName) ? OnPass : OnFail;
return CurrentStatus;
case AccountCheckType.UserIsMemberOfGroup:
CurrentStatus = manager.UserIsMemberOfGroup(accountName, groupName) ? OnPass : OnFail;
return CurrentStatus;
default:
throw new Exception("Unknown checkType in account requirement");
}
}
}
public enum RegistryCheckType
{
RegistryKeyExists,
RegistryValueExists
}
public class RegistryRequirement:Requirement
{
#region Declarations
private RegistryManager manager = new RegistryManager();
private RegistryCheckType checkType;
private string key;
private string subKey;
private string value;
#endregion
#region Constructor/Deconstructor
/// <summary>
/// Initializes a new instance of the <see cref="RegistryRequirement"/> class.
/// </summary>
public RegistryRequirement(string key,string subKey)
{
if(string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key cannot be null or empty.");
}
if (string.IsNullOrEmpty(subKey))
{
throw new ArgumentException("Subkey cannot be null or empty.");
}
this.key = key;
this.subKey = subKey;
this.checkType = RegistryCheckType.RegistryKeyExists;
}
public RegistryRequirement(string key, string subKey,string value)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key cannot be null or empty.");
}
if (string.IsNullOrEmpty(subKey))
{
throw new ArgumentException("Subkey cannot be null or empty.");
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("Value cannot be null or empty.");
}
this.key = key;
this.subKey = subKey;
this.value = value;
this.checkType = RegistryCheckType.RegistryValueExists;
}
#endregion
public override RequirementStatus PerformCheck()
{
switch (checkType)
{
case RegistryCheckType.RegistryKeyExists:
CurrentStatus = manager.RegistryKeyExists(key, subKey) ? OnPass : OnFail;
return CurrentStatus;
case RegistryCheckType.RegistryValueExists:
CurrentStatus = manager.RegistryValueExists(key, subKey, value) ? OnPass : OnFail;
return CurrentStatus;
default:
throw new Exception("Unknown checkType in registry requirement");
}
}
}
public abstract class Requirement
{
#region Constructor/Deconstructor
/// <summary>
/// Initializes a new instance of the <see cref="Requirement"/> class.
/// </summary>
public Requirement()
{
}
#endregion
#region Properties
public RequirementStatus OnPass { get; set; }
public RequirementStatus OnFail { get; set; }
public RequirementStatus CurrentStatus { get; protected set; }
#endregion
public abstract RequirementStatus PerformCheck();
}
public class RegistryManager
{
#region Declarations
#endregion
#region Constructor/Deconstructor
/// <summary>
/// Initializes a new instance of the <see cref="RegistryManager"/> class.
/// </summary>
public RegistryManager()
{
}
#endregion
#region Properties
#endregion
public bool RegistryKeyExists(string key,string subKey)
{
//Todo: Implement this
return true;
}
public bool RegistryValueExists(string key,string subKey,string value)
{
//Todo: Implement this
return true;
}
}
public class RequirementFileReader
{
#region Declarations
private XmlDocument xmlDocument=new XmlDocument();
private string filePath;
#endregion
#region Constructor/Deconstructor
/// <summary>
/// Initializes a new instance of the <see cref="RequirementFileReader"/> class.
/// </summary>
public RequirementFileReader(string filePath)
{
if(string.IsNullOrEmpty(filePath))
{
throw new ArgumentException("File path cannot be null or empty.");
}
this.filePath = filePath;
}
#endregion
#region Properties
#endregion
public IEnumerable<Requirement> GetRequirements()
{
var requirements=new List<Requirement>();
xmlDocument.Load(filePath);
var rootNode = xmlDocument.DocumentElement;
if(rootNode==null)
{
throw new Exception("Not a valid xml file.");
}
foreach (XmlNode node in rootNode.ChildNodes)
{
var onPass = (RequirementStatus) Enum.Parse(typeof (RequirementStatus), node.Attributes["onpass"].Value);
var onFail = (RequirementStatus) Enum.Parse(typeof (RequirementStatus), node.Attributes["onfail"].Value);
Requirement req = null;
switch (node.Name)
{
case "UserExists":
var user=node.Attributes["username"].Value;
req = new AccountRequirement(user, AccountCheckType.DomainUserExists)
{OnPass = onPass, OnFail = onFail};
break;
case "GroupExists":
var group = node.Attributes["groupname"].Value;
req = new AccountRequirement(group, AccountCheckType.DomainGroupExists) { OnPass = onPass, OnFail = onFail };
break;
case "RegKeyExists":
var key=node.Attributes["key"].Value;
var subkey=node.Attributes["subkey"].Value;
req = new RegistryRequirement(key, subkey);
break;
case "RegValueExists":
var key1 = node.Attributes["key"].Value;
var subkey1=node.Attributes["subkey"].Value;
var value1=node.Attributes["value"].Value;
req = new RegistryRequirement(key1, subkey1, value1);
break;
default:
throw new Exception("Invalid xml tag found.");
}
requirements.Add(req);
}
return requirements;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T20:21:58.390",
"Id": "4192",
"Score": "0",
"body": "which version of C# do you use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T03:56:47.577",
"Id": "4197",
"Score": "0",
"body": "I use .NET 3.5 SP1"
}
] |
[
{
"body": "<p>You program seem me a good design, it would be great and also increase the program readability, if you change the function name which perform checks.</p>\n\n<p>They should start with <strong>Is</strong> </p>\n\n<p><em><strong>for example</em></strong> ---> your function name <code>DomainGroupExists</code> could be change to IsDomainGroupExists ... this could be applied to all your checks functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T20:22:25.930",
"Id": "4193",
"Score": "4",
"body": "`IsDomainGroupExists` doesn't sound like correct English"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T06:08:14.617",
"Id": "4200",
"Score": "0",
"body": "@Snowbear JIM-compiler :Agree with your BUT, This is the common in object oriented programming for starting the name of a function with \"Is\" if they do validation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T20:37:34.417",
"Id": "4208",
"Score": "0",
"body": "Perhaps Does would be the best word for this situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T10:01:49.810",
"Id": "4236",
"Score": "0",
"body": "`IsDomainGroup` would read better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T12:11:33.987",
"Id": "4239",
"Score": "0",
"body": "`HasDomainGroup` ... anyone?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T12:12:48.313",
"Id": "4240",
"Score": "0",
"body": "@Steven Jeuris : would work .."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T14:30:25.237",
"Id": "4246",
"Score": "1",
"body": "I see no problem with `DomainGroupExists`, where `IsDomainGroup` would be misleading. You're not checking to see if it *is* a domain group, you're checking to see if it *exists*, so the name describes exactly what it's doing. I would say the convention of describing what you're doing outweighs the \"convention\" of starting a validation function with \"Is\"."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T09:13:15.990",
"Id": "2676",
"ParentId": "2675",
"Score": "0"
}
},
{
"body": "<p>On thing that worries me is the number of <code>switch</code> statements you have in the code. Some OO <a href=\"https://stackoverflow.com/questions/4417070/switch-statements-are-bad\">practitioners see it as a code smell</a>.</p>\n\n<p>One possibility is to fill a dictionary:</p>\n\n<pre><code>public delegate Requirement AllDelegates(XmlNode node);\nDictionary<string,delegate> typeDictionary;\n\ntypeDictionary.Add(\"UserExists\", RequirementDelegates.UserDelegate);\ntypeDictionary.Add(\"GroupExists\", RequirementDelegates.GroupDelegate);\ntypeDictionary.Add(\"RegKeyExists\", RequirementDelegates.RegKeyDelegate);\ntypeDictionary.Add(\"RegValueExists\", RequirementDelegates.RegValueDelegate);\n</code></pre>\n\n<p>where, for example, <code>UserDelegate</code> is a static member of the <code>RequirementDelegates</code> class:</p>\n\n<pre><code>class RequirementDelegates\n{\n public static Requirement UserDelegate(XmlNode node, \n RequirementStatus onPass, \n RequirementStatus onFail )\n {\n var user = node.Attributes[\"username\"].Value;\n var req = new AccountRequirement(user, AccountCheckType.DomainUserExists)\n {OnPass = onPass, OnFail = onFail};\n return req;\n }\n}\n</code></pre>\n\n<p>Then your big switch statement at the end just becomes:</p>\n\n<pre><code>AllDelegates theDelegate = typeDictionary[node.Name];\nvar req = theDelegate(node, onPass, onFail);\n</code></pre>\n\n<p>The delegates are still in one place, but the logic is clearer in the <code>GetRequirements</code> method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T21:14:10.813",
"Id": "2686",
"ParentId": "2675",
"Score": "4"
}
},
{
"body": "<p>Whilst the code you have posted could be refactored and improved, I personally think you are trying to solve the problem in the wrong way.</p>\n\n<p>If all you want is to pull certain bits of information out of certain elements, then I would definitely use XPath to achieve this. You could easily pull out the data from the elements you need to initialize your other classes, without all the cruft of the <code>foreach</code> and <code>switch</code> in the <code>GetRequirements</code> method.</p>\n\n<p>Alternatively, you could generate an XSD (if there isn't already one) for the XML you are consuming using <a href=\"https://stackoverflow.com/questions/87621/how-do-i-map-xml-to-c-objects\">XSD.exe</a>, and then generate C# classes from the XSD.You'd probably want to tweak the XSD so that the various elements require they contain text or attributes. Then you could use the XSD to quickly validate the XML document and use the C# classes to serialise the XML into objects which you could then use to do further validation checks and initialise your other objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T13:28:34.930",
"Id": "4243",
"Score": "0",
"body": "Hello Sgrassie,\nI thought about using XML serialization for this as I am using it in other areas of my project. To the best of my knowledge, XML serialization will group the tags by name and not necessarily by the order that they appear in the file. I need the checks to be performed in the order that they appear in the XML file. I also looked over some XPath tutorials and did not see any distinct advantage of using XPath over the foreach loop as I would still need to get the node name and attributes. Perhaps you could elaborate more on what you were thinking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T14:27:21.923",
"Id": "4245",
"Score": "0",
"body": "Without seeing an example of the xml it's a little difficult to offer further advice. Are they always the same checks? Are they always in the same order? If the order of the elements is changeable then I would expect some piece of data which tells me what the order is."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T10:26:37.627",
"Id": "2731",
"ParentId": "2675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2686",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T07:49:39.877",
"Id": "2675",
"Score": "5",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Improving the design of this program."
}
|
2675
|
<p>I know it's a good idea to put all data-related logic in your models in CakePHP, but what would you say about keeping every Model::find() and its particular params in the model? Is this good practice, or just taking things too far?</p>
<p><strong>For example, is this:</strong></p>
<p>PostsController:</p>
<pre><code>function index() {
$posts = $this->Post->getLatest();
$this->set(compact('posts'));
}
</code></pre>
<p>Post model:</p>
<pre><code>function getLatest() {
$params = array(
'conditions' => array('published' => 1),
'limit' => 5,
'order' => 'publish_date DESC'
);
return $this->find('all', $params);
}
</code></pre>
<p><strong>Better than this:</strong></p>
<p>PostsController:</p>
<pre><code>function index() {
$params = array(
'conditions' => array('published' => 1),
'limit' => 5,
'order' => 'publish_date DESC'
);
$posts = $this->Post->find('all', $params);
$this->set(compact('posts'));
}
</code></pre>
<p>Any thoughts? Which is better architecturally?</p>
|
[] |
[
{
"body": "<p>It's totally egilable to write shorthand-<code>find</code> functions. This way the controller is not depended of the model's parameters. I tend to go that far, that I don't use any fields directly in my controllers (and thus, not using <code>find</code> in controllers at all).<br>\nYou could save a variable by defining the array in your find-call aswell ;). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T19:31:55.037",
"Id": "4207",
"Score": "0",
"body": "Thanks for that. I use the first example I gave (all params in the model) because I feel it scans better and opens more opportunities for model method reuse. I just had a slight nagging doubt that I'm going overboard with it, so I appreciate the feedback. Seeing as nobody else has written otherwise, I reckon it must not be a bad idea."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T10:33:13.140",
"Id": "2690",
"ParentId": "2677",
"Score": "4"
}
},
{
"body": "<p>I know this is an old question but i thought i'd share my experience.</p>\n\n<p>I recently had an application where i was sick of defining all the Contain associations every time i wanted to get an a record. So i created an <code>Application::getApplication($id);</code> method that included all my Contains and their conditions.</p>\n\n<p>This worked great, every time i wanted an application i just called this. unfortunately when i moved to production and had to deal with a lot more data this became too slow to use in a lot of places. I had to go back and change all the calls to <code>getApplicaion()</code> to usual finds where i could tweak the Contains parameter to only get what i needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T10:53:39.540",
"Id": "9359",
"ParentId": "2677",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2690",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T09:29:07.003",
"Id": "2677",
"Score": "3",
"Tags": [
"php",
"mvc"
],
"Title": "How skinny should controllers be, how fat should models be in CakePHP?"
}
|
2677
|
<p>I wrote a little Python script to replace some files in <code>usr/bin</code> with symlinks to files in a different location.</p>
<p>I wouldn't mind anyone telling me where I could do better.</p>
<pre><code>#!/usr/bin/env python -tt
"""Xcode4 installs and expects to find a git installation at /usr/bin.
This is a pain if you want to control your own installation of git that
might be installed elsewhere. This script replaces the git files in
/usr/bin with symlinks to the preferred installation.
Update the 'src_directory' to the location of your preferred git installation.
"""
import sys
import os
#- Configuration -----------------------------------------------------------------
src_directory = '/usr/local/git/bin/' # preferred installation
#----------------------------------------------------------------------------------
dest_directory = '/usr/bin/'
files = ('git','git-cvsserver','git-receive-pack','git-shell','git-upload-archive','git-upload-pack','gitk')
def main():
if os.getuid():
print "This script needs to be run as 'sudo python update_git.py'"
sys.exit(1)
for a_file in files:
src_file = os.path.join(src_directory, a_file)
dest_file = os.path.join(dest_directory, a_file)
if os.path.exists(dest_file):
os.remove(dest_file)
os.symlink(src_file, dest_file)
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<pre><code>#!/usr/bin/env python -tt\n\n\"\"\"Xcode4 installs and expects to find a git installation at /usr/bin.\nThis is a pain if you want to control your own installation of git that\nmight be installed elsewhere. This script replaces the git files in\n/usr/bin with symlinks to the preferred installation.\n\nUpdate the 'src_directory' to the location of your preferred git installation.\n\"\"\"\nimport sys\nimport os\n\n#- Configuration -----------------------------------------------------------------\nsrc_directory = '/usr/local/git/bin/' # preferred installation\n#----------------------------------------------------------------------------------\n\ndest_directory = '/usr/bin/'\nfiles = ('git','git-cvsserver','git-receive-pack','git-shell','git-upload-archive','git-upload-pack','gitk')\n</code></pre>\n\n<p>The official python style guide recommends using ALL_CAPS to name global constants. Additionally, some of these constants might be better as command line arguments to the script. That way you don't need to modify the script to install to a different location.</p>\n\n<pre><code>def main():\n if os.getuid():\n</code></pre>\n\n<p>I suggest using <code>if os.getuid() != 0</code> because I think its better to be explicit. The code will run the same, but this way I think its clearer that you are checking for zero rather then an actual boolean value.</p>\n\n<pre><code> print \"This script needs to be run as 'sudo python update_git.py'\"\n sys.exit(1)\n\n for a_file in files:\n</code></pre>\n\n<p>a_file is kinda ugly. I'm guessing you are using it to avoid replace the builtin file. I suggest filename.</p>\n\n<pre><code> src_file = os.path.join(src_directory, a_file)\n dest_file = os.path.join(dest_directory, a_file)\n\n if os.path.exists(dest_file):\n os.remove(dest_file)\n</code></pre>\n\n<p>What if someone deletes the file between your script checking if it exists and deleting it? Also checking if the file exists duplicates effort that remove will have to do. You could rewrite the code to try remove, and then catching the doesn't exist exception. I wouldn't bother here though.</p>\n\n<pre><code> os.symlink(src_file, dest_file)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>You don't catch any exceptions. In a script this simple that might be okay. But it might be a good idea to try/catch IOError/OSError and print them out for the user hopefully with enough detail that the user can tell whats going wrong. If you don't the exception will be dumped, but the user will also see a stack trace which might be scary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T16:11:59.237",
"Id": "4187",
"Score": "0",
"body": "Wow! That's a lot of good points. Thanks very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T15:41:31.457",
"Id": "2683",
"ParentId": "2678",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "2683",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-28T09:31:08.380",
"Id": "2678",
"Score": "7",
"Tags": [
"python",
"file-system"
],
"Title": "Replacing files with symlinks to other files"
}
|
2678
|
<p>My coding skill is pretty rusty and moreover, I have never paid much attention to writing elegant code. I want to start on this. Problem is to merge 2 sorted linked list. Algorithmically this is trivial, but looks a good problem to practice coding.</p>
<pre><code>struct node
{
char *data;
struct node *nextp;
}
typedef struct node node;
typedef struct node list; //I do 2 typedefs here to signify when conceptually I
//mean a whole list and when just a single node.is this a good practice? or only
//one that confuses.
node * add(node *listp, char *data)
{
node * newp=(node *)malloc(sizeof(node));
assert(newp != NULL);
newp->data=(char *)malloc(sizeof(strlen(data));
assert(newp->data != NULL);
strcpy(newp->data,data); // allocate space in newp->data . should there be +1?
newp->next=NULL;
if(listp==NULL)
listp=nextp ;
else
listp->nextp=newp;
return newp;
}
list *mergelist(list * list1p, list *list2p)
{
// initialize mergedlistp;
node dummy;
node* mergedlistendp=&dummy;
list* leftlistp = NULL;
if (list1p == NULL) leftlistp=list2p;
if(list2p == NULL) leftlistp = list1p;
if(list1p != NULL && list2p!= NULL)
{
while(1)
{
if(strcmp(list1p -> data,list2p -> data) <=0)
{
mergedlistendp=add (mergedlistendp,list1p->data);
list1p=list1p -> next;
if(list1p == NULL)
{leftlistp=list2p; break;}
}
else
{
mergedlistendp=add (mergedlistendp,list2p->data);
list2p=list2p -> next;
if(list2p == NULL)
{leftlistp=list1p; break;}
}
}
for(leftlistp!=NULL;leftlistp = leftlistp->next)
add(mergedlistendp,leftlistp->data);
return mergedlistendp; // I have to return mergedlistp here (i.e. head of list)
//. How to store address of mergedlistendp the first time it is assigned a value?
}
</code></pre>
<p>I would like my code to be reviewed.Any feedback on naming, program flow, correctness, better code, indenting, idioms etc is appreciated. Please advise on how corner cases are handled more elegantly.</p>
|
[] |
[
{
"body": "<p><strong>You should have added error checking</strong>:</p>\n\n<pre><code> node * newp=(node *)malloc(sizeof(node));\n newp->data=(char *)malloc(sizeof(strlen(data));\n</code></pre>\n\n<p>malloc can return NULL if there wont be enough Virtual Adress Space. Would be great if function return error code.</p>\n\n<p><strong>add {} it could bite your next time</strong></p>\n\n<pre><code> if(listp==NULL) \n listp=nextp ;\n else\n listp->nextp=newp;\n //next live goes here, looks like next statment in else, but it's not.\n</code></pre>\n\n<p><strong>Use PascalCase or camelCase</strong></p>\n\n<pre><code>// initialize mergedlistp;\nnode* mergedlistendp=NULL; // mergedList is a better name\nlist* leftlistp = NULL;\n</code></pre>\n\n<p><strong>Stick to one style,</strong> once you have:</p>\n\n<pre><code>if (list1p == NULL) leftlistp=list2p;\nif(list2p == NULL) leftlistp = list1p;\n</code></pre>\n\n<p>another one</p>\n\n<pre><code> if(listp==NULL) \n listp=nextp ;\n</code></pre>\n\n<p>or </p>\n\n<pre><code> if(list2p == NULL)\n {leftlistp=list1p; break;}\n</code></pre>\n\n<p><strong>One statment per line</strong></p>\n\n<pre><code> if(list2p == NULL)\n {leftlistp=list1p; break;} // put break in the next line.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T13:32:16.987",
"Id": "2695",
"ParentId": "2693",
"Score": "7"
}
},
{
"body": "<ul>\n<li><p>use <code>const</code> when the function will not change the argument</p>\n\n<pre><code>node * add(node *listp, const char *data)\n</code></pre></li>\n<li><p>do not cast the return value of <code>malloc()</code>. Casting server no useful purpose and may hide errors (specifically failure to include <code><stdlib.h></code> and wrong assumptions made by the compiler about the return type)</p></li>\n<li><p>(subjective) add a description to assertions for more easily identify where they originate</p>\n\n<pre><code>assert(newp != NULL && \"malloc failed to create node\");\n</code></pre></li>\n<li><p>(subjective) one space indentation is too little</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T14:27:59.430",
"Id": "2697",
"ParentId": "2693",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T12:35:24.617",
"Id": "2693",
"Score": "7",
"Tags": [
"optimization",
"c",
"algorithm"
],
"Title": "Merge sort 2 sorted linked list"
}
|
2693
|
<p>Given an array which contains integers (may contain thousands of elements), you have to write a program to find the second largest element of the group.</p>
<pre><code>int secondmax(int array[],int n)
{
int max;
int secondmax;
assert(n>1);
max=array[0]>array[1] ? array[0] : array[1];
secondmax=array[0]>array[1] ? array[1] : array[0];
for(j=2;j<n;j++)
{
if(array[j]> max) { secondmax=max;max=array[j];}
else if (array[j] > secondmax) { secondmax=array[j];}
}
return secondmax;
}
</code></pre>
<ul>
<li><p>Is code correct?</p></li>
<li><p>Is usage of <code>assert</code> okay or should it be avoided?</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T14:00:10.693",
"Id": "4205",
"Score": "0",
"body": "The working code is at http://ideone.com/ko0ID"
}
] |
[
{
"body": "<p>There's no need to check if array[0] > array[1] twice.</p>\n\n<pre><code>if (array[0] > array[1]) {\n max = array[0];\n secondmax = array[1];\n} else {\n secondmax = array[0];\n max = array[1];\n}\n</code></pre>\n\n<p>But if you really want to use the ternary operator here (<code>? :</code>), at least move them to the declarations, and move the assertion above.</p>\n\n<p>It's a micro-optimization, but I would assign array[j] to a temporary variable inside the loop since it may potentially be accessed four times. Plus it is more readable</p>\n\n<pre><code>for(j=2;j<n;j++)\n{\n int candidate = array[j];\n if (candidate > max) {\n secondmax = max;\n max = candidate;\n }\n else if (candidate > secondmax) {\n secondmax = candidate;\n }\n}\n</code></pre>\n\n<p>Gotta say that I'm not a big fan of a single space for indentation or putting multiple statements on a single line. I've worked at a company where we used two before, and that was confusing. One is asking for trouble. And with 24+ inch monitors common, there's no need to be so frugal with your vertical screen real estate! :)</p>\n\n<p>The assertion seems like a good choice, though you might consider returning a signaling value instead. It really depends on what callers will expect, and make sure you document your choice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T13:00:12.813",
"Id": "4216",
"Score": "0",
"body": "One quick question: am i missing sth here? how to uniformly indent in stackoverflow editor ? tab doesnt work.. anything inbuilt so that we dont have to count 5 spaces for each line. please let me know, because I often post code and everytime people complain of indenting and formating -- Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T21:09:12.967",
"Id": "4227",
"Score": "0",
"body": "I guess after years of doing it by hand I just got used to it. There's a toolbar button above the editor that will indent everything four spaces to make it code, and you could use that on each block successively to get to the right spacing I suppose. When I need to write a larger example I will do so in an editor that does the tab-to-space thing for me and then paste it here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T19:44:58.083",
"Id": "2704",
"ParentId": "2694",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "2704",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T13:16:34.300",
"Id": "2694",
"Score": "2",
"Tags": [
"c",
"algorithm"
],
"Title": "Second largest element of a large array"
}
|
2694
|
<blockquote>
<p>Given two binary trees, you have to find whether the second is a sub tree of the first.</p>
</blockquote>
<p>First attempt (brute force):</p>
<pre><code>int issubtree(tree *tree1p, tree * tree2p)
{
if (tree2p == NULL)
return 1;
if (tree1p == NULL)
return 0;
if (tree1p->data == tree2p->data)
return (issubtree(tree1p->leftp,tree2p->leftp)
&& (issubtree(tree1p->leftp,tree2p->leftp));
else
return (issubtree(tree1p->leftp,tree2p) || (issubtree(tree1p->rightp,tree2p));
}
</code></pre>
<p>Please give feedback on correctness more efficient code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T14:56:11.593",
"Id": "4206",
"Score": "1",
"body": "I'd come up with better (subjective, I know) names for the parameters: `int issubtree(const tree *haystack, const tree *needle)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T16:57:23.567",
"Id": "29561",
"Score": "0",
"body": "Why cant we get the list of preorder and inorder of both the trees\nand compare the preorder and inorder of 2 is a subseq of preorder and inorder of 1"
}
] |
[
{
"body": "<p>This algorithm requires the values to maintain the same structure in both trees which is probably okay for this assignment (homework?).</p>\n\n<p>If these are binary search trees, there's at least one optimization you can make right off the bat: inside the <code>else</code> block you don't have to check both directions. Think about how you would find the root node of the subtree in the main tree.</p>\n\n<p>And yes, choosing meaningful variable and function names and using consistent formatting (I fixed it) goes a long way toward keeping code readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T19:24:55.880",
"Id": "2702",
"ParentId": "2696",
"Score": "0"
}
},
{
"body": "<p>Firstly, what's will all the p's? I guess they mean pointer? They are silly, get rid of them.</p>\n\n<p>Consider these trees:</p>\n\n<pre><code> [A] [A]\n / \\ / \\\n [B] [C] [D] [C]\n /\n[D]\n</code></pre>\n\n<p>Your code will claim that the second tree is a subtree of the first. The problem is that you cannot check the left/right matching using issubtree because they need to be exact matches not subtrees. You need to seperate the subtree search from the matching:</p>\n\n<pre><code>int matches(tree * tree1, tree * tree2)\n{\n if(tree1 == tree2) return 1;\n if(tree1 == NULL || tree2 == NULL) return 0;\n if(tree1->data != tree2->data) return 0;\n return matches(tree1->left, tree2->left) && matches(tree1->right, tree2->right);\n}\n\nint issubtree(tree *haystack, tree * needle)\n{\n if(tree1 == haystack) return 0;\n if( matches(haystack, needle) ) return 1;\n return issubtree(haystack->left, tree2) || issubtree(haystack->right, needle);\n}\n</code></pre>\n\n<p>For increased efficiency, we can look at the problem in another way. We can express a tree by its pre-order traversal. So for the first tree above we have:</p>\n\n<pre><code>A,B,D,(NULL),(NULL),(NULL),C,(NULL), (NULL)\n</code></pre>\n\n<p>We can reconstruct the original tree from this sequence. Additionally, a subtree will show up as a substring of this sequence. This means that we can view the subtree problem as the same as the substring search problem. That's a well studied problem and you can view various algorithms for it here: <a href=\"http://en.wikipedia.org/wiki/String_searching_algorithm\">http://en.wikipedia.org/wiki/String_searching_algorithm</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T21:12:00.850",
"Id": "59919",
"Score": "0",
"body": "When looking at the wikipedia example for pre-order https://en.wikipedia.org/wiki/Tree_traversal#Pre-order you can not match sub-tree F,A,B,D,G as substring because C and E are in between."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-03T03:24:29.340",
"Id": "59936",
"Score": "0",
"body": "@Flip, that's not a subtree. From wiki: \"A subtree of a tree T is a tree consisting of a node in T and all of its descendants in T\" C & E have to be included for it to be a subtree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-24T13:37:03.007",
"Id": "186235",
"Score": "0",
"body": "I tested mentioned code with your example, but it gives me correct answer. Am I missing something? Code: http://ideone.com/GLt7za"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-24T14:07:47.960",
"Id": "186241",
"Score": "0",
"body": "@Hengameh, you inputted the tree incorrectly, you swapped left and right in the first tree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-24T14:35:25.840",
"Id": "186250",
"Score": "0",
"body": "You are right! Embarrassing! Sorry."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T19:39:21.593",
"Id": "2703",
"ParentId": "2696",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "2703",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T14:13:04.833",
"Id": "2696",
"Score": "5",
"Tags": [
"performance",
"algorithm",
"c"
],
"Title": "Given two Binary trees, find whether the second is a sub tree of the first"
}
|
2696
|
<p>I'm starting to dive into <strong>TDD</strong> with <strong>NUnit</strong> and despite I've enjoyed checking some resources I've found here at stackoverflow, I often find myself not gaining good traction.</p>
<p>So what I'm really trying to achieve is to acquire some sort of checklist/workflow —and here's where I need you guys to help me out— or "<em>Test Plan</em>" that will give me decent Code Coverage.</p>
<p>So let's assume an ideal scenario where we could start a project from scratch with let's say a Mailer helper class that would have the following code:</p>
<p>(I've created the class just for the sake of aiding the question with a code sample so any criticism or advice is encouraged and will be very welcome)</p>
<p><strong>Mailer.cs</strong></p>
<pre><code>using System.Net.Mail;
using System;
namespace Dotnet.Samples.NUnit
{
public class Mailer
{
readonly string from;
public string From { get { return from; } }
readonly string to;
public string To { get { return to; } }
readonly string subject;
public string Subject { get { return subject; } }
readonly string cc;
public string Cc { get { return cc; } }
readonly string bcc;
public string BCc { get { return bcc; } }
readonly string body;
public string Body { get { return body; } }
readonly string smtpHost;
public string SmtpHost { get { return smtpHost; } }
readonly string attach;
public string Attach { get { return Attach; } }
public Mailer(string from = null, string to = null, string body = null, string subject = null, string cc = null, string bcc = null, string smtpHost = "localhost", string attach = null)
{
this.from = from;
this.to = to;
this.subject = subject;
this.body = body;
this.cc = cc;
this.bcc = bcc;
this.smtpHost = smtpHost;
this.attach = attach;
}
public void SendMail()
{
if (string.IsNullOrEmpty(From))
throw new ArgumentNullException("Sender e-mail address cannot be null or empty.", from);
SmtpClient smtp = new SmtpClient();
MailMessage mail = new MailMessage();
smtp.Send(mail);
}
}
}
</code></pre>
<p><strong>MailerTests.cs</strong></p>
<pre><code> using System;
using NUnit.Framework;
namespace Dotnet.Samples.NUnit
{
[TestFixture]
public class MailerTests
{
[Test]
public void SendMail_FromArgumentIsNotNull_ReturnsTrue()
{
// Arrange
string argument = null;
// Act
Mailer mailer = new Mailer(from: argument);
// Assert
Assert.IsNotNull(mailer.From, "parameter 'from' cannot be null.");
}
[Test]
public void SendMail_FromArgumentIsNotEmpty_ReturnsTrue()
{
// Arrange
string argument = String.Empty;
// Act
Mailer mailer = new Mailer(from: argument);
// Assert
Assert.IsNotEmpty(mailer.From, "parameter 'from' cannot be empty.");
}
[Test]
public void SendMail_FromArgumentIsNullOrEmpty_ThrowsException()
{
// Arrange
dynamic argument = null;
// Act
Mailer mailer = new Mailer(from: argument);
Action act = () => mailer.SendMail();
// Assert
Assert.Throws<ArgumentNullException>(new TestDelegate(act));
}
}
}
</code></pre>
<p>So after having my first 2 failing tests the next obvious step would be implementing the functionality to make them pass, but, should I <em>keep</em> the failing tests and create new ones after implementing the code that will make those pass, or should I <em>modify</em> the existing ones after making them pass? </p>
<p>Any advice about this topic will really be enormously appreciated.</p>
|
[] |
[
{
"body": "<p>sometimes you make new ones, sometimes you extend the current test you are working on. There's no real rules. You are trying to keep your tests well factored like your code. So sometimes you DELETE a test also.</p>\n\n<p>Just treat your test code like production code. Remove duplication. Keep it simple. Basically, with unit tests, you want as few tests as possible. </p>\n\n<p>that doesn't mean you don't test something, but reduce your tests down to them minimum that will validate the units function. Too often unit tests get large and messy and simple changes in the code cause lots of tests to break. So don't be afraid to refactor your tests. Also keep your tests at the right level of abstraction, meaning, don't dig into the details of your code and test the internal workings.</p>\n\n<p>Looking at your code, you have started with argument validation, this is not a good way to start. You want to start with something significant..... add validation of parameters later once you understand the nature of your objects.</p>\n\n<p>Also, dont be afraid of multiple test fixtures to do your arrange... (even though the code is kind of testing the wrong thing)</p>\n\n<pre><code>namespace Dotnet.Samples.NUnit\n{\n [TestFixture]\n public class NullFromAddressFixture\n {\n private Mailer mailer;\n\n [SetUp]\n public void Setup()\n {\n // Arrange\n dynamic argument = null\n mailer = new Mailer(from: argument);\n\n }\n\n [Test]\n public void SendMail_FromArgumentIsNotNullOrEmpty_ReturnsTrue()\n {\n Assert.IsNotNullOrEmpty(mailer.From, \"Parameter cannot be null or empty.\");\n }\n\n [Test]\n public void SendMail_FromArgumentIsNullOrEmpty_ThrowsException()\n {\n // Act\n Action act = () => mailer.SendMail();\n act.ShouldThrow<ArgumentNullException>();\n\n // Assert\n Assert.Throws<ArgumentNullException>(new TestDelegate(act));\n }\n }\n\n [TestFixture]\n public class EmptyFromAddressFixture\n {\n [Test]\n public void SendMail_FromArgumentIsOfTypeString_ReturnsTrue()\n {\n // Arrange\n dynamic argument = String.Empty;\n\n // Act\n Mailer mailer = new Mailer(from: argument);\n\n // Assert\n mailer.From.Should().Be(argument, \"Parameter should be of type string.\");\n }\n\n // INFO: At this first 'iteration' I've almost covered just the first argument of the method so logically this sample is nowhere near completed.\n // TODO: Create a test that will eventually require the implementation of a method to validate a well-formed email address.\n // TODO: Create as much tests as needed to give the remaining parameters good code coverage.\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T04:22:21.683",
"Id": "2705",
"ParentId": "2699",
"Score": "3"
}
},
{
"body": "<p>It is important to get one's mindset in a TDD mode beforehand. What I mean by this is</p>\n\n<p>1) Identify the responsibility of a class - this helps in identifying the test cases.\n2) Identify the interactions of the class with external dependencies - Unit testing shouldn't be testing the behaviour of the external dependency.</p>\n\n<p>In this case - you have written a wrapper class around SendMail whose responsibility is to \"Collect and Despatch\".</p>\n\n<p>I'd say SmtpClient is a dependency - you should be able to Mock it's behaviour in your test.</p>\n\n<p><strong>Mailer.cs</strong></p>\n\n<pre><code>using System.Net.Mail;\nusing System;\n\nnamespace Dotnet.Samples.NUnit\n{\n public class Mailer\n {\n readonly string from;\n public string From { get { return from; } }\n\n readonly string to;\n public string To { get { return to; } }\n\n readonly string subject;\n public string Subject { get { return subject; } }\n\n readonly string cc;\n public string Cc { get { return cc; } }\n\n readonly string bcc;\n public string BCc { get { return bcc; } }\n\n readonly string body;\n public string Body { get { return body; } }\n\n readonly string smtpHost;\n public string SmtpHost { get { return smtpHost; } }\n\n readonly string attachment;\n public string Attachment { get { return Attachment; } }\n\n private SmtpClient smtpClient;\n\n public Mailer(string from = null, string to = null, string body = null, string subject = null, string cc = null, string bcc = null, string smtpHost = \"localhost\", string attachment = null, SmtpClient smtpClient= new SmtpClient())\n {\n this.from = from;\n this.to = to;\n this.subject = subject;\n this.body = body;\n this.cc = cc;\n this.bcc = bcc;\n this.smtpHost = smtpHost;\n this.attachment = attachment;\n }\n\n public void SendMail()\n {\n if (string.IsNullOrEmpty(From))\n throw new ArgumentNullException(\"Sender e-mail address cannot be null or empty.\", from);\n\n MailMessage mail = new MailMessage();\n smtpClient.Send(mail);\n }\n }\n}\n</code></pre>\n\n<p><strong>Testing SendMail</strong></p>\n\n<pre><code>[Test]\npublic voud ShouldCallSendOfSmtpClientWhenSendMailIsCalled\n{\n //Stub & Setup\n var mockSmtpClient = MockRepository.GenerateMock<SmtpClient>();\n var mailer = new Mailer(smtpClient: mockSmtpClient);\n\n //Act\n var message = new MailMessage();\n mailer.SendMail(message);\n\n //Assert\n mockSmtpClient.AssertWasCalled(m=>m.Send(Arg<MailMessage>.Is.Anything));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T20:47:38.797",
"Id": "4305",
"Score": "0",
"body": "Thanks a lot for your comment! It's been definitely informative."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T05:24:49.983",
"Id": "2756",
"ParentId": "2699",
"Score": "4"
}
},
{
"body": "<p>To answer your question directly, you don't typically change a test once it passes, unless it breaks (you'll often need to modify the setup for a given class as new requirements are added, but this can be addressed by refactoring your test classes and using inheritance). The point is to have a set of tests that verify the expected outcome, so unless the expected outcome changes, you shouldn't change your tests. And your tests should start out by testing for the expected outcome. You don't normally write 1 condition, make it pass, then add more conditions to the same test; you either start out with multiple conditions you're testing for, or write additional tests.</p>\n\n<p>To use a simplified example to make sure I correctly understand what you're asking, if you were testing a function <code>Add(int arg1, int arg2)</code>, and you wrote 2 tests:</p>\n\n<pre><code>[Test]\npublic void Add_2_plus_2_is_4()\n{\n Assert.AreEqual(4, Add(2, 2));\n}\n\n[Test]\npublic void Add_Throws_Argument_Exception_For_Negative_Number()\n{\n Assert.Throws<ArgumentException>(Add(2, -1));\n}\n</code></pre>\n\n<p>Once your tests pass, you would leave them in place when you go on to write your unit tests for the <code>Subtract(int arg1, int arg2)</code> method. You wouldn't change the 2 test you just wrote to instead validate your <code>Subtract</code> method. Is that what you were asking?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T23:50:33.213",
"Id": "4322",
"Score": "0",
"body": "Thank you! Your contribution is definitely helpful, I'll start following your advice and I'd quite probably update the sample code. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T02:04:11.127",
"Id": "2774",
"ParentId": "2699",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T17:42:27.250",
"Id": "2699",
"Score": "7",
"Tags": [
"c#",
"unit-testing"
],
"Title": "TDD workflow best-practices for .NET using NUnit"
}
|
2699
|
<p>I'm new to this page I want to ask you to critique my code on jInternalFrame. Basically the problem is that there is no complete example on using this, so I wrote this "template" but I don't know if it lacks of something.</p>
<p>So here is the code(It does 'nothing' just calling, positioning and basic stuff):</p>
<p><strong>Main.java</strong></p>
<pre><code>package forms;
import java.awt.*;
import javax.swing.*;
public class Main {
static JFrame frame;
static panel pan;
static menu men;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
UIManager.LookAndFeelInfo look[];
look = UIManager.getInstalledLookAndFeels();
try {
UIManager.setLookAndFeel(look[3].getClassName());
} catch (Exception ex) {
}
frame = new JFrame();
pan = new panel();
men = new menu(pan);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(pan);
frame.setJMenuBar(men.getMenuBar());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
</code></pre>
<p><strong>mTmp.java</strong></p>
<pre><code>package forms;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
public class mTmp extends JInternalFrame {
//referencia a singleton
private static mTmp ref;
//desktop, panel, pos. relativa
JDesktopPane desktop;
JPanel panel;
Dimension idx;
//componentes swing
private JButton jButton1;
private JButton jButton2;
private JButton jButton3;
private JPanel jPanel1;
private JScrollPane jScrollPane1;
private JTextArea jTextArea1;
private JTextField jTextField1;
public mTmp() {
super("ventana", true, true, true, true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static mTmp getmTmp(JDesktopPane desktop, JPanel panel, Dimension idx) {
if (ref == null) {
ref = new mTmp();
ref.desktop = desktop;
ref.panel = panel;
ref.idx = idx;
ref.crearmTmp();
}
return ref;
}
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
@Override
public void dispose() {
ref = null;
super.dispose();
}
private void initComponents(GroupLayout layout) {
jPanel1 = new JPanel();
jTextField1 = new JTextField();
jScrollPane1 = new JScrollPane();
jTextArea1 = new JTextArea();
jButton1 = new JButton();
jButton2 = new JButton();
jButton3 = new JButton();
jPanel1.setBorder(BorderFactory.createTitledBorder(""));
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("jButton1");
GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addGap(27, 27, 27).addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(jButton1))).addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(jButton1)).addGap(27, 27, 27).addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE).addContainerGap()));
jButton2.setText("jButton2");
jButton3.setText("jButton3");
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(27, 27, 27).addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(jButton2).addComponent(jButton3)).addContainerGap(38, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(25, 25, 25).addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGroup(layout.createSequentialGroup().addGap(92, 92, 92).addComponent(jButton2).addGap(36, 36, 36).addComponent(jButton3))).addContainerGap(30, Short.MAX_VALUE)));
actions();
}
private void crearmTmp() {
GroupLayout layout = new GroupLayout(panel);
initComponents(layout);
panel.setLayout(layout);
if (panel != null) {
this.setContentPane(panel);
this.getRootPane().setOpaque(false);
}
desktop.add(this);
this.setOpaque(false);
this.setVisible(true);
this.setLocation(idx.width, idx.height);
this.setSize(500, 400);
desktop.getDesktopManager().activateFrame(this);
}
private void actions() {
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
}
}
</code></pre>
<p><strong>menu.java</strong></p>
<pre><code>package forms;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
public class menu extends JMenuBar implements ActionListener {
private JMenuBar menuBar = new JMenuBar();
private LinkedList<JMenu> list = new LinkedList<JMenu>();
private panel Panel;
private Dimension dim;
public menu(panel Panel) {
this.Panel = Panel;
list.add(newMenu("Archivo", KeyEvent.VK_A));
list.get(0).add(newMenuItem("Salir", KeyEvent.VK_N, "salir"));
list.get(0).add(newMenuItem("Formlario 1", KeyEvent.VK_E, "form1"));
list.get(0).add(newMenuItem("Formlario 2", KeyEvent.VK_J, "form2"));
list.get(0).add(newMenu("Submenu", KeyEvent.VK_O));
list.get(0).getItem(3).add(newMenuItem("Salir", KeyEvent.VK_N, "salir"));
list.add(newMenu("Editar", KeyEvent.VK_D));
for (int i = 0; i < list.size(); i++) {
menuBar.add((JMenu) list.get(i));
}
dim = new Dimension(120, 60);
}
private JMenu newMenu(String name, int key) {
JMenu menu = new JMenu(name);
menu.setMnemonic(key);
return menu;
}
private JMenuItem newMenuItem(String name, int key, String command) {
JMenuItem menuItem = new JMenuItem(name);
menuItem.setMnemonic(key);
menuItem.setAccelerator(KeyStroke.getKeyStroke(key, ActionEvent.ALT_MASK));
menuItem.setActionCommand(command);
menuItem.addActionListener(this);
return menuItem;
}
public JMenuBar getMenuBar() {
return menuBar;
}
protected void quit() {
System.exit(0);
}
public void actionPerformed(ActionEvent e) {
if ("salir".equals(e.getActionCommand())) {
quit();
} else if ("form1".equals(e.getActionCommand())) {
//Panel.newAlumno(dim);
dim.setSize(dim.width + 20, dim.height + 50);
} else if ("form2".equals(e.getActionCommand())) {
Panel.newmTmp(dim);
dim.setSize(dim.width + 20, dim.height + 20);
}
}
}
</code></pre>
<p><strong>panel.java</strong></p>
<pre><code>package forms;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JDesktopPane;
import javax.swing.JPanel;
public final class panel extends JPanel {
private final JDesktopPane desktop = new JDesktopPane();
private Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
public panel() {
super(new BorderLayout());
desktop.setBackground(Color.white);
add(desktop);
dim.setSize(0.9 * dim.width, 0.8 * dim.height);
setPreferredSize(dim);
}
public void newmTmp(Dimension dim) {
JPanel p1 = new JPanel();
p1.setOpaque(true);
mTmp.getmTmp(desktop, p1, dim);
}
}
</code></pre>
<p>Thanks in advance</p>
|
[] |
[
{
"body": "<p>Your class names don't follow the normal standard of starting with a capital letter. Also they are not very specific so it is hard to understand what their purpose might be. Your variable names suffer from similar problems of not being </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T12:53:06.590",
"Id": "2709",
"ParentId": "2700",
"Score": "5"
}
},
{
"body": "<ul>\n<li><code>UIManager.setLookAndFeel(look[3].getClassName());</code> is dangerous: As far as I know there is nowhere defined how many L&Fs have to be present in which order, so on a different VM this line could simply blow up.</li>\n<li>Please use uppercase class names</li>\n<li><p>Why do you go a detour when creating menus by using a list? You might need a few lines less using a list, but the fun starts if you want to insert menus later, and you rely on list indexes. </p>\n\n<pre><code>JMenu archivo = newMenu(\"Archivo\", KeyEvent.VK_A);\narchivo.add(newMenuItem(\"Salir\", KeyEvent.VK_N, \"salir\"));\narchivo.add(newMenuItem(\"Formlario 1\", KeyEvent.VK_E, \"form1\"));\narchivo.add(newMenuItem(\"Formlario 2\", KeyEvent.VK_J, \"form2\"));\nJMenu submenu = newMenu(\"Submenu\", KeyEvent.VK_O);\nsubmenu.add(newMenuItem(\"Salir\", KeyEvent.VK_N, \"salir\"));\narchivo.add(submenu); \n\nJMenu editar = newMenu(\"Editar\", KeyEvent.VK_D);\n\nmenuBar.add(archivo);\nmenuBar.add(editar);\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-03T19:04:47.103",
"Id": "4902",
"Score": "0",
"body": "thanks for the review. About the menus, just seem a little more organized to me to have \"levels\", but yes, It could get messy"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-29T13:38:43.283",
"Id": "3198",
"ParentId": "2700",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-29T18:10:57.603",
"Id": "2700",
"Score": "5",
"Tags": [
"java",
"swing"
],
"Title": "jInternalFrames code"
}
|
2700
|
<p>Problem:</p>
<blockquote>
<p><em>n</em> students have marks and names. Rank students based on their marks and print their names.</p>
</blockquote>
<hr>
<pre><code>#include <stdio.h>
#include <assert.h>
struct student
{
int marks;
char name[50];
};
struct listnode
{
struct student * data;
struct listnode *next;
};
addtofrontoflist(struct listnode *listhead,struct student *node)
{
//make a block of listnode.
struct listnode bucketnode;
bucketnode.data=node;
struct listnode *tmp;
tmp=listhead->next;
listhead->next=&bucketnode;
bucketnode.next=tmp;
}
bucket_sort(struct student array[],int n)
{
struct listnode *buckets[n];
int i,j;
struct listnode *temp;
for(i=0;i<n;i++)
{
buckets[i]=malloc(sizeof(struct listnode));
assert(buckets[i]!=NULL);
}
for(i=0;i<n;i++)
{
addtofrontoflist(buckets[array[i].marks],&array[i]);
}
for(i=0;i<n;i++)
{
if(buckets[i]==NULL) continue;
for(temp=buckets[i];temp!=NULL;temp++)
printf("%d %s\n",temp->data->marks,temp->data->name);
}
}
main()
{
struct student array[5]={"1,one","2,two","2,two","4,four","1,one"};
bucket_sort(array,5);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T16:42:01.010",
"Id": "4220",
"Score": "8",
"body": "Two things: (1) please indent your code properly. (2) please describe the actual problem. At the moment you’re only offering a dense wall of code and a semi-intelligible title."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T14:44:16.350",
"Id": "4312",
"Score": "1",
"body": "@Konrad, this is code review. There isn't supposed to be a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T20:27:38.827",
"Id": "4320",
"Score": "0",
"body": "@Winston It would still be nice to know what exactly the OP wants. What does the code do? Which direction should the code review take? Notice that since my comment the post has been edited and now the title and the first sentence are much more intelligible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T14:14:56.703",
"Id": "4351",
"Score": "0",
"body": "@Konrad, OK, I must have come by after the edit."
}
] |
[
{
"body": "<p>First, make sure the code compiles. You should include <code>stdlib.h</code> for <code>malloc</code>. Depending on which compiler and libraries you use, this may still work on your system but always include the proper headers for the api's you're using.</p>\n\n<p>Then your initialization of the student array in <code>main</code> is wrong. Your compiler should have given you a warning about this too. If not, pump up the warning level! You probably want this instead:</p>\n\n<pre><code>struct student array[5] = {{1, \"one\"}, {2, \"two\"}, {2, \"two\"}, {4, \"four\"}, {1, \"one\"}};\n</code></pre>\n\n<p>Also make sure you specify the return type of each function. If you don't return a value, make the return type <code>void</code>. If you don't specify the function default to return <code>int</code>, and your compiler should give you a warning that you exit without returning a value. (Pay attention to warnings!)</p>\n\n<p>Another thing with functions, try to name them properly and make sure they do what the function name says. Your function <code>bucket_sort</code> does not do what advertised. It first converts an array of student to buckets, then tries to sort it and then prints the result. A name like <code>print_students_sorted_by_mark()</code> would probably be better. And better yet, you might want to split this into three functions.</p>\n\n<p>The sorting also looks broken, but I have not looked to closely into that now.</p>\n\n<p>In general you may want to pay more attention to naming. You use both listnode and bucketnode/bucket to signify the same thing. Cleaning up naming and keeping it consistent will mean a lot to others reading your code, especially in bigger projects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-25T06:44:05.067",
"Id": "3626",
"ParentId": "2708",
"Score": "4"
}
},
{
"body": "<ul>\n<li><p>Since your functions have no explicit return types (and surely you've compiled this), you must be implementing this under an older C standard that allowed for implicit return types.</p>\n\n<p>Regardless, I would recommend adding explicit return types to your functions:</p>\n\n<ul>\n<li><p><code>main()</code> should return an <code>int</code> as it is supposed to return an integer value based on the program's execution outcome (either <code>0</code> for success or <code>1</code> for failure). However, if it will <em>always</em> execute successfully, then you can omit the <code>return 0</code> at the end.</p></li>\n<li><p>The other functions should return <code>void</code> as they're not already returning anything.</p></li>\n</ul></li>\n<li><p>You may <code>typedef</code> your <code>struct</code>s to avoid having to type <code>struct</code> elsewhere.</p></li>\n<li><p>You're inconsistently using snake_case naming and all-lowercase. The latter is not very readable as compound words should be separated. Since you're already using snake_case, just use that for all of your variable and function naming here.</p></li>\n<li><p><code>marks</code> should probably just be <code>mark</code> as it's just a single variable. But if a student is supposed to have more than one, then <code>marks</code> should be an array. Also, must this be an integer type, or can a student have a decimal value as a mark? This would of course depend on how you want to implement this grading system.</p></li>\n<li><p>The variable <code>j</code> declared in <code>bucket_sort()</code> is unused, so it should be removed. You should have your compiler warnings up high so that you'll be told when this occurs.</p></li>\n<li><p>You should add whitespace between operators for readability. Keeping lines shorter would not be of much benefit as you should try not to have so much code on one line.</p>\n\n<p>For instance, one of your <code>for</code> loops:</p>\n\n<blockquote>\n<pre><code>for(i=0;i<n;i++)\n</code></pre>\n</blockquote>\n\n<p>would look like this:</p>\n\n<pre><code>for (i = 0; i < n; i++)\n</code></pre>\n\n<p>And your array:</p>\n\n<blockquote>\n<pre><code>struct student array[5]={\"1,one\",\"2,two\",\"2,two\",\"4,four\",\"1,one\"};\n</code></pre>\n</blockquote>\n\n<p>should have its elements separated:</p>\n\n<pre><code>struct student array[5] = { \"1,one\", \"2,two\", \"2,two\", \"4,four\", \"1,one\" };\n</code></pre></li>\n<li><p>I'd recommend having a macro for the number of students:</p>\n\n<pre><code>#define NUM_STUDENTS 5\n</code></pre>\n\n<p>You can use this macro for the array size and anything else, and in case you'll ever need to change this number, this will be done in just one place.</p>\n\n<p>In addition, <code>bucket_sort()</code> will no longer need to take a size.</p>\n\n<pre><code>student array[NUM_STUDENTS] = { \"1,one\",\"2,two\",\"2,two\",\"4,four\",\"1,one\" };\nbucket_sort(array);\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:19:13.140",
"Id": "46778",
"ParentId": "2708",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T11:41:26.110",
"Id": "2708",
"Score": "8",
"Tags": [
"algorithm",
"c",
"sorting"
],
"Title": "Using bucket sort to rank students based on their marks"
}
|
2708
|
<p>I know that this is very very basic, but now I am starting from group up after getting frustrated with my coding practices and knowledge of standard idioms out there and elegant way of coding corner cases. The problem is to insert into tail of a linked list.</p>
<pre><code>void insertattail (struct node *head, int data)
{
//First construct the node in newp
struct node *newp;
struct node *p;
newp = malloc (sizeof (struct node));
newp -> data = data;
newp -> next = NULL;
// Standard name for node pointers only used for traversal? p? q? tmp?
// if more than 1 kind of nodes?
// Then what about temp pointers for swapping etc but not exactly for traversal?
if (head == NULL) // is there more elegant way of dealing with this? any idiom?
{
head = newp;
return;
}
for (p=head; p->next != NULL; p++)
;
p->next=newp;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T13:36:37.487",
"Id": "4217",
"Score": "0",
"body": "More linked list code is at https://ideone.com/UrtaO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T21:21:57.683",
"Id": "4228",
"Score": "1",
"body": "I've always like `curr` for \"current node pointer\" to match next and previous."
}
] |
[
{
"body": "<pre><code>if(head == NULL) // is there more elegant way of dealing with this? any idiom?\n{\nhead=newp;\nreturn;\n}\n</code></pre>\n\n<p><code>head</code> is a local variable in this function. Modifying it will not change the variable that was passed into the function. As a result, the new node you create isn't attached to anything that the caller can access. If you want to modify a variable being passed in you need to use a pointer. If you want to modify a pointer, you need to use a pointer to a pointer.</p>\n\n<p>Here is a version which reduces the amount of code, but for those who don't think in pointers naturally it may be hard to follow.</p>\n\n<pre><code>// I take a pointer to a pointer so that I can modify it if need be.\nvoid insertattail(struct node **head,int data)\n{\n // advance the pointer until it reaches NULL\n // because its a pointer to a pointer I can modify it\n while(*head != NULL) head = &(*head)->next;\n\n // replace that NULL with a new node\n *head = malloc(sizeof(struct node));\n // fill up the node\n (*head)->data = data;\n (*head)->next = NULL;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T15:37:42.397",
"Id": "2712",
"ParentId": "2710",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "2712",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T12:58:05.090",
"Id": "2710",
"Score": "6",
"Tags": [
"c",
"algorithm",
"linked-list"
],
"Title": "Inserting into a linked list"
}
|
2710
|
<p>A schoolmate is going through the interview process, and was given the question of detecting if a linked list data structure has an infinite loop in it. I wrote this example, and wanted to see what experience programmers thought of it.</p>
<pre><code>/*
* detecting loops in a linked list, java
*
* This linked list doesn't have a payload, but that is irrelevant to
* this problem, although might be useful for debugging.
*
*/
import java.util.*;
class Node
{
Node n = null;
Node()
{
}
Node(Node n)
{
setNext(n);
}
void setNext(Node n)
{
this.n = n;
}
boolean hasNext()
{
return n!=null;
}
Node next()
{
return n;
}
boolean isLoopy(Set<Node> visited)
{
if(visited.contains(this))
{
return true;
}else
{
if(hasNext())
{
visited.add(this);
return next().isLoopy(visited);
}else
{
return false;
}
}
}
boolean isLoopy()
{
return isLoopy(new HashSet<Node>());
}
// test harness
public static void main(String[] args)
{
Node n1 = new Node();
Node n2 = new Node(n1);
n1.setNext(n2);
System.out.println("loopy list is loopy:");
System.out.println(n1.isLoopy());
Node n4 = new Node();
Node n3 = new Node(n4);
System.out.println("non loopy list is loopy:");
System.out.println(n3.isLoopy());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T18:01:06.813",
"Id": "4222",
"Score": "2",
"body": "It is possible solve it with O(1) memory consumption."
}
] |
[
{
"body": "<pre><code> void setNext(Node n)\n {\n this.n = n;\n }\n boolean hasNext()\n {\n return n!=null;\n }\n Node next()\n {\n return n;\n }\n</code></pre>\n\n<p>I think the getters and setters are misplaced here. Such methods should be used to hide the internal details of an implementation. However, the entire Node class is the internal details of a List class. As such having getters and setters just complicates the situation.</p>\n\n<pre><code> boolean isLoopy(Set<Node> visited)\n</code></pre>\n\n<p>An option to consider is storing a visited flag on the nodes rather then as a set.</p>\n\n<pre><code> {\n if(visited.contains(this))\n {\n return true;\n }else\n {\n</code></pre>\n\n<p>That's a new way of arranging else that I haven't seen before.</p>\n\n<pre><code> if(hasNext())\n {\n visited.add(this);\n</code></pre>\n\n<p>At first glance, it seems odd that this line isn't outside of the if-block. I can see that it doesn't matter. However, at least a comment explaining why you've put it here.</p>\n\n<pre><code> return next().isLoopy(visited);\n }else\n {\n return false;\n }\n }\n }\n</code></pre>\n\n<p>Your code is recursive but it doesn't need to be. It would better as a method on a list class (or a static Node method):</p>\n\n<pre><code>boolean isLoopy()\n{\n Set<Node> visited = new HashSet<Node>();\n for(Node node = head; node != null; node = node.next)\n {\n if( visited.contains(node) )\n {\n return true;\n }else{\n visited.add(node);\n }\n }\n return false;\n}\n</code></pre>\n\n<p>I think this code is clearer and somewhat more efficient. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T15:54:22.917",
"Id": "2713",
"ParentId": "2711",
"Score": "10"
}
},
{
"body": "<pre><code>Node n = null;\n</code></pre>\n\n<p>In Java, objects by default initialized to null, so</p>\n\n<pre><code>Node n;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T12:03:26.420",
"Id": "4238",
"Score": "4",
"body": "Setting a variable on declaration explicitly to null is a good thing to do, because it indicates to a reader of the code, that this variable purposely may not be assigned to."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T20:15:18.210",
"Id": "2717",
"ParentId": "2711",
"Score": "-1"
}
},
{
"body": "<p>This is a classic interview question. At this point, I think it measures more whether you've been to many interviews than whether you can think creatively algorithmically while on a job interview. Anyway,</p>\n\n<pre><code>public class Node {\n public Node next = null;\n public Node() {}\n public Node(Node n) { next = n; }\n public boolean hasNext() { return next != null; }\n public boolean hasLoop() {\n Node n = this, n2 = this;\n while (n.hasNext()) {\n n = n.next;\n if (n == n2) return true;\n if (!n.hasNext()) return false;\n n = n.next;\n if (n == n2) return true;\n n2 = n2.next;\n }\n return false;\n }\n}\n</code></pre>\n\n<p>(Not compiled, but you get the idea. I think getters/setters for next is overkill, given that the whole point is to manipulate the field at a low level, given this data structure.)</p>\n\n<p>This uses constant space; since <code>n</code> travels twice as fast as <code>n2</code>, if there is a loop, both <code>n</code> and <code>n2</code> will get caught at it and <code>n</code> will overtake <code>n2</code> from behind (after a maximum number of steps equal to twice (lead-in plus loop length)). Otherwise, <code>n</code> will reach the end and we're done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-22T13:11:43.487",
"Id": "103198",
"Score": "1",
"body": "More information about the algorithm can be found in the wiki page for Tortoise and Hare algorithm: http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T03:37:19.003",
"Id": "2724",
"ParentId": "2711",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "2713",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T15:35:55.187",
"Id": "2711",
"Score": "10",
"Tags": [
"java",
"interview-questions"
],
"Title": "Linked list loop detection in Java"
}
|
2711
|
<p>I've written a fairly small library that <em>abstracts cookie functionality in a way that mimics working with a database model</em>. The repository is on <a href="https://bitbucket.org/yrizos/simplecookie/overview" rel="nofollow">bitbucket</a> and the code is small enough to embed here: </p>
<pre><code>class SimpleCookie {
/**
* Cookie value char limit
* @var int
*/
const valueLimit = 2000;
/**
* Cookie data
* @var array
*/
protected $cookieData = array();
/**
* Cookie name
* @var string
*/
protected $cookieName = null;
/**
* If cookie exists, it get's loaded on construct
*
* @param string $cookieName
*/
public function __construct($cookieName) {
$this->load($cookieName);
}
/**
* @param string $key
* @return mixed
*/
public function __get($key) {
return
isset($this->cookieData[$key])
? $this->cookieData[$key]
: null;
}
/**
* @param string $key
* @param mixed $value
*/
public function __set($key, $value) {
$this->cookieData[$key] = $value;
}
/**
* @param string $key
* @return bool
*/
public function __isset($key) {
return isset($this->cookieData[$key]);
}
/**
* @param string $key
*/
public function __unset($key) {
if(isset($this->cookieData[$key])) {
unset($this->cookieData[$key]);
}
}
/**
* Load a cookie
*
* @param string $cookieName
* @return SimpleCookie|false
*/
public function load($cookieName) {
$this->setName($cookieName);
if(!$data = $this->getCookie($this->cookieName)) {
return false;
}
if(is_array($data)) {
$data = implode("", $data);
}
return $this->setData( $this->getCookieArray( $data ) );
}
/**
* Save a cookie
*
* @param int $expires
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httponly
* @return bool
*/
public function save($expires = 0, $path = "/", $domain = null, $secure = false, $httponly = false) {
$value = $this->getCookieString($this->cookieData);
$name = $this->cookieName;
if(strlen($value) > SimpleCookie::valueLimit) {
$value = str_split($value, SimpleCookie::valueLimit);
$result = true;
foreach($value as $k => $v) {
$result = $result && $this->setCookie("{$name}[$k]", $v, $expires, $path, $domain, $secure, $httponly);
}
return $result;
}
return $this->setCookie($name, $value, $expires, $path, $domain, $secure, $httponly);
}
/**
* Set cookie
*
* @since version 0.2
* @param int $expires
* @param string $value
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httponly
* @return bool
*/
protected function setCookie($name, $value, $expires = 0, $path = "/", $domain = null, $secure = false, $httponly = false) {
$expires = is_int($expires) || ctype_digit($expires) ? (int) $expires : 0;
$path = is_string($path) ? $path : "/";
$domain = is_string($domain) || is_null($domain) ? $domain : null;
$secure = $secure === true;
$httponly = $httponly === true;
return setcookie($name, $value, $expires, $path, $domain, $secure, $httponly);
}
/**
* Get cookie
*
* @since version 0.2
* @param string $name
* @return mixed|false
*/
protected function getCookie($name) {
return isset($_COOKIE[$name]) && !empty($_COOKIE[$name]) ? $_COOKIE[$name] : false;
}
/**
* Delete a cookie
*
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httponly
* @return bool
*/
public function delete($path = "/", $domain = null, $secure = false, $httponly = false) {
$this->setData(array());
return $this->save(time() - 3600, $path, $domain, $secure, $httponly);
}
/**
* Get cookie value from array
*
* Called on save
*
* @param array $data
* @return string
*/
protected function getCookieString(array $data) {
return http_build_query($data);
}
/**
* Get cookie array from cookie value
*
* Called on load
*
* @param string $string
* @throws InvalidArgumentException
* @return array
*/
protected function getCookieArray($string) {
if(!is_string($string)) {
throw new InvalidArgumentException("Cookie string must be a string :)");
}
parse_str($string, $data);
return $data;
}
/**
* Set cookie data
*
* This function updates internal data array,
* it does not save the cookie.
*
* @param array $data
* @return SimpleCookie
*/
public function setData(array $data) {
$this->cookieData = $data;
return $this;
}
/**
* Get data array
*
* @return array
*/
public function getData() {
return $this->cookieData;
}
/**
* Set cookie name
*
* @param string $cookieName
* @throws InvalidArgumentException
* @return SimpleCookie
*/
protected function setName($cookieName) {
if(!is_string($cookieName) || empty($cookieName)) {
throw new InvalidArgumentException("Cookie name must be a non empty string");
}
$this->cookieName = $cookieName;
return $this;
}
}
</code></pre>
<p>I would really love to hear your critiques on:</p>
<ul>
<li>Code quality</li>
<li>Code clarity</li>
<li>Comments sufficiency</li>
</ul>
<p>I'm more interested in what I'm doing wrong than right. Any opinions on the actual usefulness of the library are welcome, although not central in my question.</p>
|
[] |
[
{
"body": "<p><em>Code quality</em></p>\n\n<p>Well, I did not try your code, but at a first glance it seems to be very robust code. But for further development I would recomend you to set up a test case for your class. See <a href=\"http://www.phpunit.de\" rel=\"nofollow\">http://www.phpunit.de</a>.</p>\n\n<p><em>Code clarity</em></p>\n\n<p>The only part where I got stuck a bit was the save method, but after a second read I got the point. In my opinion any programmer with sufficient oo skills can get your code after one or two reads.</p>\n\n<p><em>Comments sufficiency</em></p>\n\n<p>Sometimes you comment, when there is no need for it. Consider the save method: through the methods name it should be clear, that a cookie gets saved. So no need for this comment. Same goes for the constructor, the load, setCookie, getCookie, setData and setName methods. As your code is very readable, I don't see any need for this degree of commenting. I would recomend you just to use the phpdoc comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T17:57:09.827",
"Id": "9263",
"Score": "1",
"body": "Bah, there is no such thing as overcommenting if you stick to -why- as opposed to what and how."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T18:59:04.460",
"Id": "9268",
"Score": "2",
"body": "Well... Sometimes you do not need to explain why because it should be obvious by reading the code. But I think that's a matter of personal preference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T07:21:54.903",
"Id": "2727",
"ParentId": "2715",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "2727",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T20:01:19.937",
"Id": "2715",
"Score": "8",
"Tags": [
"php"
],
"Title": "Critique request: PHP cookie library"
}
|
2715
|
<p>The method must search <code>Product</code>s found by criteria and store them in <code>@products</code>.</p>
<p>The criteria are as follows:</p>
<ul>
<li>If the user enters something in <code>text_field</code> (<code>:search_keywords</code>) then the product's name needs to be matched with that word</li>
<li>If the user specifies <code>product_type</code> (<code>:product[:type]</code>) then all the found products must be of that type.</li>
</ul>
<p></p>
<pre><code>def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T14:13:52.547",
"Id": "4338",
"Score": "7",
"body": "Note that the way you build your queries is extremely vulnerable to SQL injection. Please see http://api.rubyonrails.org/classes/ActiveRecord/Base.html under the conditions section on how to safely build queries."
}
] |
[
{
"body": "<ol>\n<li><p>You can use blank? </p></li>\n<li><p>You need user parameters in SQL query.</p></li>\n<li><p>Maybe you need escaping character <code>%</code> in <code>search_keywords</code>.</p></li>\n</ol>\n\n<p></p>\n\n<pre><code>def search\n keywords_blank = params[:search_keywords].blank?\n type_blank = params[:product] && !params[:product][:type].blank?\n\n @products = if keywords_blank && type_blank\n Product.all\n elsif keywords_blank\n Product.find_all_by_product_type_id(params[:product][:type])\n elsif type_blank\n Product.find(:all, :conditions => [\"name LIKE :name\", :name => \"%#{params[:search_keywords]}%\"])\n else\n Product.find(:conditions => [\"name LIKE :name AND product_type_id = :type\", {:name => \"%#{params[:search_keywords]}%\", :type => params[:product][:type]}])\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T09:13:58.023",
"Id": "2730",
"ParentId": "2716",
"Score": "1"
}
},
{
"body": "<p>Try to use scopes, its a lot nicer</p>\n\n<pre><code>def search\n @products = Products.scoped\n if !params[:search_keywords].blank?\n @products = @products.where(\"name LIKE ?\", \"%#{params[:search_keywords]}%\")\n end\n if !params[:product].try(:[], :type).blank?\n @products = @products.where(:product_type_id => params[:product][:type])\n end\n @products # maybe @products.all if realy needed\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T14:10:49.003",
"Id": "2798",
"ParentId": "2716",
"Score": "8"
}
},
{
"body": "<p>I've seen many Railers' codes tempt to shove many logic in View and Controller. Allow me to add these important emphases:</p>\n\n<ol>\n<li><p><strong>Skinny Controller Fat Model</strong> which is one of <em>The Elegant Rails Way principles</em>.</p></li>\n<li><p>And <strong>Testing</strong>. </p></li>\n</ol>\n\n<p>Here I have <strong>products_controller.rb</strong> file inside <strong>app/controllers</strong> directory that contains this:</p>\n\n<pre><code>class ProductsController < ApplicationController\n def search\n @products = Product.search(params)\n end\nend\n</code></pre>\n\n<p>I put the logic inside the Model. Here is my <strong>product.rb</strong> file inside <strong>app/models</strong> directory:</p>\n\n<pre><code>class Product < ActiveRecord::Base\n scope :nm, lambda { |n| where \"name LIKE ?\", '%' + n + '%' }\n scope :criteria, lambda { |n, type| nm(n).where type_id: type }\n\n def self.search(opts={})\n return all if opts.empty?\n return nm(opts[:search_keywords]) unless opts[:search_keywords].nil?\n return criteria(opts[:name], opts[:type]) if opts[:product].try(:[], :type).empty?\n end\nend\n</code></pre>\n\n<p>You could also try to experiment <em>Dynamic Scope Construction</em> to improve Product Model code above. I haven't tried it successfully <strong>AND</strong> efficiently here, let me know if anyone can make it better, anyway.</p>\n\n<p>And <strong>Testing</strong>. You can also test your app using <a href=\"http://apidock.com/rspec\" rel=\"nofollow\">RSpec</a>, <a href=\"http://cukes.info/\" rel=\"nofollow\">Cucumber</a>, Ruby Selenium, Watir, or any other Test for Ruby Environment, but here I'll only show you how to do it using Ruby Unit Test. Here is my <strong>product_test.rb</strong> inside <strong>test/unit</strong> directory:</p>\n\n<pre><code>require 'test_helper'\nrequire 'product'\n\nclass ProductTest < ActiveSupport::TestCase\n fixtures :products\n\n def test_nm\n assert_equal Product.nm(\"Pick\").first.name, products(:pickaxe).name\n end\n\n def test_criteria\n assert_equal Product.criteria(\"Bach\", 2).first.name, products(:bach).name\n end\n\n def test_search\n assert_equal Product.search(:search_keywords => \"Pick\").first.name, \n products(:pickaxe).name\n assert_equal Product.search(:search_keywords => \"Pick\", :type => 1).first.name, \n products(:pickaxe).name\n assert_equal Product.search.size, Product.count\n end\nend\n</code></pre>\n\n<p>And its related fixture. Here is my <strong>products.yml</strong> file inside <strong>test/fixtures</strong> directory:</p>\n\n<pre><code>pickaxe:\n name: Pickaxe 3\n type_id: 1\n\nbach:\n name: Bach\n type_id: 2\n\nlotr:\n name: LOTR\n type_id: 3\n</code></pre>\n\n<p>And for controller testing, here is my <strong>products_controller_test.rb</strong> file inside <strong>test/functional</strong> directory:</p>\n\n<pre><code>require 'test_helper'\nrequire \"products_controller\"\n\nclass ProductsControllerTest < ActionController::TestCase\n fixtures :products\n\n test \"should get search\" do\n get :search, :search_keywords => 'Pick', :product => { :type => '1' }\n assert_response :success\n assert_not_nil assigns(:products)\n end\nend\n</code></pre>\n\n<p>Let's go test them. I use:</p>\n\n<pre><code>. ruby -v\nruby 1.9.2p0 (2010-08-18) [i386-darwin9.8.0]\n. rails -v\nRails 3.0.9\n</code></pre>\n\n<p>Here is my test's result:</p>\n\n<pre><code>. rake test\n(in /Users/arie/se/tester)\nNOTICE: CREATE TABLE will create implicit sequence \"products_id_seq\" for serial column \"products.id\"\nNOTICE: CREATE TABLE / PRIMARY KEY will create implicit index \"products_pkey\" for table \"products\"\nLoaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader\nStarted\n...\nFinished in 0.237899 seconds.\n\n3 tests, 5 assertions, 0 failures, 0 errors, 0 skips\n\nTest run options: --seed 54809\nLoaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader\nStarted\n.\nFinished in 0.330431 seconds.\n\n1 tests, 2 assertions, 0 failures, 0 errors, 0 skips\n\nTest run options: --seed 25681\n</code></pre>\n\n<p>Alright! Worked like a charm! 0 errors for both unit (for model) and functional (for controller) tests. I also tested it from my browser and it worked.</p>\n\n<p><a href=\"http://ifile.it/ep6hyzb\" rel=\"nofollow\">You can also download my copy files here</a>.</p>\n\n<p>Links:</p>\n\n<ol>\n<li><a href=\"http://guides.rubyonrails.org/testing.html\" rel=\"nofollow\">Testing Reference</a></li>\n<li><a href=\"http://railscasts.com/episodes/155-beginning-with-cucumber\" rel=\"nofollow\">Beginning with Cucumber RailsCasts</a></li>\n<li><a href=\"http://m.onkey.org/active-record-query-interface\" rel=\"nofollow\">Active Record Query Interface 3.0</a></li>\n<li><a href=\"http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html\" rel=\"nofollow\">The Skinny on Scopes (Formerly named_scope)</a></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-23T03:50:44.843",
"Id": "3071",
"ParentId": "2716",
"Score": "6"
}
},
{
"body": "<p>You can use a combination of scopes to simplify the code. Also, you can take advantage of some handy Ruby/ActiveSupport methods and conventions to avoid if conditions.</p>\n\n<pre><code>def search\n @products = Product.scoped\n @products = @products.search_by_name(params[:search_keywords])\n @products = @products.search_by_type(params[:product][:type] rescue nil)\n # in your view\n # @products.all\nend \n\nclass Product\n\n def self.search_by_name(value)\n if value.present?\n where(\"name LIKE ?\", \"%#{value}%\")\n else\n self\n end\n end\n\n def self.search_by_type(value)\n if value.present?\n where(:product_type_id => value)\n else\n self\n end\n end\n\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T20:32:55.083",
"Id": "4460",
"ParentId": "2716",
"Score": "0"
}
},
{
"body": "<p>I like Bert Goethals, Arie and Simone Carletti's answers - my solution would have a touch of each:</p>\n\n<p>in your controller:</p>\n\n<pre><code>class ProductsController < ApplicationController\n\n def search\n keywords = params[:search_keywords]\n type_id = params[:product].try(:[],:type)\n @products = Product.search({:type_id => type_id, :keywords => keywords})\n end\n\nend\n</code></pre>\n\n<p>in your model</p>\n\n<pre><code> def self.search(options={})\n keywords = options[:keywords]\n type_id = options[:type_id]\n\n products = Product.scoped\n products = products.where(\"name like ?\",\"%#{keywords}%\") if keywords.present? \n products = products.where(:type_id => type_id) if type_id.present?\n products\n end\n</code></pre>\n\n<p>I could go with scopes but only if the scope will be used from more than one spot, otherwise the code is small enough to be understandable and organized without them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T18:19:25.427",
"Id": "12447",
"ParentId": "2716",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T20:05:46.223",
"Id": "2716",
"Score": "6",
"Tags": [
"ruby",
"ruby-on-rails",
"search"
],
"Title": "Search for products based on criteria"
}
|
2716
|
<p>This is a social share widget for guubo.com. The live widget can be seen <a href="http://guy.lt/" rel="nofollow">here</a> (though you need to be signed in guubo.com, otherwise you will see a logged-out user interface). JS is not my first language, therefore some reviews are welcome.</p>
<pre><code>// create iframe
var iframe = document.createElement('iframe');
iframe.setAttribute('style', 'border:none; overflow:hidden; width: 93px; height: 32px;');
iframe.setAttribute('scrolling', 'no');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowTransparency', 'true');
document.body.appendChild(iframe);
// access iframe object
iframe.doc = null;
if(iframe.contentDocument)
{
iframe.doc = iframe.contentDocument;
}
else if(iframe.contentWindow)
{
iframe.doc = iframe.contentWindow.document;
}
else if(iframe.document)
{
iframe.doc = iframe.document;
}
iframe.doc.open();
iframe.doc.close();
// load CSS to iframe window
var css_object = document.createElement('link');
css_object.rel = 'stylesheet';
css_object.type = 'text/css';
css_object.href = 'http://guubo.com/public/css/share.css?' + Math.random();
iframe.doc.head.appendChild(css_object);
var css_object = css_object.cloneNode('false');
css_object.href = 'http://guubo.com/public/css/reset.css?' + Math.random();
iframe.doc.head.appendChild(css_object);
// load CSS to parent window
var css_object = css_object.cloneNode('false');
css_object.href = 'http://guubo.com/public/css/share.css?' + Math.random();
iframe.doc.body.innerHTML = '<a href="http://guubo.com/?url=' + encodeURIComponent(document.location.href) + '&name=' + encodeURIComponent(document.title) + '" target="_blank" class="guubo_ui guubo_share_button" onclick="parent.guuboCreateDialog(); return false;"><?=$share_count?></a>';
function calculateCeneteredPosition(Xwidth, Yheight)
{
// First, determine how much the visitor has scrolled
var scrolledX, scrolledY;
if( self.pageYOffset ) {
scrolledX = self.pageXOffset;
scrolledY = self.pageYOffset;
} else if( document.documentElement && document.documentElement.scrollTop ) {
scrolledX = document.documentElement.scrollLeft;
scrolledY = document.documentElement.scrollTop;
} else if( document.body ) {
scrolledX = document.body.scrollLeft;
scrolledY = document.body.scrollTop;
}
// Next, determine the coordinates of the center of browser's window
var centerX, centerY;
if( self.innerHeight ) {
centerX = self.innerWidth;
centerY = self.innerHeight;
} else if( document.documentElement && document.documentElement.clientHeight ) {
centerX = document.documentElement.clientWidth;
centerY = document.documentElement.clientHeight;
} else if( document.body ) {
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;
}
return {left: scrolledX + (centerX - Xwidth) / 2, top: scrolledY + (centerY - Yheight) / 2};
}
function countCharacters()
{
var guubo_message = document.getElementById('guubo_message');
var count_message = document.getElementById('guubo_count');
count_message.innerHTML = 116-guubo_message.value.length;
}
function submitForm()
{
document.forms["guubo_form"].submit();
guubo_dialog.innerHTML = 'Message sent to guubo.com!';
setTimeout(function(){
guuboCloseDialog();
}, 1000);
}
function guuboCloseDialog()
{
document.body.removeChild(guubo_dialog);
}
function guuboCreateDialog()
{
guubo_dialog = document.createElement('div');
var position = calculateCeneteredPosition(400, 150);
guubo_dialog.setAttribute('id', 'guubo_dialog');
guubo_dialog.setAttribute('class', 'guubo_dialog');
guubo_dialog.setAttribute('style', 'left: ' + position.left + 'px; top: ' + position.top + 'px;');
guubo_dialog.innerHTML = '\
<form name="guubo_form" id="guubo_form" action="http://guubo.com/share3.php" method="post">\
<div id="guubo_dialog_header">\
<div class="left"><a href="http://guubo.com" target="_blank">guubo.com</a> – chain share & analytics service</div>\
<div class="right"><a href="#" onclick="parent.guuboCloseDialog(); return false;">close dialog</a></div>\
</div>\
\
<textarea name="message" id="guubo_message" onKeyDown="countCharacters();" onKeyUp="countCharacters();" maxlength="116">' + document.title + '</textarea>\
<input type="submit" value="Share" onclick="parent.submitForm(); return false;" />\
<p><span id="guubo_count"></span> characters remaining. guubo.com will automatically append URL to the message.</p>\
</form>\
<div class="clear"></div>';
document.body.appendChild(guubo_dialog);
countCharacters();
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code sets a lot of global variables, and you should always <a href=\"http://dev.opera.com/articles/view/javascript-best-practices/#avoidglobals\" rel=\"nofollow noreferrer\">avoid them</a>. The easiest way to do that is \"<a href=\"https://stackoverflow.com/questions/1841916/how-to-avoid-global-variables-in-javascript/1841941#1841941\">to wrap your code in a closure and manually expose only those variables you need globally to the global scope.</a>\"</p>\n\n<p>Your script works a lot with DOM and DOM related objects. A lot of the goals you seem to be trying to reach for in that area could be achieved more expressively using the robust patterns found in a good library like jQuery, Prototype, Dojo, or Mootools. It is nearly always best to pick one of them and learn the API rather than trying to reinvent the wheel. Changes will be easier, and, likely, your code will be more cross-browser compatible. Don't use such a library for everything under the sun, but most of them cover a lot of common concerns.</p>\n\n<p>With jQuery, for example, this line:</p>\n\n<pre><code>guubo_dialog.setAttribute('style', 'left: ' + position.left + 'px; top: ' + position.top + 'px;');\n</code></pre>\n\n<p>need not depend on an awkward string concatenation to set the style attributes. It could instead look much cleaner and be more adaptable:</p>\n\n<pre><code>$(guubo_dialog).css({\n 'left': position.left + 'px',\n 'top': position.top + 'px'\n});\n</code></pre>\n\n<p>To keep your code style consistant, consider using JSLint or JSHint to tell you where you've gone wrong. <code>guubo_dialog</code>, for example, ought to be explicitly declared as a variable somewhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-29T03:16:27.837",
"Id": "3191",
"ParentId": "2718",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "3191",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T22:03:18.047",
"Id": "2718",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Social share widget for guubo.com"
}
|
2718
|
<p>This is my first attempt at a jQuery plugin. Any tips or comments in regards the the plugin setup would be appreciated. I'm also looking for a general review over the code itself. I'm wondering if there is a better way to encode the font. The way I'm doing it now makes it easy to see, read and create the characters, but it's bulky.</p>
<p>One item to note it the font is not yet complete, but most screens/animations have what they need. I should have the font finished out in the next few days.</p>
<p>You can see a working ANSI animated screen <a href="http://justinzaun.com/ansi" rel="nofollow">here</a>. There is a known issue with IE that prevents this from working. I know the fix, but just haven't gotten doing it yet.</p>
<p>The full font is not listed here as it's too large to post. A full listing is <a href="http://justinzaun.com/ansi/js/ansi.js" rel="nofollow">here</a>. Only the majority of the font has been removed from the listing below.</p>
<pre><code>(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
var $this = $(this);
$this.addClass('ansiScreen');
var data = $this.data('ansi');
if (!data) {
data = new Object();
data.target = $this;
data.fontheight = 16;
data.fontwidth = 8;
data.canvas = $('<canvas width="' + (data.fontwidth * 80) + 'px" height="' + (data.fontheight * 25) + 'px">');
$this.append(data.canvas);
data.ctx = data.canvas[0].getContext('2d');
data.processInterval = null;
data.ansi = null;
data.ansiCode = null;
data.ansiPos = 0;
data.fgcolor = 'rgb(255, 255, 255)';
data.bgcolor = 'rgb(0, 0, 0)';
data.bold = false;
data.blink = false;
data.pos = [0, 0];
data.savepos = [0, 0];
data.screen = Array();
data.last = 0;
for (var i = 0; i < 25; i++) {
data.screen.push(Array());
for (var j = 0; j < 80; j++) {
data.screen[i].push([data.bgcolor, data.fgcolor, ' ', false, true]);
}
}
$this.data('ansi', data);
}
});
},
destroy: function () {
return this.each(function () {
var $this = $(this);
var data = $this.data('ansi');
// Clean up
$(window).unbind('.ansi');
data.tooltip.remove();
$this.removeData('ansi');
});
},
load: function (ansiUrl) {
return this.each(function () {
var $this = $(this);
var me = this;
$.ajax({
'url': ansiUrl,
'data': 'text',
beforeSend: function (jqXHR, settings) {
jqXHR.overrideMimeType('text/plain; charset=x-user-defined');
},
success: function(ansiData) {
var data = $this.data('ansi');
if (data.processInterval != null) {
clearInterval(data.processInterval);
clearInterval(data.screenInterval);
}
data.ansi = ansiData;
data.ansiPos = 0;
data.fgcolor = 'rgb(255, 255, 255)';
data.bgcolor = 'rgb(0, 0, 0)';
data.bold = false;
data.blink = false;
data.pos = [0, 0];
data.savepos = [0, 0];
var interval = setInterval(function () {
processAnsi.call(me);
}, 5);
data.processInterval = interval;
$this.data('ansi', data);
updateDisplay.call(me);
}
});
});
}
};
$.fn.ansi = function (method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.ansi');
}
};
// Process a byte from teh ansi data
function processAnsi() {
var $this = $(this);
var data = $this.data('ansi');
if (data.ansiPos > data.ansi.length)
{
clearInterval(data.processInterval);
return;
}
var code = data.ansi.charCodeAt(data.ansiPos) & 0xff;
data.ansiPos += 1;
$this.data('ansi', data);
var display = true;
if (code < 33 || code > 126)
{
switch (code)
{
case 0: display = false; break;
case 10: display = false; cursorStartOfLine.call(this); break;
case 13: display = false; cursorDown.call(this, 1); break;
case 27: display = false; ansiCode.call(this); break;
default: display = true; break;
}
}
if (display) {
putCharacter.call(this, code);
}
updateDisplay.call(this);
}
function ansiCode() {
var $this = $(this);
var data = $this.data('ansi');
if (data.ansiPos > data.ansi.length)
return '-';
var valid = /^[0-9;HABCDRsuJKmh]$/;
var end = /^[HABCDRsuJKmh]$/;
var char = data.ansi[data.ansiPos];
var escape = '';
if (char == '[')
{
var stop = false;
do {
data.ansiPos += 1;
var char = data.ansi[data.ansiPos];
escape += char;
stop = end.test(char);
} while (valid.test(char) && !stop)
data.ansiPos += 1;
}
switch(escape[escape.length - 1])
{
case 'J': // Clear screen
if (escape == '2J') {
clearDisplay.call(this);
}
break;
case 'A': // Move up
var lines = parseInt(escape.substring(0, escape.length - 1));
if (isNaN(lines)) { lines = 1; }
data.pos[1] -= lines;
if (data.pos[1] < 0) { data.pos[1] = 0; }
break;
case 'B': // Move down
var lines = parseInt(escape.substring(0, escape.length - 1));
if (isNaN(lines)) { lines = 1; }
cursorDown.call(this, lines);
break;
case 'C': // Move Forward
var spaces = parseInt(escape.substring(0, escape.length - 1));
if (isNaN(spaces)) { spaces = 1; }
cursorForward.call(this, spaces);
break;
case 'D': // Move back
var spaces = parseInt(escape.substring(0, escape.length - 1));
if (isNaN(spaces)) { lines = 1; }
data.pos[0] -= spaces;
if (data.pos[0] < 0) { data.pos[0] = 0; }
break;
case 'H': // Move To
var codes = escape.substring(0, escape.length - 1).split(';');
if (isNaN(codes[0])) { codes[0] = 1; }
if (isNaN(codes[1])) { codes[1] = 1; }
data.pos[0] = codes[1] - 1;
data.pos[1] = codes[0] - 1;
break;
case 'K': // Clear
var mode = parseInt(escape.substring(0, escape.length - 1));
if (isNaN(mode)) { mode = 0; }
switch (mode)
{
case 2: // clear current line
for (var i=0; i< data.screen[0].length; i++)
{
data.screen[data.pos[1]][i] = [data.bgcolor, data.fgcolor, 32, false, true];
}
break;
case 1: // clear start of line
for (var i=0; i< data.pos[1]; i++)
{
data.screen[data.pos[1]][i] = [data.bgcolor, data.fgcolor, 32, false, true];
}
break;
case 0: // clear end of line
default:
for (var i=data.pos[1]; i< data.screen[0].length; i++)
{
data.screen[data.pos[1]][i] = [data.bgcolor, data.fgcolor, 32, false, true];
}
break;
}
break;
case 's': // Save position
data.savepos[0] = data.pos[0];
data.savepos[1] = data.pos[1];
break;
case 'u': // Restore position
data.pos[0] = data.savepos[0];
data.pos[1] = data.savepos[1];
break;
case 'm': // Change attrinutes
var codes = escape.substring(0, escape.length - 1).split(';');
for (var i=0; i < codes.length; i++) {
var code = codes[i];
switch (code) {
case '0':
data.bold = false;
data.blink = false;
data.fgcolor = 'rgb(255, 255, 255)';
data.bgcolor = 'rgb(0, 0, 0)';
break;
case '1':
data.bold = true;
break;
case '5':
data.blink = true;
break;
case '30':
data.fgcolor = !data.bold ? 'rgb(0, 0, 0)' : 'rgb(85, 85, 85)';
break;
case '31':
data.fgcolor = !data.bold ? 'rgb(170, 0, 0)' : 'rgb(255, 85, 85)';
break;
case '32':
data.fgcolor = !data.bold ? 'rgb(0, 170, 0)' : 'rgb(85, 255, 85)';
break;
case '33':
data.fgcolor = !data.bold ? 'rgb(170, 85, 0)' : 'rgb(255, 255, 0)';
break;
case '34':
data.fgcolor = !data.bold ? 'rgb(0, 0, 170)' : 'rgb(85, 85, 255)';
break;
case '35':
data.fgcolor = !data.bold ? 'rgb(170, 0, 170)' : 'rgb(255, 85, 255)';
break;
case '36':
data.fgcolor = !data.bold ? 'rgb(0, 170, 170)' : 'rgb(85, 255, 255)';
break;
case '37':
data.fgcolor = !data.bold ? 'rgb(170, 170, 170)' : 'rgb(255, 255, 255)';
break;
case '40':
data.bgcolor = 'rgb(0, 0, 0)';
break;
case '41':
data.bgcolor = 'rgb(170, 0, 0)';
break;
case '42':
data.bgcolor = 'rgb(0, 170, 0)';
break;
case '43':
data.bgcolor = 'rgb(170, 85, 0)';
break;
case '44':
data.bgcolor = 'rgb(0, 0, 170)';
break;
case '45':
data.bgcolor = 'rgb(170, 0, 170)';
break;
case '46':
data.bgcolor = 'rgb(0, 170, 170)';
break;
case '47':
data.bgcolor = 'rgb(170, 170, 170)';
break;
default:
$('#debug').html($('#debug').html() + '<br>Unknown Attribute: ' + code);
break;
}
}
break;
default:
$('#debug').html($('#debug').html() + '<br>esc[' + escape);
break;
}
$this.data('ansi', data);
return '';
}
// Move the cursor position up a number of lines
function cursorStartOfLine(lines) {
var $this = $(this);
var data = $this.data('ansi');
data.pos[0] = 0;
$this.data('ansi', data);
}
// Move the cursor position down a number of lines
// scroll the screen if needed
function cursorDown(lines) {
var $this = $(this);
var data = $this.data('ansi');
var rows = data.screen.length;
var cols = data.screen[0].length;
data.pos[1] += lines;
if (data.pos[1] > data.screen.length - 1) {
data.pos[1] = rows - 1;
for (var i = 0; i < rows - 1; i++) {
for (var j = 0; j < cols; j++) {
data.screen[i][j] = data.screen[i+1][j];
data.screen[i][j][4] = true;
}
}
for (var j = 0; j < cols; ++j) {
data.screen[rows-1][j] = [data.bgcolor, data.fgcolor, 32, false, true];
}
}
$this.data('ansi', data);
}
// Move the cursor position forward a number of columns
function cursorForward(cols) {
var $this = $(this);
var data = $this.data('ansi');
data.pos[0] += cols;
if (data.pos[0] > data.screen[0].length - 1) {
data.pos[0] = 0;
cursorDown.call(this,1);
}
$this.data('ansi', data);
}
// Puts a character on screen
function putCharacter(charCode) {
var $this = $(this);
var data = $this.data('ansi');
data.screen[data.pos[1]][data.pos[0]] = [data.bgcolor, data.fgcolor, charCode, data.blink, true];
$this.data('ansi', data);
// Move forward 1 character
cursorForward.call(this, 1);
}
// Clear the screen
function clearDisplay() {
var $this = $(this);
var data = $this.data('ansi');
for (var i = 0; i < data.screen.length; i++) {
for (var j = 0; j < data.screen[i].length; j++) {
data.screen[i][j] = [data.bgcolor, data.fgcolor, ' ', data.blink, true];
}
}
data.pos = [0, 0];
$this.data('ansi', data);
}
// Update the container with the current screen
function updateDisplay() {
var $this = $(this);
var data = $this.data('ansi');
for (var i = 0, length1 = data.screen.length; i < length1; ++i) {
var a = data.screen[i]; // cache object
for (var j = 0, length2 = a.length; j < length2; ++j) {
if (a[j][4])
{
data.ctx.save();
data.ctx.beginPath();
data.ctx.rect (data.fontwidth * j, data.fontheight * i, data.fontwidth, data.fontheight);
data.ctx.clip();
data.ctx.fillStyle = a[j][0];
data.ctx.fillRect (data.fontwidth * j, data.fontheight * i, data.fontwidth, data.fontheight);
data.ctx.fillStyle = a[j][1];
drawCharater.call(this, a[j][2], [data.fontwidth * j, data.fontheight * i], 1);
data.ctx.restore();
a[j][4] = false;
}
}
}
$this.data('ansi', data);
}
// Draw a single character at a given location
function drawCharater(code, location, size) {
var $this = $(this);
var data = $this.data('ansi');
var template = new Array();
switch(code)
{
case 32:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 48:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,1,1,1,1,0,0]);
template.push([0,1,1,0,0,1,1,0]);
template.push([1,1,0,0,0,0,1,1]);
template.push([1,1,0,0,0,0,1,1]);
template.push([1,1,0,1,1,0,1,1]);
template.push([1,1,0,1,1,0,1,1]);
template.push([1,1,0,0,0,0,1,1]);
template.push([1,1,0,0,0,0,1,1]);
template.push([0,1,1,0,0,1,1,0]);
template.push([0,0,1,1,1,1,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 49:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,1,1,1,0,0,0]);
template.push([0,1,1,1,1,0,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,1,1,1,1,1,1,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 50:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,1,1,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,1,1,0,0,0,0]);
template.push([0,1,1,0,0,0,0,0]);
template.push([1,1,0,0,0,0,0,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,1,1,1,1,1,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 51:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,1,1,1,1,0,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 52:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,1,1,0,0]);
template.push([0,0,0,1,1,1,0,0]);
template.push([0,0,1,1,1,1,0,0]);
template.push([0,1,1,0,1,1,0,0]);
template.push([1,1,0,0,1,1,0,0]);
template.push([1,1,1,1,1,1,1,0]);
template.push([0,0,0,0,1,1,0,0]);
template.push([0,0,0,0,1,1,0,0]);
template.push([0,0,0,0,1,1,0,0]);
template.push([0,0,0,1,1,1,1,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 53:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([1,1,1,1,1,1,1,0]);
template.push([1,1,0,0,0,0,0,0]);
template.push([1,1,0,0,0,0,0,0]);
template.push([1,1,0,0,0,0,0,0]);
template.push([1,1,1,1,1,1,0,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 54:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,1,1,1,1,0,0]);
template.push([0,1,1,0,0,0,0,0]);
template.push([1,1,0,0,0,0,0,0]);
template.push([1,1,0,0,0,0,0,0]);
template.push([1,1,1,1,1,1,0,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 55:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([1,1,1,1,1,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,1,1,0,0]);
template.push([0,0,0,1,1,0,0,0]);
template.push([0,0,1,1,0,0,0,0]);
template.push([0,0,1,1,0,0,0,0]);
template.push([0,0,1,1,0,0,0,0]);
template.push([0,0,1,1,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 56:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
case 57:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,1,1,1,1,1,0,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([1,1,0,0,0,1,1,0]);
template.push([0,1,1,1,1,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,0,1,1,0]);
template.push([0,0,0,0,1,1,0,0]);
template.push([0,1,1,1,1,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
default:
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
template.push([0,0,0,0,0,0,0,0]);
break;
}
for(var y=0; y<16; y++)
{
for(var x=0; x<8; x++)
{
if (template[y][x] == 1)
data.ctx.fillRect(location[0] + x, location[1] + y, 1, 1);
}
}
}
})(jQuery);
</code></pre>
|
[] |
[
{
"body": "<p>You could use a bit more concise syntax. For example, when filling the <code>data</code> object in ìnit()`, you could use literal object notation:</p>\n\n<pre><code>data = {\n target: $this,\n fontheight: 16,\n fontwidth: 8,\n canvas: $('<canvas width=\"' + (data.fontwidth * 80) + 'px\" height=\"' + (data.fontheight * 25) + 'px\">'),\n // etc.\n}\n</code></pre>\n\n<p>Or use <code>jQuery.extend()</code>, to add or overwrite properties.</p>\n\n<p>You don't need to reassign the <code>data</code> object (<code>$this.data('ansi', data);</code>) after changing the the properties of <code>data</code>, because it's a reference and all changes have been applied to the object \"inside jQuery\" already. Example:</p>\n\n<pre><code>var $example = jQuery(\"body\");\nvar data = {}; // Empty object\n$example.data(\"ansi\", data); // Assign data\nvar data = $example.data(\"ansi\"); // get reference\ndata.test = \"hello\";\nalert($example.data(\"ansi\").test); // Shows 'hello'. No need to call $example.data(\"ansi\", data); before\n</code></pre>\n\n<p>In <code>destroy()</code> you call <code>data.tooltip.remove();</code>, but I can't seem to see <code>data.tooltip</code> ever being set.</p>\n\n<p>You have some duplicate code, that could be refactored into a separate function, such as parsing the integers from the escape sequences.</p>\n\n<p>You should consider moving the actual \"business code\" parts into separate functions.</p>\n\n<p>The colors should be kept in an array/object instead of assigning them.</p>\n\n<p>(More maybe later.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T13:04:24.023",
"Id": "2733",
"ParentId": "2719",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2733",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T22:44:18.747",
"Id": "2719",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"plugin",
"graphics"
],
"Title": "jQuery to display ANSI graphics"
}
|
2719
|
<p>I commonly run into the need to implement IDisposable in my code. To correctly dispose of both managed and unmanaged resources requires a reasonable amount of boilerplate code. Based on the documentation found <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.dispose%28v=VS.100%29.aspx">here</a> I have created the following base class.</p>
<p>My intent is that any object I create that needs to dispose of resources doesn't need to rewrite the boilerplate code. Rather it can inherit from this object and implement two abstract methods.</p>
<p>Does this appear correct? And has anyone else written something similar? I would appreciate comments on the style, correctness and how well this conforms to best practices.</p>
<pre><code>public abstract class DisposableObject : IDisposable
{
private bool _disposed = false;
public bool Disposed
{
get { return _disposed; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposableObject()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
DisposeManagedResources();
}
DisposeUnmanagedResources();
_disposed = true;
}
}
protected abstract void DisposeManagedResources();
protected abstract void DisposeUnmanagedResources();
}
</code></pre>
<p>EDIT: Final Implementation</p>
<pre><code>public abstract class DisposableObject : IDisposable
{
public bool Disposed { get; private set;}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposableObject()
{
Debug.Assert(Disposed, "WARNING: Object finalized without being disposed!");
Dispose(false);
}
private void Dispose(bool disposing)
{
if (!Disposed)
{
if (disposing)
{
DisposeManagedResources();
}
DisposeUnmanagedResources();
Disposed = true;
}
}
protected virtual void DisposeManagedResources() { }
protected virtual void DisposeUnmanagedResources() { }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T12:22:01.517",
"Id": "4241",
"Score": "4",
"body": "One problem I see is you'll quickly run into multiple inheritance issues (or rather the lack of). I've often seen similar implementations however, and in some scenarios where you control the entire inheritance hierarchy I guess it is useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T16:04:31.207",
"Id": "4251",
"Score": "0",
"body": "Inheritance (or the lack of it) is something I considered as well. Primarily I am using this class to help wrap unmanaged libraries that I want to use in managed code. For this scenario I decided I could live with the limitation on inheritance."
}
] |
[
{
"body": "<p>Personally I would have made <code>Dispose(bool disposing)</code> protected virtual rather than have 2 abstract methods ... for consistency with most unsealed disposable objects in the framework. Also, I recall FxCop was quite pedantic about the implementation of IDisposable.</p>\n\n<p>If you still want to use use the two methods, I would suggest making at-least <code>DisposeUnmanagedResources()</code> virtual rather than abstract as a convenience to inheritors. I find it much more common for my disposable objects to dispose other objects rather than clean-up unmanaged resources of their own.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T03:27:07.487",
"Id": "2723",
"ParentId": "2720",
"Score": "4"
}
},
{
"body": "<p>I would think on making two changes:</p>\n\n<ol>\n<li>Make one or both <code>Dispose*Resources</code> methods virtual instead of abstract. Though it highly depends on how often do you need to handle unmanaged resources. I can't remember last time I was handling them and I would hate overriding this method in <strong>each</strong> class just to make it empty. </li>\n<li>I would add some logging either to your finalizer method or to <code>Dispose(bool disposing)</code> method in order to catch situations when disposable object wasn't disposed correctly by calling <code>Dispose()</code> method. Most developers are looking for such information and you have a good place to inject it.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T16:06:07.680",
"Id": "4252",
"Score": "0",
"body": "Both good suggestions, thanks! As far as logging goes, I'm considering adding assert statements to warn if Dispose is not called by the developer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T08:26:48.760",
"Id": "2728",
"ParentId": "2720",
"Score": "15"
}
},
{
"body": "<p>I'm in agreement with Brian, with the exception that I believe the <code>Dispose(bool disposing)</code> method should be abstract. My reasoning behind this, is that you must have a reason for inheriting from the <code>DisposableObject</code> type in the first place, in which case, having the method as virtual seems a little pointless, as it would be an optional implementation. If it's optional, why inherit from <code>DisposableObject</code> anyway?</p>\n\n<p>Having it as virtual would be beneficial where you have some common code, but perhaps a better design would be:</p>\n\n<pre><code>protected virtual void Dispose(bool disposing)\n{\n if (!Disposed)\n {\n DisposeInternal(disposing);\n Disposed = true;\n }\n}\n\nprotected abstract void DisposeInternal(bool disposing);\n</code></pre>\n\n<p>That way you can assure that <code>DisposeInternal</code> is only ever called when you are actually disposing, and it doesn't need to set the <code>Dispose</code> flag, as this is handled by the outer call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T03:29:42.110",
"Id": "4325",
"Score": "0",
"body": "My comment about making the method virtual as opposed to abstract was specifically regarding the case where there was a separate method to clean-up managed and unmanaged resources. In the case where there is a single clean-up method, I would agree that it should be abstract."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T03:38:17.003",
"Id": "4326",
"Score": "0",
"body": "In your sample code, you should call `DisposeInternal()` regardless of `disposing` and pass `disposing` into it, since unmanaged resources should be cleaned up on finalising if not already disposed of properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T06:10:42.983",
"Id": "4330",
"Score": "0",
"body": "@Brian - Good point, I'll update my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T19:01:42.210",
"Id": "4341",
"Score": "1",
"body": "I disagree that this function should be public. There is never a situation where it is correct for the user of the class to call Dispose(false). This distinction is only provided so that at runtime, if the developer has forgotten to call Dispose on the object, we won't be competing with the GC to dispose of any remaining objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T22:51:29.227",
"Id": "4346",
"Score": "0",
"body": "Another good point, I've changed it to protected..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T18:23:21.020",
"Id": "2790",
"ParentId": "2720",
"Score": "7"
}
},
{
"body": "<p>Something I've found useful in the past when implementing this pattern is to capture the stack trace during construction, and include this in the <code>Debug.Assert</code> message.</p>\n\n<p>Knowing where the object was constructed can often be a help in tracking down the source of the issue, especially if the objects are created in one place and then need to be disposed of by some other object which takes over responsibility for their lifetime.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T21:40:49.357",
"Id": "2792",
"ParentId": "2720",
"Score": "11"
}
},
{
"body": "<p>If this is restricted to wrapping unmanaged libraries, then it could be useful, but I wouldn't ever use it where there are no unmanged resources, it'll completely screw-up the garbage-collector- as one should not have a finalizer unless one absolutely needs it.</p>\n\n<p><a href=\"http://www.devx.com/dotnet/Article/33167/1954\" rel=\"nofollow\">You must implement finalizers very carefully; it's a complex operation that can carry considerable performance overhead.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-03T19:11:16.757",
"Id": "98574",
"Score": "0",
"body": "I would go so far as to suggest a separate subclass of this `DisposableObject` class implementing the finalizer. Most subclasses would inherit directly from `DisposableObject`, but if you need to write a quick wrapper for something unmanaged then you could use the specialized abstract subclass with a finalizer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-27T12:31:47.010",
"Id": "13120",
"ParentId": "2720",
"Score": "3"
}
},
{
"body": "<p>Adding a method for checking and throwing can clean up a lot of noise.</p>\n\n<pre><code>protected void VerifyDisposed()\n{\n if (_disposed)\n {\n throw new ObjectDisposedException(GetType().FullName);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-18T23:44:59.823",
"Id": "105067",
"ParentId": "2720",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2728",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T00:28:22.327",
"Id": "2720",
"Score": "36",
"Tags": [
"c#",
".net"
],
"Title": "DisposableObject base class for C#"
}
|
2720
|
<p>This code comes straight out from the example code in a Django book. I find it quite bad, mainly because the use of flags (<code>if ajax</code> then again <code>if ajax</code>) and unnecessarily bigger variable scope (set <code>title=''</code>, <code>tags=''</code> and then use these variables in different flows). The function body also seems way too long.<br>
I guess I'll subtract the book title (for the record I find the book in general good). </p>
<p>How would you rate this code, say out of 10 (10=very good, 3 and below being unacceptable)? (I'd rate it a 3) </p>
<p>The reason I ask is, I had rejected similar code in the past during code review and now I'm wondering whether I've been too strict or didn't understand python culture (I'm new to python).</p>
<pre><code>@login_required
def bookmark_save_page(request):
ajax = 'ajax' in request.GET
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
bookmark = _bookmark_save(request, form)
if ajax:
variables = RequestContext(request, {
'bookmarks': [bookmark],
'show_edit': True,
'show_tags': True
})
return render_to_response(
'bookmark_list.html', variables
)
else:
return HttpResponseRedirect(
'/user/%s/' % request.user.username
)
else:
if ajax:
return HttpResponse(u'failure')
elif 'url' in request.GET:
url = request.GET['url']
title = ''
tags = ''
try:
link = Link.objects.get(url=url)
bookmark = Bookmark.objects.get(
link=link,
user=request.user
)
title = bookmark.title
tags = ' '.join(
tag.name for tag in bookmark.tag_set.all()
)
except (Link.DoesNotExist, Bookmark.DoesNotExist):
pass
form = BookmarkSaveForm({
'url': url,
'title': title,
'tags': tags
})
else:
form = BookmarkSaveForm()
variables = RequestContext(request, {
'form': form
})
if ajax:
return render_to_response(
'bookmark_save_form.html',
variables
)
else:
return render_to_response(
'bookmark_save.html',
variables
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T15:24:19.487",
"Id": "4250",
"Score": "0",
"body": "Seems okay-ish to me, but I would absolutely split it up into into functions/methods instead of the slightly silly \"if ajax\" check. There are also too many hardcoded values. I'd give it a \"4\"."
}
] |
[
{
"body": "<p>In my opinion it's little bit hard to read. You have to split it up into POST/GET methods.\nThen you have to clean up code in POST/GET methods.\nSomething like this, for example.</p>\n\n<pre><code>@login_required\ndef bookmark_save(request):\n form = BookmarkSaveForm()\n if request.method == 'POST':\n form = bookmark_POST(request):\n if isinstance(form, HttpResponse):\n return form\n elif 'url' in request.GET:\n form = bookmark_GET(request)\n\n variables = RequestContext(request, {'form': form})\n\n if 'ajax' in request.GET:\n template_name = 'bookmark_save_form.html'\n else:\n temaplte_name = 'bookmark_save.html'\n return render_to_response(temaplte_name, variables)\n</code></pre>\n\n<p>And functions for POST/GET actions</p>\n\n<pre><code>def bookmark_POST(request):\n form = BookmarkSaveForm(request.POST)\n if form.is_valid():\n bookmark = _bookmark_save(request, form)\n if 'ajax' in request.GET:\n variables = RequestContext(request, {\n 'bookmarks': [bookmark],\n 'show_edit': True,\n 'show_tags': True\n })\n return render_to_response(\n 'bookmark_list.html', variables\n )\n else:\n return HttpResponseRedirect(\n '/user/%s/' % request.user.username\n )\n else:\n if 'ajax' in request.GET:\n return HttpResponse(u'failure')\n return form\n\ndef bookmark_GET(request):\n url = request.GET['url']\n try:\n link = Link.objects.get(url=url)\n bookmark = Bookmark.objects.get(\n link=link,\n user=request.user\n )\n title = bookmark.title\n tags = ' '.join(\n bookmark.tag_set.all().\\\n values_list('name', flat=True)\n )\n except (Link.DoesNotExist, Bookmark.DoesNotExist):\n title = ''\n tags = ''\n form = BookmarkSaveForm({\n 'url': url,\n 'title': title,\n 'tags': tags\n })\n return form\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T16:18:09.227",
"Id": "2737",
"ParentId": "2721",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "2737",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T01:23:22.153",
"Id": "2721",
"Score": "5",
"Tags": [
"python",
"django",
"ajax"
],
"Title": "How would you rate this python code? (Django AJAX)"
}
|
2721
|
<p>This is the first PDF class I have made for the iOS using code from Apple's samples. There could easily be stuff here wrong that I am missing. </p>
<p>I intend this to get images out of for a layer, for example:</p>
<pre><code>image.contents = (id)[self.test imageForPage: 3 size: CGSizeMake(4*dpc, 2*dpc)].CGImage;
</code></pre>
<p>Here is this hopefully decent code. Any suggestions are welcome.</p>
<pre><code>@interface PDFDocument : NSObject {
CGPDFDocumentRef pdfFile;
}
- (id) initWithURL: (NSURL*) url;
- (UIImage*) imageForPage: (size_t) pageno size: (CGSize) size;
- (CGSize) sizeOfPage: (size_t) pageno;
@end
@implementation PDFDocument
- (id) initWithURL: (NSURL*) url {
if ([super init])
{
// Open PDF
CGPDFDocumentRef doc = CGPDFDocumentCreateWithURL((CFURLRef)url);
if (doc == NULL)
@throw @"PDF File does not exist.";
pdfFile = doc;
}
return self;
}
- (UIImage*) imageForPage: (size_t) pageno size: (CGSize) size {
if (pdfFile) {
// Get First Page
CGPDFPageRef page = CGPDFDocumentGetPage(pdfFile, pageno);
if (page == NULL)
@throw @"Page does not exist.";
// Get Page Size
CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
// Start Drawing Context to Render PDF
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGRect u = { {0, 0}, size};
CGContextFillRect(context, u);
CGContextSetAllowsAntialiasing(context, NO);
CGContextSaveGState(context);
// Scale PDF
CGContextScaleCTM(context, size.width / cropBox.size.width, size.height / cropBox.size.height);
// Flip Context to render PDF correctly
CGContextTranslateCTM(context, 0.0, cropBox.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); // must retain?
UIGraphicsEndImageContext();
return img;
}
return nil;
}
- (CGSize) sizeOfPage: (size_t) pageno {
if (pdfFile) {
CGPDFPageRef page = CGPDFDocumentGetPage(pdfFile, pageno);
if (page == NULL)
@throw @"Page does not exist";
CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
return cropBox.size;
}
@throw @"No document loaded.";
}
@end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T05:35:34.823",
"Id": "4233",
"Score": "1",
"body": "I have encountered PDF files where the text is written in landscape but the page width and height will tell you that the page is in portrait. When opened in a PDF viewer, the file will be in landscape. I had to add special handling for files like those. Unfortunately, I don't have my code with me right now so I can't share, but I believe you're missing that part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T13:35:01.887",
"Id": "4244",
"Score": "1",
"body": "Something like this? http://ipdfdev.com/2011/03/23/display-a-pdf-page-on-the-iphone-and-ipad/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T13:29:40.760",
"Id": "4286",
"Score": "0",
"body": "Yeah, something like that. But I remember mine to be much simpler, like ~8 additional lines only."
}
] |
[
{
"body": "<p>One immediate change I'd make is how you're handling errors. While <code>try-catch</code> blocks are extremely common in other programming languages, I actually don't see them all that very often in Objective-C.</p>\n\n<p>That doesn't mean we won't have errors. It just means error handling is typically handled differently in my experience with Objective-C. Just take a look at some of the Foundation methods as example:</p>\n\n<pre><code>stringWithContentsOfFile:encoding:error:\n</code></pre>\n\n<p>You can send <code>nil</code> as the argument for the <code>error</code>, but otherwise, you send the method an <code>NSError</code> object, and when the method returns, if there was an error, you can check the object to find out what it was. In the case of an <code>init</code> method, if an error occurred, you'd also want to return <code>nil</code> as well as loading the error description in the passed error object.</p>\n\n<hr>\n\n<p>For completeness, it seems like it might be a good idea to create a corresponding <code>PDFPage</code> class. And instead of <code>imageForPage:size:</code> being called over and over to create pages, the end user would create instances of <code>PDFPage</code>. The <code>PDFDocument</code> in turn isn't much more than an array of <code>PDFPages</code> with some logic for adding a single page, array of pages, remove pages, from front, back, specific index, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T06:55:05.723",
"Id": "72930",
"Score": "0",
"body": "I never liked that kind of error control, although now I would never use exceptions like that either."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T02:16:16.413",
"Id": "42247",
"ParentId": "2722",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "42247",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T00:24:22.510",
"Id": "2722",
"Score": "8",
"Tags": [
"objective-c",
"ios",
"pdf"
],
"Title": "What can I improve on my iOS PDF class?"
}
|
2722
|
<p>I want to write some basic code on graph like DFS, BFS but before that I am coding graph representation in adjacency list, and some basic functions like <code>readgraphfrommatrix</code>. (This will initialize graph from adjacency matrix which is easier to supply as input to test the program.)</p>
<p>A vertex can have some info like name (say name of town), an edge can have some info like weight.</p>
<p>Does below code look decent enough or there are more standard recognized code snippets for adjacency list representation of graphs?</p>
<pre><code>struct edge
{
char *data;
}
struct vertex
{
char *data;
};
struct node
{
int vertexnumber;
struct node *next;
}
struct graph
{
int nvertex,nedges; //
struct vertex **V; // in main, I will malloc depending on input to have sth like struct vertex V[nvertex];
struct edge **E //to have like struct edge E[nedges];
struct node **list ; // to have like struct node* list[nvertex];
}
</code></pre>
|
[] |
[
{
"body": "<p>Code style: Use <code>typedef struct</code> instead of <code>struct</code> for cleanliness.</p>\n\n<p>This looks generally OK, but is not strictly speaking an adjacency list representation. In an adjacency list representation you store a list of verticies, and each of those verticies store a list of its neighbours. This structure implicitly encodes the edges of the graph.</p>\n\n<p>A more compact adjacency representation might look something more like this:</p>\n\n<pre><code>typedef struct{\n char *data;\n struct vertex **neighbours;\n char **weight; // edge to neighbours[i] stored in weight[i] \n} vertex;\n\ntypedef struct{\n int num_verticies;\n struct vertex **V;\n} graph;\n</code></pre>\n\n<p>The edges can be recovered by traversing the graph. To improve performance we may choose a structure other than a linked list to store the neighbours of a vertex.</p>\n\n<p>Which further annotations you keep in the graph struct will depend on the final use case. For certain algorithm having an explicit edge list will be vital, whereas for others it will be wasteful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-13T18:34:33.177",
"Id": "10870",
"ParentId": "2732",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T11:08:06.420",
"Id": "2732",
"Score": "5",
"Tags": [
"optimization",
"c",
"graph"
],
"Title": "Coding adjacency list representing graph"
}
|
2732
|
<p>I'm working on a few JavaScript functions for myself that I hope come in handy sometime. The first I wrote was a Capitalization function (yeah i know, <em>real</em> original. whatever)
I was just wondering if </p>
<ol>
<li>I'm doing anything incredibly stupid</li>
<li>There's anyway to make the code below more concise (like cool JS concision features i don't know about, tightening down on program flow, etc.)</li>
<li>There's anything else cool i can do</li>
</ol>
<p>Code:</p>
<pre><code>String.prototype.capitalize = function(everyWord) {
var words = this.split(" ");
if (everyWord == true) {
for (i = 0; i < words.length; i++) {
words[i] = cap(words[i]);
}
}
else {
words[0] = cap(words[0]);
}
return words.join(" ");
function cap(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
};
var x = "abraham lincoln yada yada";
x = x.capitalize();
alert(x);
x = x.capitalize(true);
alert(x);
</code></pre>
<p>Thanks!
<a href="http://jsfiddle.net/thomas4g/LpwRn/31/" rel="nofollow">http://jsfiddle.net/thomas4g/LpwRn/31/</a></p>
|
[] |
[
{
"body": "<p><a href=\"http://jsfiddle.net/a8h3a/3/\" rel=\"nofollow\">Live example</a></p>\n\n<pre><code>String.capitalize = function(str, everyWord) {\n return _.map(_.words(str), function(val, key) {\n return key === 0 || everyWord ? _.capitalize(val) : val;\n }).join(\" \");\n};\n</code></pre>\n\n<p>Write to <code>String</code> not <code>String.prototype</code>. Extending native prototypes is not friendly.</p>\n\n<p>Use <a href=\"http://documentcloud.github.com/underscore/\" rel=\"nofollow\">underscore</a> and <a href=\"https://github.com/msy/underscore.string\" rel=\"nofollow\">underscore.string</a>.</p>\n\n<p>Basically don't re-invent the wheel ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T14:53:54.990",
"Id": "4247",
"Score": "1",
"body": "but i *want* to reinvent the wheel. For my own learning purposes, and also so i can quickly grab my own code when i want it for a project instead of downloading something, etc. Also, what's the actual advantage of not using prototype? Other than not reinventing the wheel, anything else? (Thanks, btw :-) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T15:04:48.677",
"Id": "4248",
"Score": "0",
"body": "@ThomasShields other code breaks if you edit the prototype (Classic `for ... in`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T16:00:25.663",
"Id": "4288",
"Score": "0",
"body": "`Object.prototype` is the only one which breaks `for..in` if you add to it - you wouldn't/shouldn't need to use that operation with any other builtins. `Array.prototype` can be dicey in a mixed codebase purely because there are common methods people want to add, and they may clobber each other or get there first with a subtly different implementation. The rest of the builtin prototypes, I doubt anyone is that bothered about..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T16:05:34.970",
"Id": "4289",
"Score": "0",
"body": "@insin `for (var i in \"foobar\")`. I just generally dislike editing prototypes on native objects because it adds undocumented features and generally confuses state."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T14:51:16.833",
"Id": "2736",
"ParentId": "2734",
"Score": "4"
}
},
{
"body": "<pre><code>function capitalize(str, everyWord) {\n var r = /\\b(\\w)/\n if (everyWord) r = /\\b(\\w)/g\n return str.replace(r, function (c) { return c.toUpperCase(); });\n}\n</code></pre>\n\n<p>Regexes can be convenient for situations like this one...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T16:06:19.497",
"Id": "4290",
"Score": "1",
"body": "+1 for using string manipuation. although `this` is `window` so make it either of the `prototype` or pass in the `str` value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T17:22:32.537",
"Id": "4294",
"Score": "0",
"body": "@Raynos: OK, I switched to a classical function, instead, and I took in account the everyWord parameter which I forgot initially... Thanks for the remark. Note: actually, my first attempt tested the built in JavaScript capitalize() function... :-("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-28T21:36:14.180",
"Id": "7538",
"Score": "0",
"body": "if you are going for real concision, how about calling your param `ew` and saying: `var r=(ew)?/b(\\w)/g:/\\b(\\w)/;`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T11:27:15.810",
"Id": "2759",
"ParentId": "2734",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "2759",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T13:32:23.167",
"Id": "2734",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Code Concision - String Capitalization"
}
|
2734
|
<p>I have this "pretty" date string generator in C# - pass it a date and it returns a string with "5 minutes ago" or "2 weeks, 3 days ago", etc.</p>
<p>It's a little verbose and hogs 61 lines, and I'm wondering if I'm missing out on some nice C# features or something. What (if any) is the best way to clean up this code? Are there any cool c# features I can use here?</p>
<pre><code>public static string getTimeSpan(DateTime postDate)
{
string stringy = "";
TimeSpan diff = DateTime.Now.Subtract(postDate);
double years = Math.Floor(diff.TotalDays / 365);
double weeks = Math.Floor(diff.TotalDays / 7);
double days = diff.Days;
double hours = diff.Hours + days * 24;
double minutes = diff.Minutes + hours * 60;
if (minutes <= 1) {
stringy = "Just Now";
} else if (years >= 1) {
if (years >= 2) {
stringy = years.ToString() + " years ago";
} else {
stringy = "1 year ago";
}
} else if (weeks >= 1) {
if ((days - weeks * 7) > 0) {
if ((days - weeks * 7) > 1) {
stringy = ", " + (days - weeks * 7).ToString() + " days";
} else {
stringy = ", " + (days - weeks * 7).ToString() + " day";
}
}
if (weeks >= 2) {
stringy = weeks.ToString() + " weeks" + stringy + " ago";
} else {
stringy = "1 week" + stringy + " ago";
}
} else if (days >= 1) {
if ((hours - days * 24) > 0) {
if ((hours - days * 24) > 1) {
stringy = ", " + (hours - days * 24).ToString() + " hours";
} else {
stringy = ", " + (hours - days * 24).ToString() + " hour";
}
}
if (days >= 2) {
stringy = days.ToString() + " days" + stringy + " ago";
} else {
stringy = "1 day" + stringy + " ago";
}
} else if (hours >= 1) {
if ((minutes - hours * 60) > 0) {
if ((minutes - hours * 60) > 1) {
stringy = ", " + (minutes - hours * 60).ToString() + " minutes";
} else {
stringy = ", " + (minutes - hours * 60).ToString() + " minute";
}
}
if (hours >= 2) {
stringy = hours.ToString() + " hours" + stringy + " ago";
} else {
stringy = "1 hour" + stringy + " ago";
}
} else if (minutes > 1) {
stringy = minutes.ToString() + " minutes ago";
}
return stringy;
}
</code></pre>
|
[] |
[
{
"body": "<p>Some things are repeated:</p>\n\n<pre><code>days - weeks * 7\nhours - days * 24\nminutes - hours * 60\n</code></pre>\n\n<p>These can and should be made into their own variables - but what you are really after seems to be </p>\n\n<pre><code>days % 7\nhours % 24\nminutes % 60\n</code></pre>\n\n<p>You can replace:</p>\n\n<pre><code>double hours = diff.Hours + days * 24;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>double hours = diff.TotalHours;\n</code></pre>\n\n<p>There is also a TotalMinutes. You can just use the Math.Floor() of these values to get an int.</p>\n\n<p>I see that you are going for a single exit point for this function, but I think that readability would be improved if you got some of the simpler paths shorter:</p>\n\n<pre><code>if (minutes <= 1) \n return \"Just Now\"; \n\nif (years >= 1) { \n if (years >= 2) {\n return years.ToString() + \" years ago\"; \n } else {\n return \"1 year ago\";\n }\n</code></pre>\n\n<p>EDIT to add:</p>\n\n<p>There's a repeated block of code that could be refactored to its own function:</p>\n\n<pre><code>if ((days - weeks * 7) > 0) {\n if ((days - weeks * 7) > 1) {\n stringy = \", \" + (days - weeks * 7).ToString() + \" days\"; \n } else {\n stringy = \", \" + (days - weeks * 7).ToString() + \" day\";\n }\n}\nif (weeks >= 2) {\n stringy = weeks.ToString() + \" weeks\" + stringy + \" ago\";\n} else {\n stringy = \"1 week\" + stringy + \" ago\";\n}\n</code></pre>\n\n<p>The body of the extracted function would look like:</p>\n\n<pre><code>if (smallUnitCount > 0) {\n if (smallUnitCount > 1) {\n stringy = String.Format(\", {0} {1}\", smallUnitCount.ToString() , smallUnitPluralName); \n } else {\n stringy = String.Format(\", {0} {1}\", smallUnitCount.ToString() , smallUnitSingularName);\n }\n}\nif (largeUnitCount >= 2) {\n stringy = String.Format(\"{0} {1}{2} ago\", largeUnitCount.ToString, largeUnitPluralName, stringy);\n} else {\n stringy = String.Format(\"{0} {1}{2} ago\", largeUnitCount.ToString, largeUnitSingularName, stringy);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T19:49:20.397",
"Id": "2745",
"ParentId": "2738",
"Score": "6"
}
},
{
"body": "<ol>\n<li>Use PascalCase for the method name</li>\n<li>Move the calc for years and months lower to be minutely \"more efficient\"</li>\n<li>Use inline <code>return</code> to reduces nesting</li>\n<li>Use ternary operator (<code>?:</code>) for simple logic to reduce <code>if/else</code> clutter</li>\n<li>Use the <code>format</code> override of <code>ToString(string format)</code> to reduce string concats</li>\n<li>Use <code>string.Format</code> with a ternary to reduce duplication</li>\n</ol>\n\n<p>The shorter version I came up with is 40 lines, but you can judge if it readable enough.</p>\n\n<pre><code> public static string GetTimeSpan(DateTime postDate) {\n string stringy = string.Empty;\n TimeSpan diff = DateTime.Now.Subtract(postDate);\n double days = diff.Days;\n double hours = diff.Hours + days*24;\n double minutes = diff.Minutes + hours*60;\n if (minutes <= 1) {\n return \"Just Now\";\n }\n double years = Math.Floor(diff.TotalDays/365);\n if (years >= 1) {\n return string.Format(\"{0} year{1} ago\", years, years >= 2 ? \"s\" : null);\n }\n double weeks = Math.Floor(diff.TotalDays/7);\n if (weeks >= 1) {\n double partOfWeek = days - weeks*7;\n if (partOfWeek > 0) {\n stringy = string.Format(\", {0} day{1}\", partOfWeek, partOfWeek > 1 ? \"s\" : null);\n }\n return string.Format(\"{0} week{1}{2} ago\", weeks, weeks >= 2 ? \"s\" : null, stringy);\n }\n if (days >= 1) {\n double partOfDay = hours - days*24;\n if (partOfDay > 0) {\n stringy = string.Format(\", {0} hour{1}\", partOfDay, partOfDay > 1 ? \"s\" : null);\n }\n return string.Format(\"{0} day{1}{2} ago\", days, days >= 2 ? \"s\" : null, stringy);\n }\n if (hours >= 1) {\n double partOfHour = minutes - hours*60;\n if (partOfHour > 0) {\n stringy = string.Format(\", {0} minute{1}\", partOfHour, partOfHour > 1 ? \"s\" : null);\n }\n return string.Format(\"{0} hour{1}{2} ago\", hours, hours >= 2 ? \"s\" : null, stringy);\n }\n\n // Only condition left is minutes > 1\n return minutes.ToString(\"# minutes ago\");\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T20:46:23.233",
"Id": "4261",
"Score": "0",
"body": "wow thanks! I didn't even know about half these operators and methods and such!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T22:05:39.543",
"Id": "4267",
"Score": "0",
"body": "It is important to remove last `return` in such cases so compiler will verify that all cases are checked and handled and there is no scenario when this method will return initial value which is `string.Empty`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T22:30:27.680",
"Id": "4269",
"Score": "0",
"body": "Updated the last line to be more explicit with the final return."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-15T19:03:33.730",
"Id": "191710",
"Score": "0",
"body": "How about future dates? :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T14:41:41.823",
"Id": "416498",
"Score": "1",
"body": "The last line should be `return string.Format(\"{0} minutes ago\", minutes);` as `minutes.ToString(\"{0} minutes ago\")` will return `{xxx} minutes ago`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:24:31.807",
"Id": "416661",
"Score": "0",
"body": "@monoblaine You are right, the code was incorrect. I have edited it to use `#` instead of `{0}`. See it in action: https://dotnetfiddle.net/gxNsxU"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:29:51.413",
"Id": "416662",
"Score": "1",
"body": "Can reduce a bit of boilerplate using string interpolation instead of `string.Format`"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-05-31T20:37:40.867",
"Id": "2746",
"ParentId": "2738",
"Score": "11"
}
},
{
"body": "<p>I would use casting <code>double</code> to <code>int</code> instead of <code>Floor</code> in your case. Firstly because I'm a little bit cautious about equality comparison of doubles in <code>years >= 1</code>. I would write it in this way: </p>\n\n<pre><code>int years = (int)(diff.TotalDays/365);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T21:35:44.237",
"Id": "4263",
"Score": "0",
"body": "would doing so accomplish the same as Floor? that is, would casting .8 to an int return 0? Because that's important (i don't want .8 to round to 1 and have the function say that it's been a year when it's only really been 80% of a year)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T21:48:31.800",
"Id": "4265",
"Score": "1",
"body": "Yep, with positive doubles casting to `int` does `Floor` exactly. See **Explicit conversion** section [here](http://msdn.microsoft.com/en-us/library/ms173105.aspx). It has exactly your sample."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T21:30:52.927",
"Id": "2748",
"ParentId": "2738",
"Score": "4"
}
},
{
"body": "<p>You can make it an extension, so you can do</p>\n\n<pre><code>string result = DateTime.Now.GetTimeSpan();\n</code></pre>\n\n<p>Here is how I did it a few time ago </p>\n\n<pre><code> /// <summary>\n /// Provide extentions for the DateTime Object.\n /// </summary>\n public static class DateTimeExtensions\n {\n /// <summary>\n /// Gets the relative time for a datetime.\n /// </summary>\n /// <param name=\"dateTime\">The datetime to get the relative time.</param>\n /// <returns>A relative time in english.</returns>\n public static string GetTimeSpan(this DateTime dateTime)\n {\n TimeSpan diff = DateTime.Now.Subtract(dateTime);\n\n if (diff.TotalMinutes < 1)\n {\n return string.Format(\"{0:D2} second{1} ago\", diff.Seconds, PluralizeIfNeeded(diff.Seconds));\n }\n\n if (diff.TotalHours < 1)\n {\n return string.Format(\"{0:D2} minute{1} ago\", diff.Minutes, PluralizeIfNeeded(diff.Minutes));\n }\n\n if (diff.TotalDays < 1)\n {\n return string.Format(\"{0:D2} hour{2} and {1:D2} minute{3} ago\", diff.Hours, diff.Minutes, PluralizeIfNeeded(diff.Hours), PluralizeIfNeeded(diff.Minutes));\n }\n\n if (diff.TotalDays <= 2)\n {\n return string.Format(\n \"{0:D2} day{3}, {1:D2} hour{4} and {2:D2} minute{5} ago\",\n diff.Days,\n diff.Hours,\n diff.Minutes,\n PluralizeIfNeeded(diff.Days),\n PluralizeIfNeeded(diff.Hours),\n PluralizeIfNeeded(diff.Minutes));\n }\n\n if (diff.TotalDays <= 30)\n {\n return string.Format(\"{0:D2} days ago\", diff.TotalDays);\n }\n\n return string.Format(\"{0:g}\", dateTime);\n }\n\n /// <summary>\n /// Gets a 's' if value is > 1.\n /// </summary>\n /// <param name=\"testValue\">The value to test.</param>\n /// <returns>An 's' if value is > 1, otherwise an empty string.</returns>\n private static string PluralizeIfNeeded(int testValue)\n {\n return testValue > 1 ? \"s\" : string.Empty;\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T09:48:01.473",
"Id": "2758",
"ParentId": "2738",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "2746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T16:51:57.523",
"Id": "2738",
"Score": "9",
"Tags": [
"c#",
"datetime"
],
"Title": "\"Pretty\" date generator"
}
|
2738
|
<p>I have a loop structure, that I really don't like. It's the initialisation I find appalingly ugly. Is there a nicer way to do the following?</p>
<pre><code>Queue<Integer> queue = getMyQueue();
Integer element = queue.poll();
while (element != null){
calculate_smart_stuff(element);
element = queue.poll();
}
</code></pre>
<p>A for loop is slightly better, but still has the ugly repetition of the assignment of element in the initialiser and the 'incrementer' I also prefer my for loops to be really easy, and only to be reserved for counting and adding (or substracting in corner cases) 1, as this is how I expect a for loop to behave.</p>
<pre><code>Queue<Integer> queue = getMyQueue();
for (Integer element = queue.poll(); element != null; element = queue.poll()){
calculate_smart_stuff(element);
}
</code></pre>
<p>Or should I just keep checking the size before assignment like so?</p>
<pre><code>Queue<Integer> queue = getMyQueue();
while (queue.size() > 0){
Integer element = queue.poll();
calculate_smart_stuff(element);
}
</code></pre>
<p>What I don't like about this is that I have to check the size every time before getting an element, which itself has a clear indication that the queue was empty.</p>
<p>Are there any better constructs I can use here, or am I just being picky with the last two options?</p>
|
[] |
[
{
"body": "<p>Can you not do:</p>\n\n<pre><code>while ((element = queue.poll) != null) {\n..\n} \n</code></pre>\n\n<p>?</p>\n\n<p>It requires more knowledge of the language but that might be a trade-off you like.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T20:26:37.687",
"Id": "4258",
"Score": "0",
"body": "yes, that works, and was about what I was looking for"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T20:47:30.500",
"Id": "4262",
"Score": "0",
"body": "Just a shame that in the while statement, I can't do the declaration like in the for example, but it helps"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T19:45:05.477",
"Id": "2744",
"ParentId": "2741",
"Score": "8"
}
},
{
"body": "<p>It would be better to do </p>\n\n<pre><code>for (Integer element; (element = queue.poll) != null;){\n\n}\n</code></pre>\n\n<p>Because you don't want element to be in the scope after the loop has ended</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T21:38:27.280",
"Id": "4264",
"Score": "0",
"body": "Definitely better than my for attempt for the for loop. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T21:17:40.330",
"Id": "2747",
"ParentId": "2741",
"Score": "13"
}
},
{
"body": "<p>Since java.util.Queue is iterable...</p>\n\n<pre><code>for (int i : queue)\n{\n System.out.println (\"\" + i);\n}\n</code></pre>\n\n<p>Simplified for-Loop, introduced about 2005. </p>\n\n<p>In the comments, the question is raised, what to do with PriorityQueue, which doesn't give guarantees about its iterator. Well - unfortunately, we can't just write:</p>\n\n<pre><code>for (int i : Arrays.sort (pq.toArray ()))\n</code></pre>\n\n<p>because Arrays.sort sorts an Array in place, and doesn't return it. So we have to construct the Array beforehand, </p>\n\n<pre><code>public void test () \n{\n Queue <Integer> queue = new PriorityQueue <Integer> ();\n queue.offer (4);\n queue.offer (41);\n queue.offer (44);\n queue.offer (14);\n\n for (int i : queue)\n {\n System.out.println (\"\" + i);\n }\n\n out.println (\"-------------\");\n\n Integer [] arr = queue.toArray (new Integer [queue.size ()]);\n Arrays.sort (arr);\n for (int i : arr)\n {\n System.out.println (\"\" + i);\n }\n}\n</code></pre>\n\n<p>That is, of course, more boilerplate than in the question. While I ask myself, why an iterator in a PriorityQueue doesn't guarantee an order, and would suggest to do otherwise, if you write your own Queues where you can overwrite 'iterator', where you're interested in the order of iteration, I don't have a suggestion for the trivial case. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T04:49:23.340",
"Id": "4284",
"Score": "1",
"body": "-1 if I could: This is OK sometimes, but: in a `PriorityQueue` this won't give you the right ordering, in a `BlockingQueue` it won't block correctly, and if the queue changes inside the loop (which is actually a pretty common thing to do if the queue is used for BFS), it will throw an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T14:17:47.673",
"Id": "4287",
"Score": "0",
"body": "And above examples are better in that regard?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T18:04:00.013",
"Id": "4301",
"Score": "0",
"body": "poll() removes the head of the queue, the for constuct uses an iterator. The iterator gives no guarantees for order: `Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).` (from http://download.oracle.com/javase/1,5.0/docs/api/java/util/Collection.html#iterator() )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T18:57:38.033",
"Id": "4303",
"Score": "0",
"body": "Yes, using `poll()` functions properly in all cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T11:18:11.883",
"Id": "4309",
"Score": "0",
"body": "I agree with you that it is counter-intuitive, and quite a cotcha, that the `Iterator` on the `Queue` interface doesn't guarantee any specific order. The reason is probably to allow more flexibility on the backend. The `PriorityQueue` in `java.util` is backed by a priorityheap, and I'm not sure how easy (or possible) it is to implement an in-order iterator on it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T03:01:59.723",
"Id": "2754",
"ParentId": "2741",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "2747",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T18:19:38.077",
"Id": "2741",
"Score": "8",
"Tags": [
"java",
"queue"
],
"Title": "fix ugly initialisation in while loop over queue"
}
|
2741
|
<p>I would like to improve this function to reduce the run time and optimize it.</p>
<pre><code>function [Pl,Plm] = funlegendre(gamma)
Plm = zeros(70,71);
Pl = zeros(70,1);
P0 = 1;
Pl(1) = gamma;
Plm(1,1) = sqrt(1-gamma^2);
for L=2:70
for M=0:L
if(M==0)
if (L==2)
Pl(L) = ((2*L-1)*gamma*Pl(L-1)-(L-1)*P0)/L;
else
Pl(l) = ((2*l-1)*gamma*Pl(l-1)-(l-1)*Pl(l-2))/l;
end
elseif(M<L)
if(L==2)
if(M==1)
Plm(L,M) = (2*L-1)*Plm(1,1)*Pl(L-1);
else
Plm(L,M) = (2*M-1)*Plm(1,1)*Plm(L-1,m-1);
end
else
if(M==1)
Plm(L,M) = Plm(L-2,m) + (2*L-1)*Plm(1,1)*Pl(L-1);
else
Plm(L,m) = Plm(L-2,m) + (2*L-1)*Plm(1,1)*Plm(L-1,M-1);
end
end
elseif(M==L)
Plm(L,M) = (2*L-1)*Plm(1,1)*Plm(L-1,L-1);
else
Plm(L,M) = 0;
end
end
end
Pl = sparse(Pl);
Plm = sparse(Plm);
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-03T16:38:10.650",
"Id": "7689",
"Score": "0",
"body": "Have you considered turning this into a mex function? That will significantly reduce run time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-24T18:26:40.723",
"Id": "8438",
"Score": "0",
"body": "@Elpezmuerto: Thank you very much for your suggestion."
}
] |
[
{
"body": "<p>At first glance I can see a few points where you can start to optimize your polynom generation.\nFirst thing I would refactor is the \"heavy\" use of conditional cases. There are only two well defined situation in which M==0 or M==L. Therefore you could extract both cases and implement them within the outer loop. If you don't care for code duplication copy/paste the functionality but if you care you have to write another function to call, which might be slow again. After you extracted the two special cases you cann ommit the remaining condition when you let L begin at 1 and run till L-1. Another point of optimization is to precompute values like 2*L-1 in the outer loop to have them \"cached\" for further access. As I'm not sure if sparse matrices are computationally faster than full matrices I'm not sure if I should recommend to use them from the beginning and not to convert the results into sparse matrices. Now I would try to vectorize as many operations as possible and let highly optimized code do the job for you.\nAnd at last step @Elpezmuerto is fully right try to turn it into a mex function. This will precompile the function and speed up the execution time even further.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:07:03.703",
"Id": "13564",
"ParentId": "2743",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13564",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T19:14:06.863",
"Id": "2743",
"Score": "3",
"Tags": [
"optimization",
"matlab"
],
"Title": "Legendre's polynomials and functions"
}
|
2743
|
<p>I need to classify each line as "announce, whisper or chat" once I have that sorted out I need to extract certain values to be processed.</p>
<p>Right now my regex is as follow:</p>
<pre><code>var regex = new Regex(@"^\[(\d{2}:\d{2}:\d{2})\]\s*(?:(\[System Message\])?\s*<([^>]*)>|((.+) Whisper You :))\s*(.*)$");
</code></pre>
<ul>
<li>Group 0 is the entire message.</li>
<li>Group 1 is the hour time of when the message was sent.</li>
<li>Group 2 is wether it was an announce or chat.</li>
<li>Group 3 is who sent the announce.</li>
<li>Group 4 is if it was a whisper or not.</li>
<li>Group 5 is who sent the whisper.</li>
<li>Group 6 is the sent message by the user or system.</li>
</ul>
<p>Classify each line:</p>
<pre><code>if 4 matches
means it is a whisper
else if 2 matches
means it is an announce
else
normal chat
</code></pre>
<p><strong>Should I change anything to my regex to make it more precise/accurate on the matches ?</strong></p>
<p>Sample data:</p>
<pre><code>[02:33:03] John Whisper You : Heya
[02:33:03] John Whisper You : How is it going
[02:33:12] <John> [02:33:16] [System Message] bla bla
[02:33:39] <John> heya
[02:33:40] <John> hello :S
[02:33:57] <John> hi
[02:33:57] [System Message] <John> has left the room
[02:33:57] [System Message] <John> has entered the room
</code></pre>
|
[] |
[
{
"body": "<p>You can always break it down in multiple lines to make it more readable. You can also use named groups which take the \"magic\" out of the group numbers (4 == whisper, 3 == normal, etc).</p>\n\n<pre><code> var regex = new Regex(@\"^\\[(?<TimeStamp>\\d{2}:\\d{2}:\\d{2})\\]\\s*\" +\n @\"(?:\" +\n @\"(?<SysMessage>\\[System Message\\])?\\s*\" +\n @\"<(?<NormalWho>[^>]*)>|\" +\n @\"(?<Whisper>(?<WhisperWho>.+) Whisper You :))\\s*\" +\n @\"(?<Message>.*)$\");\n\n string data = @\"[02:33:03] John Whisper You : Heya\n[02:33:03] John Whisper You : How is it going\n[02:33:12] <John> [02:33:16] [System Message] bla bla\n[02:33:39] <John> heya\n[02:33:40] <John> hello :S\n[02:33:57] <John> hi\n[02:33:57] [System Message] <John> has left the room \n[02:33:57] [System Message] <John> has entered the room\";\n\n foreach (var msg in data.Split(new char[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries))\n {\n Match match = regex.Match(msg);\n if (match.Success)\n {\n if (match.Groups[\"Whisper\"].Success)\n {\n Console.WriteLine(\"[whis from {0}]: {1}\", match.Groups[\"WhisperWho\"].Value, msg);\n }\n else if (match.Groups[\"SysMessage\"].Success)\n {\n Console.WriteLine(\"[sys msg]: {0}\", msg);\n }\n else\n {\n Console.WriteLine(\"[normal from {0}]: {1}\", match.Groups[\"NormalWho\"].Value, msg);\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T23:49:11.570",
"Id": "4270",
"Score": "0",
"body": "that is pretty cool dude thanks I was looking for a way to actually split each pattern I wanted like that but was not aware of how to do it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T23:47:35.860",
"Id": "2750",
"ParentId": "2749",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2750",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T22:27:38.257",
"Id": "2749",
"Score": "4",
"Tags": [
"c#",
"parsing",
"regex"
],
"Title": "Using Regex to parse a chat transcript"
}
|
2749
|
<p>Last weekend I was writing a short PHP function that accepts a starting move and returns valid knight squares for that move.</p>
<pre><code><?php
/* get's starting move and returns valid knight moves */
echo GetValidKnightSquares('e4');
function GetValidKnightSquares($strStartingMove) {
$cb_rows = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8);
$valids = array(array(-1, -2), array(-2, -1), array(-2, 1), array(-1, 2), array(1, 2), array(2, 1), array(2, -1), array(1, -2));
$row = substr($strStartingMove, 0, 1);
$col = substr($strStartingMove, 1, 1);
$current_row = $cb_rows[$row];
if(!in_array($current_row, $cb_rows)) {
die("Hey, use chars from a to h only!");
}
$current_col = $col;
if($current_col > 8) {
die("Hey, use numbers from 1 to 8 only!");
}
$valid_moves = '';
foreach ($valids as $valid) {
$new_valid_row = $current_row + $valid[0];
$new_valid_col = $current_col + $valid[1];
if(($new_valid_row <= 8 && $new_valid_row > 0) && ($new_valid_col <= 8 && $new_valid_col > 0)) {
$row_char = array_search($new_valid_row, $cb_rows);
$valid_moves .= $row_char . "$new_valid_col ";
}
}
return "Valid knight moves for knight on $strStartingMove are: $valid_moves";
}
?>
</code></pre>
<p>Could you please take a look at it and share your thoughts about it? The code can also be found <a href="http://pastebin.com/8tnpe1dN" rel="noreferrer">here</a>.</p>
<hr>
<p>I was kinda 'criticized' about the code. One guy said it's <em>messy, too long and not 'clever' enough</em>. So I needed second opinion on it, a code review if you like. I think there is a place for improvement (always), but for me this was the first time I've coded something related with Chess. I've found something like this that caught my attention:</p>
<pre><code>if ((abs(newX-currentX)==1 and abs(newY-currentY)==2) or (abs(newX-currentX)==2 and abs(newY-currentY)==1)) {
/* VALID MOVE FOR A KNIGHT */
}
else {
/* INVALID MOVE FOR A KNIGHT */
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:06:49.400",
"Id": "4271",
"Score": "0",
"body": "what is the question? :O"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:07:43.730",
"Id": "4272",
"Score": "0",
"body": "Erm, what's the *actual* problem you get ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:08:27.323",
"Id": "4273",
"Score": "0",
"body": "Whats the question? It's passed my quick read/obvious error test. Does it work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:10:14.887",
"Id": "4274",
"Score": "1",
"body": "\"Share our thoughts\"? my thought is that it should work, what else were you looking for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:10:33.757",
"Id": "4275",
"Score": "0",
"body": "This can certainly be restructured more nicely. Short tip: instead of `substr` use `$row = $strStartingMove[0];` and `$col = $strStartingMove[1];` or better yet pass the coordinates around as array and/or integers only."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:21:13.040",
"Id": "4276",
"Score": "0",
"body": "Looks nice. Does php have lambda expressions and things like zip, filter and map? Then you could do something like start = \"D2\"; print map (lambda (x, y): \"%s%d\" % (chr (ord ('A') + x), y + 1), filter (lambda (x, y): x in range (8) and y in range (8), map (lambda (x, y): (x [0] + y [0], x[1] + y [1] ), zip ( [ (2, 1), (2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2), (-2, 1), (-2, -1) ], [ (ord (start [0] ) - ord ('A'), int (start [1] ) - 1 ) ] * 8) ) ) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T16:52:30.570",
"Id": "4292",
"Score": "0",
"body": "That is a nice way to handle it, better than both of our solutions;)"
}
] |
[
{
"body": "<p>what about this? </p>\n\n<pre><code>function GetValidKnightSquares($strStartingMove){\n $rowvals='abcdefgh';\n $row_assoc=array_flip(str_split($rowvals));\n $row = $strStartingMove[0]-1;\n if(!strstr($rowvals,$row)){\n die('invalid row');\n }\n $col = $strStartingMove[1];\n if($col<1 || $col>7){\n die('invalid column');\n }\n $srow=$row_assoc[$row];\n $valid_moves=array(\n $row_assoc[$srow+2].$col+1,\n $row_assoc[$srow+2].$col-1,\n $row_assoc[$srow-2].$col+1,\n $row_assoc[$srow-2].$col-1,\n $row_assoc[$srow+1].$col+2,\n $row_assoc[$srow+1].$col-2,\n $row_assoc[$srow-1].$col+2,\n $row_assoc[$srow-1].$col-2,\n );\n return \"Valid knight moves for knight on $strStartingMove are: \".implode(', ',$valid_moves);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:28:21.053",
"Id": "4277",
"Score": "0",
"body": "This one doesn't check the board borders. Also you could make it even shorter by setting up two nested for loops to change the signs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:31:24.810",
"Id": "4278",
"Score": "0",
"body": "shorter != faster, but yes I didn't check for borders, if he wrote the other code, he should be able to figure out where that goes;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:34:48.510",
"Id": "4279",
"Score": "0",
"body": "Well we don't know whether he's going for easily maintainable code or fast code. Also the performance difference is going to be insignificant here unless he's doing calling that function thousands of times in a row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:38:53.240",
"Id": "4280",
"Score": "0",
"body": "I always worry about overhead beacuse I generally run large multi-user sites an web apps.... do you have any useful criticism?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:56:02.907",
"Id": "4281",
"Score": "0",
"body": "Nothing besides the fact that seeing a programmer do something the program should be doing (like generate 8 lines of almost identical code, or map letters to numbers in alphabetical order) is usually a bad sign."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T01:06:11.213",
"Id": "4282",
"Score": "0",
"body": "ok, there ya go, that's my update...if you can do it better, teach us something and be constructive."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:15:06.793",
"Id": "2752",
"ParentId": "2751",
"Score": "1"
}
},
{
"body": "<p>Another way:</p>\n\n<pre><code>function GetValidKnightSquares($strStartingMove){\n $row_letters = array_combine(range(1,8),range('a','h'));\n $row_numbers = array_flip($row_letters);\n $row = $row_numbers[$strStartingMove[0]];\n $col = $strStartingMove[1];\n\n $valid_moves = array();\n foreach( array( 1=>2, 2=>1 ) as $r=>$c )\n foreach( array( -1, 1 ) as $r_sign )\n foreach( array( -1, 1 ) as $c_sign )\n $valid_moves[] = $row_letters[$row + $r * $r_sign].($col + $c * $c_sign);\n\n // This line from trey's code is actually pretty neat.\n return \"Valid knight moves for knight on $strStartingMove are: \".implode(', ',$valid_moves);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T01:31:00.087",
"Id": "2753",
"ParentId": "2751",
"Score": "1"
}
},
{
"body": "<p>First of all, a function called <code>GetValidKnightSquares</code> shouldn't be translating chessboard locations. Any code that performs a distinct operation and can be named should be extracted into its own function. It makes everything much easier to read and understand. <strong>Name things.</strong></p>\n\n<p>Second, I would probably leverage whatever data structure you choose for your board to determine the valid moves on that board. The structure I'm going to choose looks like this:</p>\n\n<pre><code>-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \n-1, \"8a\", \"8b\", \"8c\", \"8d\", \"8e\", \"8f\", \"8g\", \"8h\", -1, \n-1, \"7a\", \"7b\", \"7c\", \"7d\", \"7e\", \"7f\", \"7g\", \"7h\", -1, \n-1, \"6a\", \"6b\", \"6c\", \"6d\", \"6e\", \"6f\", \"6g\", \"6h\", -1, \n-1, \"5a\", \"5b\", \"5c\", \"5d\", \"5e\", \"5f\", \"5g\", \"5h\", -1, \n-1, \"4a\", \"4b\", \"4c\", \"4d\", \"4e\", \"4f\", \"4g\", \"4h\", -1, \n-1, \"3a\", \"3b\", \"3c\", \"3d\", \"3e\", \"3f\", \"3g\", \"3h\", -1, \n-1, \"2a\", \"2b\", \"2c\", \"2d\", \"2e\", \"2f\", \"2g\", \"2h\", -1, \n-1, \"1a\", \"1b\", \"1c\", \"1d\", \"1e\", \"1f\", \"1g\", \"1h\", -1, \n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1\n</code></pre>\n\n<p>It's a one-dimensional array that represents the ranks and files of the two-dimensional board. The negative ones are there to pad the board and make it easier to detect when a piece has moved out of play. (We'll see this later.) This type of data structure is called a <a href=\"http://chessprogramming.wikispaces.com/10x12+Board\" rel=\"nofollow\">Mailbox</a> (because <a href=\"http://en.wikipedia.org/wiki/Robert_Hyatt\" rel=\"nofollow\">some old-timer thought it looked like one</a>, I guess) and it's very common in chess programming.</p>\n\n<p>Here's how to generate it:</p>\n\n<pre><code>// converts an index in the mailbox into its corresponding value in algebraic notation\nfunction i2an($i) {\n $files = \"abcdefgh\";\n return 10 - floor($i / 10) . $files[($i % 10) - 1];\n}\n\nfunction generateEmptyBoard() {\n $row = array();\n for($i = 0; $i < 120; $i++) {\n $row[] = ($i < 20 || $i > 100 || !($i % 10) || $i % 10 == 9)\n ? -1\n : i2an($i);\n }\n return $row;\n}\n</code></pre>\n\n<p>This gives us the array we saw above. All that's left is to use it:</p>\n\n<pre><code>function knightMoves($square, $board) {\n $i = an2i($square);\n $moves = array();\n foreach(array(8, -8, 12, -12, 19, -19, 21, -21) as $offset) {\n $move = $board[$i + $offset];\n if ($move != -1) {\n $moves[] = $move;\n }\n }\n return $moves;\n}\n\n// converts a position in algebraic notation into its location in the mailbox\nfunction an2i($square) {\n return (10 - $square[0]) * 10 + strpos(\"abcdefgh\", $square[1]) + 1;\n}\n</code></pre>\n\n<p>Notice that the mailbox's borders make it very easy to tell when we've moved to a position off the board. </p>\n\n<p>Here are some examples:</p>\n\n<pre><code>$board = generateEmptyBoard();\nprint_r(knightMoves(\"1h\", $board));\nprint_r(knightMoves(\"5b\", $board));\nprint_r(knightMoves(\"6c\", $board));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>$ php knights.php\nArray\n(\n [0] => 2f\n [1] => 3g\n)\nArray\n(\n [0] => 6d\n [1] => 4d\n [2] => 3a\n [3] => 7c\n [4] => 3c\n [5] => 7a\n)\nArray\n(\n [0] => 5a\n [1] => 7e\n [2] => 5e\n [3] => 7a\n [4] => 4b\n [5] => 8d\n [6] => 4d\n [7] => 8b\n)\n</code></pre>\n\n<p>What's cool is that you can use this mailbox throughout your entire application by substituting some representation of actual pieces for the location names in the inner elements. It's useful for more than just your narrow problem, in other words.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T06:06:02.270",
"Id": "64411",
"Score": "0",
"body": "Note: I should have used notation like \"a8\" instead of \"8a\" of course. That should be a trivial fix left to anyone who finds this in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:17:55.820",
"Id": "37710",
"ParentId": "2751",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T00:04:54.980",
"Id": "2751",
"Score": "4",
"Tags": [
"php"
],
"Title": "Need help with valid knight moves in Chess"
}
|
2751
|
<p>Can this code be improved? I'm avoiding using the QueryString collection because the query string may contain eg: <code>OrderBy=Column1&OrderBy=Column2</code> and it didn't seem helpful to start with those switched into QueryString["OrderBy"]=="Column1,Column2";</p>
<pre><code> var query = "";
if (urlHelper.RequestContext.HttpContext.Request.Url != null)
{
query = urlHelper.RequestContext.HttpContext.Request.Url.Query.TrimStart('?');
if (query.Length > 0)
{
var kvp =
query.Split('&').Select(x => x.Split('='))
.Select(x => new { Key = x[0], Value = (x.Length > 0) ? x[1] : ""})
.Where(x => x.Key != "page")
.ToList();
kvp.Add(new { Key = "page", Value = number.ToString() });
query = String.Join("&", kvp.Select(x => x.Key + "=" + x.Value).ToArray());
}
else query = String.Format("page={0}", number);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T16:39:15.880",
"Id": "4291",
"Score": "0",
"body": "Why do you think it won't be helpful to switch to `QueryString[\"OrderBy\"]==\"Column1,Column2\"`. It seems to be more regular structure than several parameters with the same name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T17:18:48.020",
"Id": "4293",
"Score": "0",
"body": "The original query string comes from form data. MVC binds the multiple \"OrderBy\" as an IEnumerable<string>. If I convert the QueryString collection into a RouteValuesDictionary to recycle the query string the IEnumerable only has one value, and it breaks the view as a result. I guess it *would* be a valid suggestion to have the controller handle both cases gracefully."
}
] |
[
{
"body": "<p>I think that yes this code can be improved.</p>\n\n<p>use a regular expression:</p>\n\n<pre><code> var newQuery = Regex.Replace(currentQuery, @\"(?i)(page=\\d*&?)\", \"\").TrimEnd('&');\n if (newQuery.Length > 0)\n newQuery += string.Format(\"&Page={0}\", currentPageNo);\n else\n newQuery = string.Format(\"Page={0}\", currentPageNo);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-17T15:46:00.100",
"Id": "2996",
"ParentId": "2762",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2996",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T15:18:50.920",
"Id": "2762",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc-2"
],
"Title": "Adding or Replacing a Page item in a QueryString in C#."
}
|
2762
|
<p>How can I write the following T-SQL query part in a shorter way without using <a href="http://www.sqlteam.com/article/introduction-to-dynamic-sql-part-1" rel="nofollow">dynamic SQL</a>?</p>
<pre><code>WHERE
( (@Max IS NULL OR @Type <> 'Products')
OR (@Max IS NOT NULL AND @Type = 'Products'
AND ProductCount > @Max ) )
AND ( (@Min IS NULL OR @Type <> 'Products')
OR (@Min IS NOT NULL AND @Type = 'Products'
AND ProductCount < @Min ) )
AND ( (@Max IS NULL OR @Type <> 'Vendors')
OR (@Max IS NOT NULL AND @Type = 'Vendors'
AND VendorCount > @Max ) )
AND ( (@Min IS NULL OR @Type <> 'Vendors' )
OR (@Min IS NOT NULL AND @Type = 'Vendors'
AND VendorCount < @Min ) )
AND ( (@Max IS NULL OR @Type <> 'Order')
OR (@Max IS NOT NULL AND @Type = 'Order'
AND OrderCount > @Max ) )
AND ( (@Min IS NULL OR @Type <> 'Order')
OR (@Min IS NOT NULL AND @Type = 'Order'
AND OrderCount < @Min ) )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T06:13:35.507",
"Id": "4295",
"Score": "3",
"body": "By \"shorter\", do you mean \"shorter\" in terms of text length, or in terms of efficiency? The first really doesn't matter-long queries can be efficient and short ones inefficient. Is the query running poorly for you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T06:15:53.203",
"Id": "4296",
"Score": "0",
"body": "@Todd No performance issue with current query, i just want make it \"shorter\" in terms of text length"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T06:28:19.790",
"Id": "4297",
"Score": "0",
"body": "maybe because you are not using it? it's definition is for posting code for peer review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T07:37:55.067",
"Id": "4298",
"Score": "0",
"body": "Maybe your question will inspire some people to visit the site slightly more often, and some others to come up with further interesting questions. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T15:03:03.273",
"Id": "103026",
"Score": "1",
"body": "What is the purpose of the Query? What does the rest of the query look like?"
}
] |
[
{
"body": "<p>You will have to test this carefully, but the following query should work:</p>\n\n<pre><code>WHERE \n( \n @Max IS NULL \n OR @Type = 'Products' AND ProductCount > @Max\n OR @Type = 'Vendors' AND VendorCount > @Max\n OR @Type = 'Order' AND OrderCount > @Max\n)\nAND\n(\n @Min IS NULL\n OR @Type = 'Products' AND ProductCount < @Min\n OR @Type = 'Vendors' AND VendorCount < @Min\n OR @Type = 'Order' AND OrderCount < @Min\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T06:15:18.563",
"Id": "2764",
"ParentId": "2763",
"Score": "7"
}
},
{
"body": "<p>Something like this</p>\n\n<p>You can rely on the <code>NULL</code> comparison to always give false (strictly: <em>unknown</em>) if <code>@Max</code> or <code>@Min</code> is <code>NULL</code> for the relevant <code>CASE</code></p>\n\n<pre><code>WHERE\n CASE @Type\n WHEN 'Products' THEN ProductCount \n WHEN 'Vendors' THEN VendorCount \n WHEN 'Order' THEN OrderCount \n END > @Max\n OR\n CASE @Type\n WHEN 'Products' THEN ProductCount \n WHEN 'Vendors' THEN VendorCount \n WHEN 'Order' THEN OrderCount \n END < @Min\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T08:21:11.500",
"Id": "4299",
"Score": "2",
"body": "Pedant's corner: the NULL comparison gives UNKNOWN, not FALSE. putting a `NOT` in front of it will still exclude those rows."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T08:23:22.830",
"Id": "4300",
"Score": "1",
"body": "@Damien_The_Unbeliever: yes, yes, I thought about that. But didn't want to deprive anyone of their fun ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-06-01T07:30:10.327",
"Id": "2765",
"ParentId": "2763",
"Score": "7"
}
},
{
"body": "<p>Here's another stab at it, based on gbn's <code>CASE</code> idea, but using <code>BETWEEN</code> to avoid repeating the cases:</p>\n\n<pre><code>WHERE\n CASE @Type\n WHEN 'Products' THEN ProductCount\n WHEN 'Vendors' THEN VendorCount\n WHEN 'Orders' THEN OrderCount\n END BETWEEN IFNULL(@Min,0) AND IFNULL(@Max,99999999)\n</code></pre>\n\n<p>Note: <code>IFNULL</code> in MySQL should be replaced by <code>ISNULL</code> in TSQL</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-11T16:48:55.030",
"Id": "2916",
"ParentId": "2763",
"Score": "4"
}
},
{
"body": "<p>I am just going to step through this so that it is a little easier to understand for someone happening upon this question in the future.</p>\n\n<p>This is what we are starting with</p>\n\n<blockquote>\n<pre><code>WHERE\n ( (@Max IS NULL OR @Type <> 'Products')\n OR (@Max IS NOT NULL AND @Type = 'Products'\n AND ProductCount > @Max ) )\n\n AND ( (@Min IS NULL OR @Type <> 'Products')\n OR (@Min IS NOT NULL AND @Type = 'Products'\n AND ProductCount < @Min ) )\n\n AND ( (@Max IS NULL OR @Type <> 'Vendors')\n OR (@Max IS NOT NULL AND @Type = 'Vendors'\n AND VendorCount > @Max ) )\n\n AND ( (@Min IS NULL OR @Type <> 'Vendors' )\n OR (@Min IS NOT NULL AND @Type = 'Vendors'\n AND VendorCount < @Min ) )\n\n AND ( (@Max IS NULL OR @Type <> 'Order')\n OR (@Max IS NOT NULL AND @Type = 'Order'\n AND OrderCount > @Max ) )\n\n AND ( (@Min IS NULL OR @Type <> 'Order')\n OR (@Min IS NOT NULL AND @Type = 'Order'\n AND OrderCount < @Min ) )\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>I am going to first take out all the <code><></code> conditions because we are already checking in the or statements for <code>@Type = {type}</code> and I am going to take out the check for <code>@Max IS NOT NULL</code> because if it were <code>NULL</code> we wouldn't hit that condition anyway.</p>\n\n<pre><code>WHERE\n ( @Max IS NULL\n OR (@Type = 'Products'\n AND ProductCount > @Max ) )\n\n AND ( @Min IS NULL \n OR (@Type = 'Products'\n AND ProductCount < @Min ) )\n\n AND ( @Max IS NULL\n OR (@Type = 'Vendors'\n AND VendorCount > @Max ) )\n\n AND ( @Min IS NULL \n OR (@Type = 'Vendors'\n AND VendorCount < @Min ) )\n\n AND ( @Max IS NULL\n OR (@Type = 'Order'\n AND OrderCount > @Max ) )\n\n AND ( @Min IS NULL\n OR (@Type = 'Order'\n AND OrderCount < @Min ) )\n</code></pre>\n\n<p>Way cleaner already.</p>\n\n<p>now we have <code>@Max IS NULL</code> and <code>@Min IS NULL</code> checks that we could combine so we aren't repeating ourselves.</p>\n\n<pre><code>WHERE\n(\n @Max IS NULL \n OR\n (@Type = 'Products' AND ProductCount > @Max)\n OR \n (@Type = 'Vendor' AND VendorCount > @Max)\n OR\n (@Type = 'Order' AND OrderCount > @Max)\n)\nAND\n(\n @Min IS NULL\n OR\n (@Type = 'Products' AND ProductCount < @Min)\n OR \n (@Type = 'Vendor' AND VendorCount < @Min)\n OR\n (@Type = 'Order' AND OrderCount < @Min)\n)\n</code></pre>\n\n<p>This is the Final Solution that @Peter Lang came to. I use Parenthesis to make sure that the where clause is being interpreted by the RDBMS the way that I want them interpreted, if they aren't interpreted the way I think they will be it can lead to weird results that sometimes are hard to spot.</p>\n\n<p>Always double check your returned data to make sure you are getting what you want. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T15:08:13.107",
"Id": "57582",
"ParentId": "2763",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "2764",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T06:07:49.150",
"Id": "2763",
"Score": "5",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Reduce the code in a WHERE clause without using dynamic SQL"
}
|
2763
|
<p><a href="http://www.microsoft.com/sqlserver" rel="nofollow">Microsoft's SQL Server</a> is a suite of relational database management system (RDBMS) products providing multi-user database access functionality. It originated from Sybase SQL Server 4.x codebase and Transact-SQL dialect (T-SQL), but forked significantly since then.</p>
<p>SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into <em>editions</em> to distinguish between product functionality.</p>
<p>The SQL Server product range is split broadly into 4 categories:</p>
<ol>
<li><p><strong>SQL Server</strong> main suite of enterprise and developer server products. Primary differences are licencing costs, capacities, and components included in the product, with some minor differences supported language features. Standard components include db language and storage server, developer tools, ETL tools, schedulers, replication. Other components include OLAP, reporting, parallel compute. Components runs as NT Services.</p></li>
<li><p><strong>SQL Server Express</strong> free for use and distribution but reduced engine performance, functionality and capacity than found it's other server siblings. Focused on small deployments. Runs as an NT Service.</p></li>
<li><p><strong>SQL Server Compact</strong> an embeddable subset of SQL Server. Like Express edition is has reduced language, functionality and capacity, but is free to distribute. It's focused on small installations and desktop applications where it's small footprint and no-management-required features are a great advantage.</p></li>
<li><p><strong>SQL Azure</strong> completely managed, hosted, high-availability instance of SQL Server 2005 with some language syntax support federated query, operated in <a href="http://www.microsoft.com/windowsazure/" rel="nofollow">Microsoft Azure</a> datacenters.</p></li>
</ol>
<p><strong>References</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms130214.aspx" rel="nofollow">MSDN SQL Server Transact-SQL Reference</a></li>
<li><a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow">SQL Server Wikipedia Article</a></li>
<li><a href="http://stackoverflow.com/tags/sql-azure/info">[sql-azure] Stack Overflow Tag</a></li>
<li><a href="http://stackoverflow.com/tags/sql-server/info">[sql-server] Stack Overflow Tag</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T18:08:57.643",
"Id": "2766",
"Score": "0",
"Tags": null,
"Title": null
}
|
2766
|
Microsoft's SQL Server is a relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases. It originated from the Sybase SQL Server codebase, which is why both products use the extension of SQL called Transact-SQL (T-SQL).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T18:08:57.643",
"Id": "2767",
"Score": "0",
"Tags": null,
"Title": null
}
|
2767
|
<pre><code>Email<input type="text" id="email" /><br />
Re-enter Email<input type="text" id="confirm-email" />
</code></pre>
<p>I'm thinking that I want a model so that I can have this partial page strongly typed. But what a lame model....</p>
<p>It would look like this, and if this is a good Idea, what should I name this model?</p>
<pre><code>public class ConfirmEmailModel?????
{
[Required]
[Display(Name = "Email",ResourceType=typeof(mvc3test.Resources.Common))]
public string Email{ get; set; }
[Display(Name = "Confirm Email")]
[Compare("Email", ErrorMessage = "no match.")]
public string ConfirmEmail{ get; set; }
}
</code></pre>
|
[] |
[
{
"body": "<p>call it a \"view model\" as its not really a model, its just a model for the view you are showing.</p>\n\n<p>ConfirmEmailViewModel :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T03:20:48.260",
"Id": "2776",
"ParentId": "2768",
"Score": "4"
}
},
{
"body": "<p>I like to take an MVVM style approach to MVC, for example, I use:</p>\n\n<pre><code>public class Person { }\n</code></pre>\n\n<p>as my domain model, and</p>\n\n<pre><code>public class PersonViewModel { }\n</code></pre>\n\n<p>as my view model. The view model is expressly used with the Controller and View. I also tend to use a mapping framework quite a lot, so I might mock up something like</p>\n\n<pre><code>public PersonController(IViewModelService<PersonViewModel> viewModelService)\n{\n _viewModelService = viewModelService;\n}\n\npublic ViewResult Edit(int id) \n{\n PersonViewModel model = _viewModelService.Get(id);\n return View(model);\n}\n\n[HttpPost]\npublic ViewResult Edit(PersonViewModel model)\n{\n if (ModelState.Valid)\n {\n _viewModelService.Update(model);\n }\n\n return View(model);\n}\n</code></pre>\n\n<p>where the <code>IViewModelService<PersonViewModel></code> service is responsible for mapping my view model back to my domain model <code>Person</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T14:27:28.200",
"Id": "2784",
"ParentId": "2768",
"Score": "0"
}
},
{
"body": "<p>No I don't believe it is overkill. I've felt the same about view models for simple things in the past but it adds bits which are helpful, such as strongly typing and validation.</p>\n\n<p>As Keith, I'd also call it ConfirmEmailViewModel.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-05T15:11:29.273",
"Id": "6558",
"ParentId": "2768",
"Score": "1"
}
},
{
"body": "<p>I don't know ASP.NET, but isn't this the job of a <em>view helper</em>? Or an \"HTML Helper\" as they put it.</p>\n\n<blockquote>\n <p>An HTML Helper is just a method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML and tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.</p>\n</blockquote>\n\n<p>I say don't create a \"view model,\" instead create a view <em>helper</em>. </p>\n\n<p>That is straight from: <a href=\"http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs\" rel=\"nofollow\">http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-05T19:27:34.600",
"Id": "6559",
"ParentId": "2768",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T19:22:08.910",
"Id": "2768",
"Score": "4",
"Tags": [
"c#",
"mvc",
"email",
"asp.net-mvc-3"
],
"Title": "Email confirmation model"
}
|
2768
|
<p><strong>Windows Presentation Foundation</strong> (WPF, previously known as “Avalon”) is part of the Microsoft <a href="/questions/tagged/.net" class="post-tag" title="show questions tagged '.net'" rel="tag">.net</a> <a href="/questions/tagged/framework" class="post-tag" title="show questions tagged 'framework'" rel="tag">framework</a> (version 3.0 onwards) used to create rich client user experiences for Windows applications. It features a diverse set of controls, layout options, 2D and 3D graphics, and media and text handling, and enables data binding and style-driven templates.</p>
<p>It uses a combination of <a href="/questions/tagged/xaml" class="post-tag" title="show questions tagged 'xaml'" rel="tag">xaml</a>, an <a href="/questions/tagged/xml" class="post-tag" title="show questions tagged 'xml'" rel="tag">xml</a>-based markup language, and any of the <a href="http://en.wikipedia.org/wiki/Common_Language_Runtime" rel="nofollow">Common Language Runtime languages</a> to define user interface elements. A fundamental aspect of WPF is to separate the user interface definition from the business logic which enables developers and designers to work concurrently on a single project much more easily. WPF also moves UI rendering off to the video hardware through the use of <a href="https://en.wikipedia.org/wiki/DirectX" rel="nofollow">DirectX</a>. Doing so allows computers to utilize their GPU, which frees the CPU to handle more of the logic-oriented tasks.</p>
<p>WPF runtime libraries are included in all versions of <a href="/questions/tagged/windows" class="post-tag" title="show questions tagged 'windows'" rel="tag">windows</a> since Windows Vista and Windows Server 2008.</p>
<p>To learn more, visit <a href="http://windowsclient.net" rel="nofollow">WindowsClient.NET</a>. See also the <a href="http://en.wikipedia.org/wiki/Windows_Presentation_Foundation" rel="nofollow">Wikipedia entry on WPF</a> and the <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx" rel="nofollow">WPF portal on MSDN</a>.</p>
<p>WPF employs <a href="/questions/tagged/xaml" class="post-tag" title="show questions tagged 'xaml'" rel="tag">xaml</a> to define and link various UI elements. WPF applications can also be deployed as standalone desktop programs or hosted as an embedded object in a website. WPF aims to unify a number of common user interface elements, such as 2D/3D rendering, fixed and adaptive documents, typography, vector graphics, runtime animation, and pre-rendered media. These elements can then be linked and manipulated based on various events, user interactions, and data bindings.</p>
<p>Microsoft has released five major WPF versions: WPF 3.0 (Nov 2006), WPF 3.5 (Nov 2007), WPF 3.5sp1 (Aug 2008), WPF 4 (April 2010), and WPF 4.5 (August 2012).</p>
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://www.kaxaml.com/" rel="nofollow">KAXAML</a> - Open source XAML Editor</li>
<li><a href="http://snoopwpf.codeplex.com/" rel="nofollow">Snoop</a> - UI Inspection Tool</li>
<li><a href="http://wpfinspector.codeplex.com/" rel="nofollow">WPF Inspector</a> - UI Inspection Tool</li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa969767.aspx" rel="nofollow">WPF Performance Suite</a> - Performance Profiling Tools for WPF</li>
<li><a href="http://stackoverflow.com/questions/9591/what-wpf-books-would-you-recommend">Recommended books</a></li>
<li><a href="http://www.amazon.co.uk/Windows-Presentation-Foundation-Unleashed-WPF/dp/0672328917" rel="nofollow">WPF Unleashed</a></li>
</ul>
<p><strong>Visual Studio Extensions for WPF Controls</strong></p>
<ul>
<li><a href="http://www.telerik.com/products/wpf/overview.aspx" rel="nofollow">Telerik UI for WPF</a></li>
<li><a href="https://www.devexpress.com/Products/NET/Controls/WPF/" rel="nofollow">DevExpress WPF Controls</a></li>
<li><a href="http://www.infragistics.com/products/wpf" rel="nofollow">Infragistics WPF Сontrols</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T20:39:50.917",
"Id": "2770",
"Score": "0",
"Tags": null,
"Title": null
}
|
2770
|
Windows Presentation Foundation (WPF) is part of the Microsoft .NET framework used to create rich client user experiences for Windows application.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T20:39:50.917",
"Id": "2771",
"Score": "0",
"Tags": null,
"Title": null
}
|
2771
|
<p>I have a T4 Templates project that generates methods to "convert" one Type (class, struct, enum) from a source Assembly its corresponding Type in another. The two types have the identical names and property names, just different namespaces and different types. This may be a re-invented a wheel. Nonetheless, I didn't find any solutions out there immediately, and it felt like a good programming exercise anyway. I'm also not familiar with dynamic languages and though it would be a worthwhile application of the dynamic (<a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx" rel="nofollow">System.Dynamic.DynamicObject</a>) keyword.</p>
<p>This following is the .tt file which writes out all the "convert" methods, but most of the work is done in a static class with numerous helper extension methods.</p>
<pre><code><#@ template language="C#" inherits="CommonT4.BaseTemplate" #>
<#@ Import Namespace="CommonT4" #>
<#@ Import Namespace="System.Collections.Generic" #>
<#@ Import Namespace="System.Text" #>
<#@ Import Namespace="System.Linq" #>
<#@ Import Namespace="System.IO" #>
<#@ Import Namespace="System.Reflection" #>
namespace <#= Namespace #>
{
public static class ConvertExtension
{
<#
//will this work for ValueType (enum, struct)?
foreach (var typeTuple in this.GetConvertTypeMappings(this.SrcAssembly, this.DestAssembly))
{
Type destType = typeTuple.Item2;
Type srcType = typeTuple.Item1;
#>
public static <#=destType.ToGenericTypeFullNameString()#> Convert(this <#=srcType.ToGenericTypeFullNameString() #> src0)
{
dynamic dest0;
dynamic <#=HelperExtensionT4.DynamicVariableNameDeclarationsString(1, MAX_LVL) #>
<#
HelperExtensionT4.WriteConvertType(this, destType, srcType);
#>
return dest0;
}
<#
}
#>
}
}
<#+
public string Namespace;
public static int MAX_LVL = 16;
#>
</code></pre>
<p>Notice the first line in every generated convert method will declare a series of dynamic variables, most of which will be reused. The reason I used dynamic keywords was so I could reuse the same variable names, even if the types assigned to those variables change later. This would make this T4 template function "WriteConvertType" easier to finish writing, in my opinion. To clarify, the dynamic keyword is not used anywhere within this helper method - the dynamic keyword will show up in the generated code with all the conversion methods. At the end of the question I'll post a snippet of what the generated code looks like, since it is lengthy.
This is the helper class where a recursive extension method "WriteConvertType" is defined. </p>
<pre><code>public static void WriteConvertType(BaseTemplate template, Type destType, Type srcType, Stack<Type> stack = null)
{
if (stack == null)
stack = new Stack<Type>();
if (srcType.IsNullableType())
{
template.WriteLine("dest{0} = new {1}(default({2}));", stack.Count, destType.ToGenericTypeFullNameString(), destType.GetGenericArguments()[0].ToGenericTypeFullNameString());
return;
}
else
template.WriteLine("dest{0} = new {1}();", stack.Count, destType.ToGenericTypeFullNameString());
var commonProperties = from tuple in template.GetCommonConvertProperties(destType, srcType)
select new { desttype = tuple.Item1, srctype = tuple.Item2, Name = tuple.Item3 };
foreach (var common in commonProperties)
{
Type srcElementType;
Type mappedType;
if (common.desttype == common.srctype || template.IsTypeMapped(common.desttype, out mappedType))//base case: would-be return;
template.WriteLine("dest{0}.{1} = src{2}.{3};", stack.Count, common.Name, stack.Count, common.Name);
else if (common.srctype.isGenericEnumerableType(out srcElementType))
{
//get matching generic argument/element Type from dest. Assembly or mscorlib:
Type destElementType = (from dtype in template.DestAssembly.GetTypes().Union(mscorlib.GetTypes())
where dtype.Name == srcElementType.Name
select dtype).First();
template.WriteLine("if (src{0}.{1} != null) {{", stack.Count, common.Name);
template.PushIndent(" ");
template.WriteLine("dest{0}.{1} = new {2}();"
, stack.Count
, common.Name
, common.desttype.ToGenericTypeFullNameString());
//caller checks stack:
if (!stack.Contains(common.desttype))
{
template.WriteLine("for (int i{0} = 0; i{0} < src{0}.{1}.Count; i{0}++)"
, stack.Count
, common.Name);
template.WriteLine("{");
template.PushIndent(" ");
template.WriteLine("src{0} = src{1}.{2}[i{1}];", stack.Count + 1, stack.Count, common.Name);
stack.Push(destElementType);
WriteConvertType(template, destElementType, srcElementType, stack);//, lvl + 1);
stack.Pop();
template.WriteLine("dest{0}.{1}.Add(dest{2});", stack.Count, common.Name, stack.Count + 1);
template.PopIndent();
template.WriteLine("}");//end for
}
template.PopIndent();
template.WriteLine("}");//end if
}
else
{
if (!stack.Contains(common.desttype))
{
template.WriteLine("src{0} = src{1}.{2};", stack.Count + 1, stack.Count, common.Name);//if property type not equal (and not IEnumerable)
template.WriteLine("if (src{0} is {1}) {{", stack.Count + 1, common.srctype.ToGenericTypeFullNameString());//if src != null
template.PushIndent(" ");//CurrentIndent += 1;
stack.Push(common.desttype);
WriteConvertType(template, common.desttype, common.srctype, stack);// lvl + 1);
stack.Pop();
template.WriteLine("dest{0}.{1} = dest{2};", stack.Count, common.Name, stack.Count + 1);//finally, set the property upon return
template.PopIndent();
template.WriteLine("}");
}
}
}
return;
}
</code></pre>
<p>Would this be considered excessive use or not an ideal situation for use of the C# dynamic keyword? Does this incur a noticeable performance penalty? Are there any guidelines or patterns/practices for the DLR?</p>
<p>Also, is "Convert" a good title for the method? The purpose of this method does seem to be a convert operation, although it's not really a cast. The purpose will be eventually to marshal the source type that's not serializable by the WCF DataContractSerializer to a destination type that <em>will</em> serialize.</p>
<p>Thanks for reading. I put the source code for this here:
<a href="http://wcfsilverlighthelper.codeplex.com/" rel="nofollow">http://wcfsilverlighthelper.codeplex.com/</a></p>
<p>Finally, here is an example of one of the generated methods.</p>
<pre><code>public static Northwind.SL.Model.Product Convert(this Northwind.NET.Model.Product src0)
{
dynamic dest0;
dynamic src1, dest1, src2, dest2, src3, dest3, src4, dest4, src5, dest5, src6, dest6, src7, dest7, src8, dest8, src9, dest9, src10, dest10, src11, dest11, src12, dest12, src13, dest13, src14, dest14, src15, dest15, src16, dest16;
dest0 = new Northwind.SL.Model.Product();
dest0.ID = src0.ID;
src1 = src0.PermissionType;
if (src1 is System.Nullable<Northwind.NET.Security.PermissionTypeEnum>)
{
dest1 = new System.Nullable<Northwind.SL.Security.PermissionTypeEnum>(default(Northwind.SL.Security.PermissionTypeEnum));
dest0.PermissionType = dest1;
}
src1 = src0.SecureName;
if (src1 is Northwind.NET.Security.SecureString)
{
dest1 = new Northwind.SL.Security.SecureString();
src2 = src1.SecurityHandle;
if (src2 is Northwind.NET.Security.SecurityHandle)
{
dest2 = new Northwind.SL.Security.SecurityHandle();
dest2.Domain = src2.Domain;
dest1.SecurityHandle = dest2;
}
dest1.Value = src1.Value;
dest0.SecureName = dest1;
}
dest0.Name = src0.Name;
src1 = src0.SecurityHandle;
if (src1 is Northwind.NET.Security.SecurityHandle)
{
dest1 = new Northwind.SL.Security.SecurityHandle();
dest1.Domain = src1.Domain;
dest0.SecurityHandle = dest1;
}
dest0.SupplierID = src0.SupplierID;
dest0.CategoryID = src0.CategoryID;
dest0.QuantityPerUnit = src0.QuantityPerUnit;
dest0.UnitPrice = src0.UnitPrice;
dest0.UnitsInStock = src0.UnitsInStock;
dest0.UnitsOnOrder = src0.UnitsOnOrder;
dest0.ReorderLevel = src0.ReorderLevel;
dest0.Discontinued = src0.Discontinued;
dest0.RowTimeStamps = src0.RowTimeStamps;
src1 = src0.Supplier;
if (src1 is Northwind.NET.Model.Supplier)
{
dest1 = new Northwind.SL.Model.Supplier();
dest1.ID = src1.ID;
dest1.Name = src1.Name;
src2 = src1.SecureName;
if (src2 is Northwind.NET.Security.SecureString)
{
dest2 = new Northwind.SL.Security.SecureString();
src3 = src2.SecurityHandle;
if (src3 is Northwind.NET.Security.SecurityHandle)
{
dest3 = new Northwind.SL.Security.SecurityHandle();
dest3.Domain = src3.Domain;
dest2.SecurityHandle = dest3;
}
dest2.Value = src2.Value;
dest1.SecureName = dest2;
}
src2 = src1.PermissionType;
if (src2 is System.Nullable<Northwind.NET.Security.PermissionTypeEnum>)
{
dest2 = new System.Nullable<Northwind.SL.Security.PermissionTypeEnum>(default(Northwind.SL.Security.PermissionTypeEnum));
dest1.PermissionType = dest2;
}
dest1.ContactName = src1.ContactName;
dest1.ContactTitle = src1.ContactTitle;
dest1.Address = src1.Address;
dest1.City = src1.City;
dest1.Region = src1.Region;
dest1.PostalCode = src1.PostalCode;
dest1.Country = src1.Country;
dest1.Phone = src1.Phone;
dest1.Fax = src1.Fax;
dest1.HomePage = src1.HomePage;
dest1.RowTimeStamps = src1.RowTimeStamps;
if (src1.Products != null)
{
dest1.Products = new System.Collections.Generic.List<Northwind.SL.Model.Product>();
for (int i1 = 0; i1 < src1.Products.Count; i1++)
{
src2 = src1.Products[i1];
dest2 = new Northwind.SL.Model.Product();
dest2.ID = src2.ID;
src3 = src2.PermissionType;
if (src3 is System.Nullable<Northwind.NET.Security.PermissionTypeEnum>)
{
dest3 = new System.Nullable<Northwind.SL.Security.PermissionTypeEnum>(default(Northwind.SL.Security.PermissionTypeEnum));
dest2.PermissionType = dest3;
}
src3 = src2.SecureName;
if (src3 is Northwind.NET.Security.SecureString)
{
dest3 = new Northwind.SL.Security.SecureString();
src4 = src3.SecurityHandle;
if (src4 is Northwind.NET.Security.SecurityHandle)
{
dest4 = new Northwind.SL.Security.SecurityHandle();
dest4.Domain = src4.Domain;
dest3.SecurityHandle = dest4;
}
dest3.Value = src3.Value;
dest2.SecureName = dest3;
}
dest2.Name = src2.Name;
src3 = src2.SecurityHandle;
if (src3 is Northwind.NET.Security.SecurityHandle)
{
dest3 = new Northwind.SL.Security.SecurityHandle();
dest3.Domain = src3.Domain;
dest2.SecurityHandle = dest3;
}
dest2.SupplierID = src2.SupplierID;
dest2.CategoryID = src2.CategoryID;
dest2.QuantityPerUnit = src2.QuantityPerUnit;
dest2.UnitPrice = src2.UnitPrice;
dest2.UnitsInStock = src2.UnitsInStock;
dest2.UnitsOnOrder = src2.UnitsOnOrder;
dest2.ReorderLevel = src2.ReorderLevel;
dest2.Discontinued = src2.Discontinued;
dest2.RowTimeStamps = src2.RowTimeStamps;
dest1.Products.Add(dest2);
}
}
dest0.Supplier = dest1;
}
return dest0;
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't think is either \"Fair use\" nor \"Abuse\" of dynamic; I think for your purpose, dynamic may be \"Misused\". </p>\n\n<p>If all you want to accomplish is to map \"two types have the identical names and property names, just different namespaces and different types\", then you should probably use a mapper class with a function method that maps the types. </p>\n\n<pre><code>public static class ObjectMapper\n{\n private static readonly Dictionary<Tuple<Type, Type>, object> Maps\n = new Dictionary<Tuple<Type, Type>, object>();\n\n /// <summary>\n /// <para>Add a new map</para>\n /// </summary>\n /// <typeparam name=\"TFrom\">From Type</typeparam>\n /// <typeparam name=\"TTo\">To Type</typeparam>\n /// <param name=\"map\">Mapping delegate</param>\n public static void AddMap<TFrom, TTo>(Action<TFrom, TTo> map)\n where TFrom : class\n where TTo : class\n {\n Maps.Add(Tuple.Create(typeof(TFrom), typeof(TTo)), map);\n }\n\n /// <summary>\n /// <para>Map object data to another object</para>\n /// </summary>\n /// <typeparam name=\"TFrom\">From type</typeparam>\n /// <typeparam name=\"TTo\">To type</typeparam>\n /// <param name=\"from\">From object</param>\n /// <param name=\"to\">To object</param>\n public static void Map<TFrom, TTo>(TFrom from, TTo to)\n {\n var key = Tuple.Create(typeof(TFrom), typeof(TTo));\n var message = string.Format(\"No map defined for {0} => {1}\", typeof(TFrom).Name, typeof(TTo).Name);\n\n if (!Maps.ContainsKey(key))\n throw new Exception(message);\n\n var map = (Action<TFrom, TTo>)Maps[key];\n\n if (map == null)\n throw new Exception(message);\n\n map(from, to);\n }\n}\n</code></pre>\n\n<p>Alternatively, if you want to do something really generic to map a TInput instance to a TOutput instance without needing to write a specific mapper function for them, you can use reflection to create an extension method of object called CastTo like so: </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class TypeHelper\n{\n public static TDestType CastTo<TDestType>(this object myType) where TDestType : new()\n {\n List<MemberInfo> tOrigMembers = myType.GetType().FindMembers(MemberTypes.Property | MemberTypes.Field,\n BindingFlags.GetProperty |\n BindingFlags.SetProperty |\n BindingFlags.SetField |\n BindingFlags.GetField |\n BindingFlags.Public |\n BindingFlags.NonPublic |\n BindingFlags.Instance,\n null, null).ToList();\n List<MemberInfo> tDestMembers = typeof (TDestType).FindMembers(MemberTypes.Property | MemberTypes.Field,\n BindingFlags.SetProperty |\n BindingFlags.SetField |\n BindingFlags.GetField |\n BindingFlags.Public |\n BindingFlags.NonPublic |\n BindingFlags.Instance,\n null, null).ToList();\n var destTypeInstance = new TDestType();\n foreach (MemberInfo m in tOrigMembers)\n {\n object value = (m is PropertyInfo)\n ? ((PropertyInfo) m).GetValue(myType, null)\n : ((FieldInfo) m).GetValue(myType);\n object enumValue;\n MemberInfo thisMember = FindMemberMatch(m.Name, value, tDestMembers, out enumValue);\n if (thisMember == null)\n continue;\n\n if (thisMember is PropertyInfo)\n {\n var pInfo = (PropertyInfo) thisMember;\n pInfo.SetValue(destTypeInstance, pInfo.PropertyType.IsEnum ? enumValue : value, null);\n continue;\n }\n if (thisMember is FieldInfo)\n {\n var fInfo = (FieldInfo) thisMember;\n fInfo.SetValue(destTypeInstance, fInfo.FieldType.IsEnum ? enumValue : value);\n continue;\n }\n }\n return destTypeInstance;\n }\n\n private static MemberInfo FindMemberMatch(string name, object value, IEnumerable<MemberInfo> members,\n out object enumValue)\n {\n enumValue = null;\n Type valueType = value == null ? typeof (object) : value.GetType();\n foreach (MemberInfo memberInfo in members)\n {\n if (memberInfo.Name != name)\n continue;\n if (memberInfo is FieldInfo)\n {\n var fieldInfo = (FieldInfo) memberInfo;\n if (fieldInfo.FieldType == valueType && fieldInfo.FieldType.IsAssignableFrom(valueType))\n return fieldInfo;\n if (fieldInfo.FieldType.IsEnum && value != null &&\n EnumIsAssignableFromValue(fieldInfo.FieldType, value))\n {\n enumValue = Enum.Parse(fieldInfo.FieldType, value.ToString(), true);\n return fieldInfo;\n }\n continue;\n }\n if (memberInfo is PropertyInfo)\n {\n var propertyInfo = (PropertyInfo) memberInfo;\n if (propertyInfo.PropertyType == valueType && propertyInfo.PropertyType.IsAssignableFrom(valueType))\n return propertyInfo;\n if (propertyInfo.PropertyType.IsEnum && value != null &&\n EnumIsAssignableFromValue(propertyInfo.PropertyType, value))\n {\n enumValue = Enum.Parse(propertyInfo.PropertyType, value.ToString(), true);\n return propertyInfo;\n }\n continue;\n }\n }\n return null;\n }\n\n private static bool EnumIsAssignableFromValue(Type enumType, object value)\n {\n return Enum.GetNames(enumType).Contains(value.ToString()) ||\n Enum.GetValues(enumType).OfType<object>().Contains(value);\n }\n} \n</code></pre>\n\n<p>To use it you would do </p>\n\n<pre><code>var myObjectOfTypeA = myObjectOfTypeB.CastTo<TypeA>();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T14:20:33.673",
"Id": "4311",
"Score": "1",
"body": "Or as another alternative, you can make use of something like AutoMapper which has been designed from the ground up to do this very thing...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T14:53:51.583",
"Id": "4313",
"Score": "1",
"body": "I didn't know about the AutoMapper. After looking at http://automapper.codeplex.com I'm in love. It even supports flattening! Thanks for the tip."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T06:56:52.367",
"Id": "2779",
"ParentId": "2772",
"Score": "1"
}
},
{
"body": "<p>With AutoMapper (<a href=\"http://automapper.codeplex.com\" rel=\"nofollow\">automapper.codeplex.com</a>), your complete code could be flattened down to:</p>\n\n<pre><code>using SLProduct = Northwind.SL.Model.Product;\nusing NetProduct = Northwind.NET.Model.Product;\n\n//\n\nSLProduct slProduct = Mapper.Map<NetProduct, SLProduct>(nlProduct);\n</code></pre>\n\n<p>As you've said that the types use the same property types and names, you won't need to customise a mapping profile.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T17:48:59.070",
"Id": "2788",
"ParentId": "2772",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T21:44:36.503",
"Id": "2772",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Fair use or Abuse of the dynamic (System.Dynamic.DynamicObject)?"
}
|
2772
|
<p>I'm going through the CoffeeScript book by Trevor Burnham, and I was curious as to what the best style is for a function I was writing.</p>
<p>In the book the author writes the function like so:</p>
<blockquote>
<pre><code>strToCoordinates = (input) ->
halves = input.split(',')
if halves.length is 2
x = parseFloat halves[0]
y = parseFloat halves[1]
if !isInteger(x) or !isInteger(y)
console.log "Each coordinate must be an integer."
else if not inRange x - 1, y - 1
console.log "Each coordinate must be between 1 and #{GRID_SIZE}."
else
{x, y}
else
console.log 'Input must be of the form `x, y`.'
</code></pre>
</blockquote>
<p>I wrote my function like so:</p>
<pre><code>strToCoordinates = (input) ->
halves = input.split(',')
if halves.length isnt 2
console.log 'Please enter coordinates in format: x,y'; return
[x, y] = (parseFloat s for s in halves)
unless isInteger(x) and isInteger(y)
console.log 'The coordinates must be integers.'; return
if not inRange(x, y)
console.log "Coordinates must be between 1 and #{GRID_SIZE}."; return
{x, y}
</code></pre>
<p>Is my use of just <code>if</code> statements and using <code>return</code> to stop the flow if the check fails an okay style?</p>
<p>I like the fact that with this style the error messages are right after the check unlike with <code>if/else</code>, and also you don't have to have large sections indented.</p>
|
[] |
[
{
"body": "<p>Well I don't now coffeescript, but guess I can read it anyway :D</p>\n\n<p>I think both are good and readable.<br>\nI don't know if you can add empty lines to the code. If you can:</p>\n\n<pre><code>strToCoordinates = (input) ->\n halves = input.split(',')\n if halves.length isnt 2\n console.log 'Please enter coordinates in format: x,y'; \n return\n\n [x, y] = (parseFloat s for s in halves)\n unless isInteger(x) and isInteger(y)\n console.log 'The coordinates must be integers.'; \n return\n\n if not inRange(x, y)\n console.log \"Coordinates must be between 1 and #{GRID_SIZE}.\"; \n return\n\n {x, y}\n</code></pre>\n\n<p>But this really is a minor arguable tweak (some will like it, some don't, I do).<br>\nAnother point would be the \"overuse\" of returns. Functions are easier to read, if they do have lss return-statements. But Again, this usually applies to larger functions only.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T10:08:32.133",
"Id": "2781",
"ParentId": "2773",
"Score": "4"
}
},
{
"body": "<p>I would agree with the author's style just because it's not the absolute case. </p>\n\n<p>If the author wants to build on the example and introduce more cases like a Z coordinate it's an else if statement, but your function you would have to have another inner if statement to handle there being three coordinates. </p>\n\n<pre><code> if isnt 2 and 3 \n ...\n if 2 \n ...\n elseif 3\n</code></pre>\n\n<p>In this example you wouldn't be adding to it anyway since it's an excerise, but if it's code you want to use in a project then there's no telling what new requirements you might add in. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T12:33:57.637",
"Id": "2782",
"ParentId": "2773",
"Score": "1"
}
},
{
"body": "<p>I don't really like hiding the returns off the end of the line, so putting them on separate lines (or reverting to the original) would be preferable.</p>\n\n<p>However, I'd also consider actually using postfix if. This would make the code read like this</p>\n\n<pre><code>strToCoordinates = (input) ->\n halves = input.split(',')\n return console.log 'Please enter coordinates in format: [x,y]' if halves.length isnt 2\n [x, y] = (parseFloat s for s in halves)\n return console.log 'The coordinates must be integers.' unless isInteger(x) and isInteger(y)\n return console.log \"Coordinates must be between 1 and #{GRID_SIZE}.\" unless inRange(x, y)\n {x, y}\n</code></pre>\n\n<p>Under certain circumstances, postfix if can be buried at the end of the line. The presence of code straight after a return draws the eye to the conditions in this case. This would be my favoured way of writing the function as not only is it concise, it would be very easy to extend to extra conditions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T02:23:33.750",
"Id": "70298",
"Score": "0",
"body": "Don't you think one will need to read the whole console.log message before seeing the condition. It's a pre-condition, hiding if at the end of a line makes it hard to see. Also, isn't it a bit weird to have 3 return statement in a row followed by a statement without the return keyword? Having the possibility of making one liners doesn't mean you have to use them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T21:36:35.693",
"Id": "86091",
"Score": "0",
"body": "I'd say the very sequence of returns makes it obvious to the reader that postfix ifs are in play. Think of it a different way: under what circumstances do you think postfix if should be used? Nearly every circumstance is harder to spot than putting a return at the front."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T17:16:53.630",
"Id": "86210",
"Score": "0",
"body": "Do you really need postfix ifs at all ? Lines should be short so that you don't have to move your eyes from left to right. Think of it another way, if you need to search for the ifs statements they should probably be somewhere else. Somewhere you don't need to search for them. Look this answer and tell me if it reads well http://codereview.stackexchange.com/a/2781/27048. You can clearly see all the paths, the ifs and the returns. Plus I don't need to move my eyes from left to right."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-09T08:41:38.520",
"Id": "3360",
"ParentId": "2773",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-01T23:02:32.150",
"Id": "2773",
"Score": "4",
"Tags": [
"converting",
"coffeescript"
],
"Title": "Converting a string to coordinates"
}
|
2773
|
<p>I've never done anything like this before so I'd like someone else to look at this before I get too carried away :)</p>
<p>Am I making this more complicated than it needs to be? I'm trying to make it EASY for other modules/scripts on this system to store and retrieve their settings. Hence why I trap the <code>ConfigParser.NoOptionError</code> error and return <code>None</code> and create the section if it doesn't exist in the <code>set()</code> method.</p>
<p>Suggestions?</p>
<pre><code>import ConfigParser
import os
from ast import literal_eval as Eval
class _ConfParse(ConfigParser.ConfigParser):
def __init__(self, confpath, conffile):
ConfigParser.ConfigParser.__init__(self)
self.conf_file = os.path.join(confpath, conffile)
try: self.readfp(open(self.conf_file), 'r')
except IOError as Err:
if Err.errno == 2: pass
else: raise Err
def set(self, section, option, value):
if self.has_section(section):
ConfigParser.ConfigParser.set(self, section, option, str(value))
else:
self.add_section(section)
ConfigParser.ConfigParser.set(self, section, option, str(value))
def get(self, section, option):
try: return Eval(ConfigParser.ConfigParser.get(self, section, option))
except ConfigParser.NoOptionError: return None
def save(self):
self.write(open(self.conf_file, 'w'))
def __del__(self):
self.save()
class LocalConfig(_ConfParse):
def __init__(self, conffile, confpath = '/etc/local/cnf'):
_ConfParse.__init__(self, confpath, conffile)
class SysConfig(_ConfParse):
def __init__(self, conffile, confpath = '/etc/sys/cnf'):
_ConfParse.__init__(self, confpath, conffile)
</code></pre>
|
[] |
[
{
"body": "<p>One problem I see is that returning None from your modified get() method conflicts with the normal case of a valueless option (from the bottom of the module docs for ConfigParser):</p>\n\n<pre><code>>>> import ConfigParser\n>>> import io\n\n>>> sample_config = \"\"\"\n... [mysqld]\n... user = mysql\n... pid-file = /var/run/mysqld/mysqld.pid\n... skip-external-locking\n... old_passwords = 1\n... skip-bdb\n... skip-innodb\n... \"\"\"\n>>> config = ConfigParser.RawConfigParser(allow_no_value=True)\n>>> config.readfp(io.BytesIO(sample_config))\n\n>>> # Settings with values are treated as before:\n>>> config.get(\"mysqld\", \"user\")\n'mysql'\n\n>>> # Settings without values provide None:\n>>> config.get(\"mysqld\", \"skip-bdb\")\n\n>>> # Settings which aren't specified still raise an error:\n>>> config.get(\"mysqld\", \"does-not-exist\")\nTraceback (most recent call last):\n ...\nConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'\n</code></pre>\n\n<p>Note the second-to-last example commented as \"Settings without values provide None:\" Of course this isn't an issue if you intend to exclude this sort of option. Other than that, I like the auto-section feature.</p>\n\n<p>Though, I'd lean towards adding to the interface rather than masking and changing the behavior, so instead of replacing get/set, add safe_ versions:</p>\n\n<pre><code>def safe_set(self, section, option, value):\n if self.has_section(section):\n self.set(section, option, str(value))\n else:\n self.add_section(section)\n self.set(section, option, str(value))\n\ndef safe_get(self, section, option):\n if self.has_option(section, option):\n return self.get(section, option)\n else:\n return None\n</code></pre>\n\n<p>This would make it more flexible as code would still have access to ConfigParser's normal interface and the option of using the \"safe\" calls which don't throw exceptions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T20:51:53.883",
"Id": "4345",
"Score": "0",
"body": "I thought about creating a different 'safe' method, but since I'm not doing anything to mess with the format of the file; you could still use the standard `ConfigParser` on the same file. Is retaining the inherited class methods un-modified a 'best' or 'standard' practice? I just don't know what the conventions are for something like this- if there are any! Thanks for looking at this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T20:38:17.297",
"Id": "2804",
"ParentId": "2775",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2804",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T02:20:10.937",
"Id": "2775",
"Score": "3",
"Tags": [
"python"
],
"Title": "Python subclassing ConfigParser"
}
|
2775
|
<pre><code><p style="background-color:#<%= debate.bg_color %>;" >
</code></pre>
<p><code>be_color</code> is a method of <code>Debate</code> that returns a string like <code>45FFFF</code>.</p>
<p>Although it does what I want, this seems like a tremendously bad idea. What would be a better way to accomplish this? (I'm very new to both Ruby and Rails. And new-ish to web development in general.)</p>
|
[] |
[
{
"body": "<p>inline styles are bad practice</p>\n\n<p>more elegant way would be assigning class to your <p> element based on debate properties, maybe creating a helper if this line is used frequently</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T22:17:01.067",
"Id": "4321",
"Score": "0",
"body": "Does that mean using the same bg_color function but putting it in the .css instead? The color is generated and could be anything from the entire range of colors.\n\nIf I create a helper, should I have the helper return something like \"background-color:#123123;\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T09:06:17.003",
"Id": "4335",
"Score": "0",
"body": "your request is strange - usually all colors are known beforehand and put to static css. something like this:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T09:11:46.550",
"Id": "4336",
"Score": "0",
"body": ".debate-1 { background-color: #123 }\n.debate-2 { background-color: #234 }\n.debate-3 { background-color: #fff }\n\nAnd then one of those classes is assigned to your <p> element, depending on your debate object.\n\nIf you hardcode css styles in your views, it will be nightmare if designer decides to change some colors. You will have to edit all occurrences of that color to new one. If you had predefined classes with colors, you would have to edit only one line in css file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T03:58:41.400",
"Id": "4406",
"Score": "0",
"body": "The color is dynamically generated based on user actions (the app is for debating, and if one side of the debate has more comments, it will have a different color, based on the total number of comments for both sides, and how many more comments the winning side has)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T02:26:14.410",
"Id": "6044",
"Score": "1",
"body": "Inline styles aren't necessarily evil, though when you find yourself using them a lot, especially similar ones, something's probably wrong with your design."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T05:29:42.377",
"Id": "2778",
"ParentId": "2777",
"Score": "6"
}
},
{
"body": "<p>Based on your restrictions I would say this solution is fine. If you don't want to do inline styles though you could definitely consider something like either writing the color to a javascript variable or a data-* attributes on the debate element.</p>\n\n<pre><code><script type=\"text/javascript\">\nvar debateColor = '<%= debate.bg_color %>';\n</script>\n</code></pre>\n\n<p>or the data solution:</p>\n\n<pre><code><p class=\"debate\" data-debate-color=\"<%= debate.bg_color %>';\n</code></pre>\n\n<p>But if it were me I would actually do the color calculation on the frontend, meaning you would basically assign the number of actions for each debate to javascript variables, and what would be done with those (a custom background color for instance, or anything else) would be determined in javascript. The color of any element just doesn't seem like something you would want to calculate on the server side unless it involves complex business logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-24T14:08:34.353",
"Id": "96509",
"Score": "0",
"body": "Don't calculate styles on the client side unless they need to be dynamic in a way that server-side business logic can't provide. Just use appropriate CSS and have done with it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T23:12:19.140",
"Id": "4042",
"ParentId": "2777",
"Score": "2"
}
},
{
"body": "<p>This has nothing to do with Ruby. Inline styles should never be used in <em>any</em> Web development, ever. Specify the background color in a CSS file.</p>\n\n<p>Bonus tip: use <a href=\"http://haml-lang.com\" rel=\"nofollow\">Haml</a> and <a href=\"http://sass-lang.com\" rel=\"nofollow\">Sass</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T00:14:55.500",
"Id": "499568",
"Score": "0",
"body": "I disagree with your blanket statement. Inline styles are a useful tool in a web developers arsenal. They should be used sparingly and the dev should be aware of their limitations and implications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T05:30:52.460",
"Id": "499577",
"Score": "0",
"body": "@Mike Under what circumstances do you believe that inline styles are useful in 2020? I can’t think of a single case where I’d use them (except for quick experiments on my development machine only)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-21T21:32:36.200",
"Id": "5511",
"ParentId": "2777",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T03:41:36.967",
"Id": "2777",
"Score": "4",
"Tags": [
"ruby",
"html",
"ruby-on-rails",
"css"
],
"Title": "Setting bgcolor in Ruby. What's the proper way to do it?"
}
|
2777
|
<p>Following the normal pattern of adding inline scripts to gridview row/s is a <strong>bad practice</strong> it used to work like below</p>
<pre><code> protected void CustomersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
case DataControlRowType.DataRow:
DataRowView drv = (DataRowView)e.Row.DataItem;
if (drv != null)
{
string sKey = drv["Id"].ToString(); e.Row.Attributes.Add("onclick","location.href='manage.aspx?="+sKey+"'");
}
break;
}
}
</code></pre>
<p>hence i switched over to event registration pattern which worked like below</p>
<pre><code>protected void CustomersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
case DataControlRowType.Header:
StringBuilder _sbDynamicScript = new StringBuilder();
_sbDynamicScript.AppendLine("Sys.Application.add_load(function(){");
_sbDynamicScript.AppendLine("try{");
break;
case DataControlRowType.DataRow:
DataRowView drv = (DataRowView)e.Row.DataItem;
if (drv != null)
{
string sKey = drv["Id"].ToString();
e.Row.Attributes.Add("id", randomNumber);
_sbDynamicScript.AppendLine("if($get('" + randomNumber + "'))$addHandler($get('" + randomNumber + "'),'click',function(evnt){location.href='manage.aspx?id='="+ sKey +"'})");
}
break;
case DataControlRowType.Footer:
_sbDynamicScript.AppendLine("}catch(err){alert(err.message)}})");
if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), "customerapp"))
{
Page.ClientScript.RegisterStartupScript(GetType(), "customerapp", _sbDynamicScript.ToString(), true);
}
Session["clientScript"] = _sbDynamicScript.ToString();
break;
}
}
</code></pre>
<p>notice rowType is used to create dynamic script. Here's something that's happening <strong>up there</strong> </p>
<p>1.add a random number as ID for the gridview row</p>
<p>2.then add a click event handler using the asp.net ajax</p>
<ol>
<li>make the make navigate away on click</li>
</ol>
<p><strong>Bug's ahoy:</strong></p>
<p>Notice that in footer template i have put that script into session, that was my mistake. You see the <strong>scripts registered using registerstartup script are not persisted on postbacks and have to be re-registered.</strong> i have put a check on PageLoad to do below</p>
<pre><code> if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), ""))
{
Page.ClientScript.RegisterStartupScript(GetType(), "customerapp", Session["clientScript"].ToString(), true);
}
</code></pre>
<blockquote>
<p>notice the script is registered from
session!! Well it happens some times
that the Gridview records are changed
by postback. But since session has
already the key in it, the
rowdatabound event script fails to get
registered with new script. So what do
i do in this situation. Can i get some
other way to persist the script and
make it run whenever gridview binds
again</p>
</blockquote>
<p>btw the script registered will look like below</p>
<pre><code>Sys.Application.add_load(function () {
try {
if ($get('ElSxrM4myH4%3d')) {
$addHandler($get('ElSxrM4myH4%3d'), 'click', function (evnt) {})
}
} catch (err) {
alert(err.message)
}
})
</code></pre>
|
[] |
[
{
"body": "<p>Would it not be better to build a generic script to handle all row scripting requirements, and include once per page? You'll end up with a cleaner end script, and your page footprint will be a lot smaller. You'll also benefit from the browser's resource caching.</p>\n\n<p>Using jQuery, you could achieve something like:</p>\n\n<pre><code>$(function() {\n $(\"tr.needEvent td\").live(function() {\n // Event handler code goes here.\n });\n});\n</code></pre>\n\n<p>where <code>tr.needEvent</code> is a class appended to the <code><tr></code> used to wrap a row. If you aren't using tables, this could be used the same way with <code><div></code> or any other container element. The important thing is, using <code>.live()</code> we can run the code once, and any other elemnets added to the page that match that selector, will be bound to the event handler automatically.</p>\n\n<p>The use of <code>$(function() {</code> is the jQuery equivalent of <code>Sys.Application.add_load(function() {</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T04:01:41.933",
"Id": "4328",
"Score": "0",
"body": "you recommend separating scripting behavior from page markup? Great Idea just that how will i add event handlers to table row's of the grid when i can't predict them [as it is generated at runtime]. Does anything else run through your mind, mine is blank right now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T06:05:09.240",
"Id": "4329",
"Score": "0",
"body": "jQuery has great support for persistent events using `.live`. I've updated my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T06:55:01.823",
"Id": "4332",
"Score": "0",
"body": "I'm still not satisfied with the answer. I will vote up but definitely not a answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T07:45:03.540",
"Id": "4333",
"Score": "0",
"body": "@Deeptechtons - What are you looking for in an answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T08:10:58.173",
"Id": "4334",
"Score": "0",
"body": "thanks for inquiring again, questions says most of it. In certains cases, another button somewhere on the webform might cause postback which doesn't rebind the Gridview in that cause the script won't be registered is it wasn't for session. I feel using session is costly too, and it creates another problem when gridview rebinds.On the Page_Load the script was already registered from session and the new script generated inside row_databound would fail get my point now?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T17:44:42.410",
"Id": "2787",
"ParentId": "2780",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2787",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T09:42:49.717",
"Id": "2780",
"Score": "0",
"Tags": [
"c#",
"javascript",
"asp.net",
"design-patterns"
],
"Title": "How to re register dynamic scripts registered with ClientScriptManager in asp dot net using session was bad idea"
}
|
2780
|
<p>I made this PHP class that loads any image you specify and resizes it to any size you want.</p>
<p><strong>Features</strong></p>
<p>If the size you specify is greater than the original, it will not stretch the image but use padding instead. Or if the size you requested is not the original aspect ratio, it will not distort the image but use padding to match the requested size.</p>
<p>You can specify what color you want the padding to be, default is white. It preserves transparency in .png files. You can specify what output you want to use (.jpeg/.gif/.png) but it defaults to the original file type.</p>
<p><strong>Primary Purpose</strong></p>
<p>The main reason I wanted to make this class was so that I could upload 1 large file and use it throughout the site. So I would not need to create several copies of the same image in different sizes (large, thumbnail, etc.)</p>
<p>In theory I wanted to be able to upload the largest version of the image I have, then still be able to load a page with 50 small thumbnails relatively fast because the large images are being shrunk before they are loaded.</p>
<p><strong>Problem</strong></p>
<p>It does work, however, when loading a very large image as a thumbnail, it still seems to take about the same amount of time as if it were not shrinking. Only instead of waiting for it to actually download you are waiting for the image to be processed and resampled before you can begin download. This delay only happens when processing large images. The one I used was 5MB.</p>
<p><strong>Code</strong></p>
<pre><code>class ImageSrv
{
private $image;
private $original_width;
private $original_height;
private $original_type;
// default colors for background and padding
private $r = 255;
private $g = 255;
private $b = 255;
function load($image_file)
{
$this->image = $this->createImageFromFile($image_file);
}
function setBackground($r, $g, $b)
{
$this->r = (int) $r;
$this->g = (int) $g;
$this->b = (int) $b;
}
function createImageFromFile($image_file)
{
$image_info = getimagesize($image_file);
$this->original_width = $image_info[0];
$this->original_height = $image_info[1];
$this->original_type = $image_info[2];
if( $this->original_type == IMAGETYPE_JPEG )
{
return imagecreatefromjpeg($image_file);
}
else if( $this->original_type == IMAGETYPE_GIF )
{
return imagecreatefromgif($image_file);
}
else if( $this->original_type == IMAGETYPE_PNG )
{
/*
* create image and preserve transpancy
* this keeps png files from having a black backgroung
* when you don't resize them.
* pngs converted to jpgs still have a black background
* not sure how to make it a different color
*/
$im = imagecreatefrompng($image_file);
imagealphablending($im, false);
imagesavealpha($im, true);
return $im;
}
}
function setSize($width = NULL,$height = NULL)
{
if($width == NULL && $height == NULL)
{
return;
}
$ratio = $this->original_width / $this->original_height;
$new_ratio = $width / $height;
if($width == NULL)
{
$width = $height*$ratio;
if($width > $this->original_width)
{
$width = $this->original_width;
}
}
else if($height == NULL)
{
$height = $width/$ratio;
if($height > $this->original_height)
{
$height = $this->original_height;
}
}
// if width is greater than original width
// set to original width and pad the difference
if($width < $this->original_width)
{
$w = $width;
}
else
{
$w = $this->original_width;
}
// if height is greater than original height
// set to original height and pad the difference
if($height < $this->original_height)
{
$h = $height;
}
else
{
$h = $this->original_height;
}
// check if new deminsions are same aspect ratio
// if not, fix aspect ratio and pad the difference
if( $w / $h != $ratio )
{
if($width > $w && $height > $h)
{
//no scaling
}
else if($width > $w)
{
$w = $h*$ratio;
}
else if($height > $h)
{
$h = $w/$ratio;
}
else if($ratio < $new_ratio)
{
$w = $h*$ratio;
}
else
{
$h = $w/$ratio;
}
}
// resize image with correct aspect ratio and use padding to meet required size
$image = imagecreatetruecolor($width, $height);
imagealphablending($image, false);
imagesavealpha($image, true);
$transparent = imagecolorallocatealpha($image, $this->r, $this->g, $this->b, 127);
imagefill($image, 0, 0, $transparent);
imagecopyresampled($image, $this->image, ($width - $w) / 2 , ($height - $h) / 2, 0, 0, $w, $h, $this->original_width, $this->original_height);
$this->image = $image;
// reset original width and height to the new width and height
$this->original_width = $width;
$this->original_height = $height;
}
function output($type=NULL)
{
if($type == NULL)
{
$type = $this->original_type;
}
if( $type == IMAGETYPE_JPEG )
{
header('Content-Type: image/jpeg');
imagejpeg($this->image);
}
else if( $type == IMAGETYPE_GIF )
{
header('Content-Type: image/gif');
imagegif($this->image);
}
else if( $type == IMAGETYPE_PNG )
{
header('Content-Type: image/png');
imagepng($this->image);
}
}
}
</code></pre>
<p>Is there anything I can do to improve this performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:44:04.563",
"Id": "76193",
"Score": "0",
"body": "See also: http://codereview.stackexchange.com/questions/44025/security-scale-and-cache-images"
}
] |
[
{
"body": "<p>I take it you are using GD for image manipulation. You could look at ImageMagick as an alternative, as its been shown to be faster at manipulating images. There is a related <a href=\"https://stackoverflow.com/questions/12661/efficient-jpeg-image-resizing-in-php\">SO question here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T14:26:38.233",
"Id": "392526",
"Score": "0",
"body": "I know this is an old answer, but this doesn't fit the criteria for a good review on Code Review. We try to steer away from answers that say \"***use X because it is better***\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T17:57:04.323",
"Id": "2789",
"ParentId": "2786",
"Score": "1"
}
},
{
"body": "<p>Cache the generated images so they only need to be generated once. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T19:01:40.197",
"Id": "2791",
"ParentId": "2786",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T16:25:50.047",
"Id": "2786",
"Score": "2",
"Tags": [
"php",
"performance",
"image"
],
"Title": "Class for loading and resizing images on the fly performs slowly on large images"
}
|
2786
|
<p>I've been asked to keep track of how long a user has been connected to a site without interruption.</p>
<p>So far the solution I've come up with is to use ajax to poll the site every now and then to check how much time has elapsed since the last call.</p>
<p>Any suggestions for possible improvements would be appreciated.</p>
<p>P.S: Not sure why but text isn't displaying if no text is in the div or echoed.</p>
<p><strong>The javascript</strong></p>
<pre><code><script type="text/javascript">
<!--
// trigger the function
toto("UserConnected.php",'scriptoutput');
-->
</script>
<script type="text/javascript">
var page = "UserConnected.php";
var timer = ""; // Not sure how to avoid conflicts between timers
function toto(url,target)
{
//alert("working");
document.getElementById(target).innerHTML = 'sending...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = function() {ajaxDone(target);};
//req.open("GET", url, true);
//req.send(null);
req.open("POST", page, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("data=<?php echo $user->id; ?>");
// IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = function() {ajaxDone(target);};
//req.open("GET", url, true);
//req.send();
req.open("POST", page, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("data=<?php echo $user->id; ?>");
}
}
timer = setTimeout("toto(page,'scriptoutput')", 1 * 60 * 1000);
}
function ajaxDone(target) {
// only if req is "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200 || req.status == 304) {
results = req.responseText;
document.getElementById(target).innerHTML = results;
} else {
document.getElementById(target).innerHTML="ajax error:\n" +
req.statusText;
}
}
}
</script>
</code></pre>
<p><strong>The PHP code</strong></p>
<pre><code>if( isset( $_POST["data"] ) ){
$id = (int) $_POST["data"];
$sql ='INSERT INTO users_timeconnected ( profil_id, last_ajax_call ) VALUES ('. $id .', NOW() ) ON DUPLICATE KEY UPDATE id=id';
$db->query( $sql );
$sql ="
select (
(
unix_timestamp( now() )
- unix_timestamp( (select last_ajax_call from users_timeconnected where profil_id =" . $id ." ) )
) / 60
)";
$db->query( $sql );
$timeSinceLastCall = $db->fetch_one();
$sql = 'select minutes_connected from users_timeconnected where profil_id =' . $id;
$db->query( $sql );
$minutesConnected = $db->fetch_one();
echo "current time:" . date("d/m/y : H:i:s", time()).'<br/>';
echo "id:" . $id .'<br/>';
echo "time since last call:" .$timeSinceLastCall.'<br/>';
echo "connected:" . $minutesConnected.'<br/>';
echo "lower than or equal to 6:" . (int)($timeSinceLastCall <= 6);
if( $timeSinceLastCall <= 6 ){
$timeSinceLastCall = 0; // reset
$sql ='UPDATE users_timeconnected SET minutes_connected = minutes_connected+5 WHERE profil_id='. $id ;
$db->query( $sql );
$sql ='UPDATE users_timeconnected SET last_ajax_call = NOW() WHERE profil_id='. $id;
$db->query( $sql );
}
}
</code></pre>
<p><strong>The SQL table</strong></p>
<pre><code>CREATE TABLE IF NOT EXISTS `users_timeconnected` (
`id` int(10) unsigned NOT NULL auto_increment,
`profile_id` int(10) unsigned NOT NULL default '0',
`last_ajax_call` timestamp NULL default NULL,
`minutes_connected` int(10) default '0',
PRIMARY KEY (`id`),
UNIQUE KEY `profil_id` (`profile_id`)
);
</code></pre>
<p><strong>The html for tests</strong></p>
<pre><code><div id="scriptoutput">Output</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-10T03:17:05.487",
"Id": "4458",
"Score": "1",
"body": "Don't know how you define \"connected\", but I would suggest you look at this answer on StackOverflow - http://stackoverflow.com/questions/1760250/how-to-tell-if-browser-tab-is-active"
}
] |
[
{
"body": "<p>Structure of your Javascript is tightly coupled with your logic, decoupling will allow change without major changes.</p>\n\n<p>a) Move you Ajax initialization [xmlHttp] to a usable function.</p>\n\n<p>b) UnIntended display of UserId <code>req.send(\"data=<?php echo $user->id; ?>\");</code> as plain text inside your javaScript is security risk</p>\n\n<p>c) Refactor your client script and least packit(dean edwards works ok) and compress it.</p>\n\n<p>d) Using a comet based server is Best solution to this rather than polling the server at defined intervals. I would recommend you learn <a href=\"http://www.ape-project.org/\" rel=\"nofollow\">APE Project</a></p>\n\n<p>another point! you can do it this way, when user navigates away from page ask them a few seconds to send ajax request. You have login time and now you have leaving time , calculate Hit rate yourself.\nAlso using LocalStorage will be viable option too</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T10:31:58.543",
"Id": "2796",
"ParentId": "2795",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "2796",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T09:12:49.763",
"Id": "2795",
"Score": "2",
"Tags": [
"php",
"javascript",
"mysql",
"sql",
"ajax"
],
"Title": "Polling script to determine the continuous time a user has been connected"
}
|
2795
|
<p>In my particular usage here, I'm using two functions to deal with one thing.</p>
<p>Lets say the user request comes in to select "ALL" the records, in which case I would pass on some code such as:</p>
<pre><code>function getRecords() {
return some_sql("Select * from whatever WHERE id > 0;");
}
</code></pre>
<p>But then I want to run just one record, I'd do </p>
<pre><code>function getRecords(SomeID) {
return some_sql("Select * from whatever WHERE id = SomeID;");
}
</code></pre>
<p>And if I wanted to get a specific list of records, I'd do something like</p>
<pre><code>function getRecordsByID(someArray(1,2,3,10,11,99)) {
var someIDs = "";
for (i in someArray) {
someIDs = "(" + someArray.join(",") + ")";
}
return some_sql("Select * from whatever WHERE id IN SomeIDs;");
}
</code></pre>
<p>It dawns on me that I could of course use getRecordByID everywhere I've used getRecord, but I can't do this for getRecords.</p>
<p>Is there a common or overlooked design pattern I'm missing here? My first guess would be something like checking the argument's contents for a valid array and running based on that, but I'd like to see a better option.</p>
|
[] |
[
{
"body": "<p>Why would you want a single method to do three logically different things? Each method you make should really only perform one task. What's the problem in just having the consumer choose the method of selection based upon their need, instead of having a one method fits all sort of thing? If having three methods really isn't what you want, perhaps you could pass a Command pattern object to a database object, to execute the desired functionality? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T18:51:22.940",
"Id": "4340",
"Score": "0",
"body": "Because logically they're all the same thing. Getting record(s)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T20:36:44.447",
"Id": "4342",
"Score": "0",
"body": "@user2905 While they're all getting records, I wouldn't say they're all the same thing since they clearly imply returning different results. Since they all share the common purpose of \"getting records [from a database]\", I would keep all methods in the same class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T20:38:05.927",
"Id": "4343",
"Score": "0",
"body": "@user2905 For example, would getRecordsForTeenagers() also be the same thing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T20:40:27.890",
"Id": "4344",
"Score": "0",
"body": "Why couldn't I return an array of records?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T16:18:55.770",
"Id": "4352",
"Score": "0",
"body": "I think you could make a cohesive class for 'getting records', but at method level, you'd distinguish between the pieces of functionality with the criterion you query with to get the specific records. \n\nReturning a collection (array, list, map, whatever) of records is a good idea if your method reads as `getRecords`, but if as the consumer of the code, you know you only want a single record, it could become misleading."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T18:15:22.940",
"Id": "2801",
"ParentId": "2800",
"Score": "5"
}
},
{
"body": "<p>While what you have can be done by reusing some code, it is always better to call the database once as opposed to calling it multiple times.</p>\n\n<p>What you could do is have a helper function</p>\n\n<pre><code>function getRecordsByCondition(condition) {\n return some_sql(\"Select * from whatever WHERE \"+condition+\";\");\n}\n</code></pre>\n\n<p>then call it from the other functions.</p>\n\n<p>Also <code>getRecord</code> can be implemented as a special case of <code>getRecordsByID</code> with an array of size 1.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T18:49:09.363",
"Id": "2810",
"ParentId": "2800",
"Score": "2"
}
},
{
"body": "<p>Just a suggestion:</p>\n\n<pre><code>function getAllRecords();\nfunction getRecords(int[] recordIds){...}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T20:00:24.720",
"Id": "2836",
"ParentId": "2800",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2801",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T17:48:35.267",
"Id": "2800",
"Score": "4",
"Tags": [
"design-patterns",
"sql"
],
"Title": "I want a nice design pattern for \"All\", \"many\" or \"one\""
}
|
2800
|
<p>I've been working on putting a new app up against Zend. In my admin section, I want the nav links to only show if the user has rights to see the page. So I set up some Acls. But this doesn't seem like the right way to do things. What's the "right" way to do this stuff?</p>
<p><strong>Bootstrap.php</strong></p>
<pre><code><?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected $_aclAdapter;
protected function _initDoctype() {
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype('XHTML1_STRICT');
}
protected function _initPlugins() {
// First, set up the Cache
$frontendOptions = array(
'automatic_serialization' => true
);
if (! is_dir("/tmp/cache")) mkdir("/tmp/cache");
$backendOptions = array(
'cache_dir' => '/tmp/cache'
);
$cache = Zend_Cache::factory('Core',
'File',
$frontendOptions,
$backendOptions);
Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
$this->_aclAdapter = new My_Plugin_Acl();
}
protected function _initRoute() {
/*
$this->bootstrap('FrontController');
$front = $this->getResource('FrontController');
$router = $front->getRouter();
$restRoute = new Zend_Rest_Route($front, array(), array('rest'));
$router->addRoute('rest', $restRoute);
return $router;
*/
}
protected function _initAutoloadModuleAdmin() {
$autoloader = new Zend_Application_Module_Autoloader(
array(
'namespace' => 'Admin',
'basePath' => APPLICATION_PATH . '/modules',
)
);
return $autoloader;
}
protected function _initDatabase() {
$database = Zend_Db_Table::getDefaultAdapter();
return $database;
}
protected function _initAuthChecker() {
$this->bootstrap('view');
$view = $this->getResource('view');
/**
* @todo Determine how to pass Acl information to the view
* so that links can be determined properly
*/
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$view->isLoggedIn = true;
$aclAdapter = $this->_aclAdapter;
$container = new Zend_Navigation();
$pages = array(
new Zend_Navigation_Page_Mvc(array('module' => 'admin', 'action' => 'index', 'controller' => 'make', 'label' => 'Makes')),
new Zend_Navigation_Page_Mvc(array('module' => 'admin', 'action' => 'index', 'controller' => 'model', 'label' => 'Models')),
new Zend_Navigation_Page_Mvc(array('module' => 'admin', 'action' => 'index', 'controller' => 'year', 'label' => 'Years')),
new Zend_Navigation_Page_Mvc(array('module' => 'admin', 'action' => 'index', 'controller' => 'user', 'label' => 'Users')),
);
foreach ($pages as $page) {
$resources = $aclAdapter->getCurrentResources($page);
$allowedToViewResource = true;
foreach ($resources as $resource) {
// access to the module
if(!$aclAdapter->isAllowed($aclAdapter->getRolesForIdentity($auth->getIdentity()->nickname), $resource, 'view')) {
$allowedToViewResource = false;
}
}
if ($allowedToViewResource) {
$container->addPage($page);
}
$view->navigation = $container;
}
} else {
$view->isLoggedIn = false;
}
}
}
</code></pre>
<p><strong>My/Plugin/Acl.php</strong></p>
<pre><code><?php
/**
* Acl functionality
*
* @category My
* @package My_Plugin
* @author Glen Solsberry <glens@dp.cx>
*/
class My_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
/**
* @var Zend_Acl
*/
protected $_acl = null;
public function __construct() {
$args = func_get_args();
if (count($args) > 0) {
$this->_acl = $args[0];
} else {
$this->_acl = new Zend_Acl();
}
$this->_acl = $this->setupRoles($this->_acl);
$this->_acl = $this->setupResources($this->_acl);
$this->_acl = $this->setupAllowances($this->_acl);
}
public function isAllowed($role, $resource, $function) {
return $this->_acl->isAllowed($role, $resource, $function);
}
/**
* preDispatch
*
* @param Zend_Controller_Request_Abstract $request
* @return none
*/
public function preDispatch(Zend_Controller_Request_Abstract $request) {
if (Zend_Auth::getInstance()->hasIdentity()) {
$identity = Zend_Auth::getInstance()->getIdentity();
$role = $this->getRolesForIdentity($identity->nickname);
} else {
$role = 'guest';
}
$resources = $this->getCurrentResources($request);
$allowedToViewResource = true;
foreach ($resources as $resource) {
// access to the module
if(!$this->_acl->isAllowed($role, $resource, 'view')) {
$allowedToViewResource = false;
}
}
if ($allowedToViewResource === false) {
//If the user has no access we send him elsewhere by changing the request
// print sprintf("I'm sorry, but your role '%s' doesn't have access to the resource named '%s'<br>", $role, $resource);
$request->setModuleName('')->setControllerName('auth')->setActionName('login');
return false;
}
return true;
}
public function getCurrentResources($request) {
if ($request instanceOf Zend_Controller_Request_Http) {
$resources = array(
$request->getModuleName(),
implode("-", array($request->getModuleName(), $request->getControllerName())),
implode("-", array($request->getModuleName(), $request->getControllerName(), $request->getActionName())),
);
} else if ($request instanceOf Zend_Navigation_Page_Mvc) {
$resources = array(
$request->getModule(),
implode("-", array($request->getModule(), $request->getController())),
implode("-", array($request->getModule(), $request->getController(), $request->getAction())),
);
} else {
throw new Zend_Exception('Unsupported request type');
}
return $resources;
}
/**
* Gets available roles for an identity, by nickname
* @param string $nickname
*/
public function getRolesForIdentity($nickname) {
if ($nickname === "") {
return 'guest';
}
return 'admin';
}
private function setupRoles(Zend_Acl $acl) {
$acl->addRole(new Zend_Acl_Role('guest'));
// make-admin has all rights that guest has
$acl->addRole(new Zend_Acl_Role('make-admin'), 'guest');
$acl->addRole(new Zend_Acl_Role('model-admin'), 'guest');
$acl->addRole(new Zend_Acl_Role('year-admin'), 'guest');
$acl->addRole(new Zend_Acl_Role('user-admin'), 'guest');
// admin has all rights that year-admin, make-admin, user-admin and model-admin have
$acl->addRole(new Zend_Acl_Role('admin'), array('year-admin', 'make-admin', 'model-admin', 'user-admin'));
return $acl;
}
private function setupResources(Zend_Acl $acl) {
// setup admin resources
$this->setupResourcesFromArrays(
$acl,
array('admin'),
array('index','make','year','model','user'),
array('index','update','delete')
);
$this->setupResourcesFromArrays(
$acl,
array('default'),
array('auth','index','error'),
array('index')
);
$this->setupResourcesFromArrays(
$acl,
array('default'),
array('auth'),
array('logout')
);
$this->setupResourcesFromArrays(
$acl,
array('default'),
array('favicon.ico'),
null
);
return $acl;
}
private function setupResourcesFromArrays($acl, $modules, $controllers, $actions) {
foreach ($modules as $module) {
$resource_name = $module;
$this->addResource($acl, $resource_name);
foreach ($controllers as $controller) {
$resource_name = sprintf('%s-%s', $module, $controller);
$this->addResource($acl, $resource_name);
if (is_array($actions)) {
foreach ($actions as $action) {
$resource_name = sprintf('%s-%s-%s', $module, $controller, $action);
$this->addResource($acl, $resource_name);
}
}
}
}
}
private function addResource($acl, $resource_name) {
if (! $acl->has($resource_name)) {
$acl->addResource(new Zend_Acl_Resource($resource_name));
}
}
private function setupAllowances(Zend_Acl $acl) {
// role, resource, privilege
$acl->allow('admin', 'admin', 'view');
$acl->allow('admin', 'admin-index', 'view');
$acl->allow('admin', 'admin-index-index', 'view');
/**
SNIP
*/
$acl->allow('guest', 'default', 'view');
$acl->allow('guest', 'default-index', 'view');
$acl->allow('guest', 'default-index-index', 'view');
$acl->allow('guest', 'default-auth', 'view');
$acl->allow('guest', 'default-auth-index', 'view');
return $acl;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You should use the <a href=\"http://framework.zend.com/manual/en/zend.application.available-resources.html\" rel=\"nofollow\">available bootstrap resources</a> where possible:</p>\n\n<pre><code>protected function _initPlugins() {\n // First, set up the Cache\n $frontendOptions = array(\n 'automatic_serialization' => true\n );\n\n if (! is_dir(\"/tmp/cache\")) mkdir(\"/tmp/cache\");\n $backendOptions = array(\n 'cache_dir' => '/tmp/cache'\n );\n\n $cache = Zend_Cache::factory('Core',\n 'File',\n $frontendOptions,\n $backendOptions);\n</code></pre>\n\n<p>could be replaced by without any functions in your bootstrap:</p>\n\n<pre><code>resources.cachemanager.yourcachename.frontend.name = Core\nresources.cachemanager.yourcachename.options.automatic_serialization = true\nresources.cachemanager.yourcachename.backend.name = File\nresources.cachemanager.yourcachename.backend.options.cache_dir = \"/tmp/cache\"\n</code></pre>\n\n<p>Finally, you activate the metadatacache for your database:</p>\n\n<pre><code>resources.db.defaultMetadataCache = \"yourcachename\"\n</code></pre>\n\n<p>Same can be done with your view:</p>\n\n<pre><code>protected function _initDoctype() {\n $this->bootstrap('view');\n $view = $this->getResource('view');\n $view->doctype('XHTML1_STRICT');\n}\n\n// can be replaced with:\nresources.view.doctype = \"XHTML1_STRICT\"\n</code></pre>\n\n<p>Assuming you're setting up the database in your config, you probably don't need this line:</p>\n\n<pre><code>protected function _initDatabase() {\n $database = Zend_Db_Table::getDefaultAdapter();\n return $database;\n}\n</code></pre>\n\n<p>You can do the same for your autoloader and routes as well.<br>\nThis probably should be a plugin on it's own:</p>\n\n<pre><code>protected function _initAuthChecker() \n{\n /* .... */\n}\n</code></pre>\n\n<p>So far on your bootstrap. I can see you're take your modules/controllers as resources. Usually I don't aggree with this: a controller handles a set of models, which are the resources. I know this doesn't make the navigation easier ;) You should have a look at the module-bootstraps too. They take module-specific bootstraping away from your main-bootstrap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T15:45:28.150",
"Id": "4363",
"Score": "0",
"body": "As I've not read up on bootstrap resources, does this just create those objects and variables within the bootstrap automagically?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T16:18:30.217",
"Id": "4365",
"Score": "0",
"body": "@gms8994: Yes :) (In a more unified way)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T16:42:09.920",
"Id": "4366",
"Score": "0",
"body": "\"So far on your bootstrap. I can see you're take your modules/controllers as resources. Usually I don't aggree with this: a controller handles a set of models, which are the resources. I know this doesn't make the navigation easier ;) You should have a look at the module-bootstraps too. They take module-specific bootstraping away from your main-bootstrap.\" can you detail what you mean about this a little more? Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T17:34:59.723",
"Id": "4367",
"Score": "0",
"body": "See Zend_Application_Resources_Modules and http://weierophinney.net/matthew/archives/234-Module-Bootstraps-in-Zend-Framework-Dos-and-Donts.html for module-bootstraping. For the controller/model stuff... this is way too much to explain it in a comment ;) http://www.survivethedeepend.com/zendframeworkbook/en/1.0 has a great explanation of both topics (you probably should read even more about it then :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T09:46:36.940",
"Id": "2808",
"ParentId": "2805",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T20:58:00.300",
"Id": "2805",
"Score": "3",
"Tags": [
"php",
"zend-framework"
],
"Title": "Zend Bootstrap code review"
}
|
2805
|
<p>I've come up with this small function to make user submitted strings safe for MySQL. I'd be grateful if someone could point out any security holes in this. I've tested it out, and it happily replaces quotes and the like. The only issue I can see is the lack of escaping ampersands, but this shouldn't matter right?</p>
<pre><code>$keywords = array("delete from", "drop table", ";", "=");
$safeKeywords = array("delete&nbsp;from", "drop&nbsp;table", "&#59;", "&#61;");
function dbSanitise($field)
{
global $keywords, $safeKeywords;
$sanitised = str_ireplace($keywords, $safeKeywords, $field);
$sanitised = htmlentities($sanitised, ENT_QUOTES);
$sanitised = mysql_real_escape_string($sanitised);
return $sanitised;
}
</code></pre>
<p>Putting this string into the function above:</p>
<p><code>Hello world delete from DELETE FROM ; = " ' ''</code></p>
<p>Yields this:</p>
<p><code>Hello world delete&amp;nbsp&amp;#59;from delete&amp;nbsp&amp;#59;from &amp;#59; &amp;#61; &quot; &#039; &#039;&#039;</code></p>
<p>Which I can only see as being perfectly acceptable for a MySQL insert operation.</p>
<p>If I'm wrong, do let me know! Thanks for any help.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T11:18:26.570",
"Id": "4348",
"Score": "1",
"body": "If your string is in quotes, why do you need to remove the dangerous words? Doesn't [mysql_real_escape_string](http://php.net/manual/en/function.mysql-real-escape-string.php) do everything you need?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T11:26:49.630",
"Id": "4349",
"Score": "0",
"body": "That's true, but I've seen all over the place that `mysql_real_escape_string` doesn't always work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T11:30:19.880",
"Id": "4350",
"Score": "1",
"body": "Can you give me a link to a \"not working\" example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T00:33:58.220",
"Id": "4401",
"Score": "1",
"body": "`mysql_real_escape_string` works provided you have already done a `mysql_connect`. Still not satisfied, then use prepared statements in mysqli/pdo."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-15T21:05:28.637",
"Id": "4544",
"Score": "2",
"body": "I agree that `mysql_real_escape_string` should make the 'dangerous' word replacement unnecessary. Otherwise, I think your replacements could be circumvented, for example, by `delete from` with two spaces between 'delete' and 'from'."
}
] |
[
{
"body": "<p>Also check PHP's filtering manual: \n<a href=\"http://php.net/manual/en/book.filter.php\" rel=\"nofollow\">http://php.net/manual/en/book.filter.php</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-18T21:19:06.443",
"Id": "3004",
"ParentId": "2809",
"Score": "1"
}
},
{
"body": "<p>You shouldn't try to think of all the bad things that could be in the query, you'll never think of them all.</p>\n\n<p>As it stands, your replacement is useless (as some of your commentors have noted). You can have any text you want inside of the string, its characters which might cause the string to be escaped which are a problem. </p>\n\n<p>mysql_real_escape_string does everything you need. You don't need to implement your own function. Better yet use prepared statements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-20T15:19:52.090",
"Id": "3020",
"ParentId": "2809",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "3020",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T11:10:04.610",
"Id": "2809",
"Score": "2",
"Tags": [
"php",
"mysql",
"security"
],
"Title": "Sanitisation function: any holes?"
}
|
2809
|
<p>I have implemented a simple iterator. Just want to check if I have missed anything.</p>
<pre><code>interface iterator<E>
{
boolean hasNext();
E next();
}
class Iterator<E> implements iterator
{
E[] arr;
int curPos = 0;
@Override
public boolean hasNext()
{
if (curPos >= arr.length || arr[curPos] == null)
{
return false;
}
else
{
return true;
}
}
@Override
public E next()
{
if(hasNext())
{
E res = arr[curPos];
curPos++;
return arr[curPos+1];
}
else
{
throw new runtimeException("No next element available !");
}
}
}
</code></pre>
<p>Questions:</p>
<ol>
<li>Why should I not use <code>Object</code> instead of <code>E</code>/template everywhere ? </li>
<li>How do I make an iterator for a binary tree.</li>
</ol>
<p>I assume apart from the above, I would have to implement a traversal algorithm and try to find if the next "traversal" successor exist?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T00:58:14.080",
"Id": "4354",
"Score": "0",
"body": "It is not very clear what is asked in the second question. Could you clarify it or (what probably would be better) move it to a separate question?"
}
] |
[
{
"body": "<p>Because then the consumer of that code could write something like:</p>\n\n<pre><code>Iterator<Foo> iterator = new Iterator<Foo>();\n\n//...\n\nFoo theFoo = iterator.next();\n</code></pre>\n\n<p>instead of having to cast the object of type Object to type Foo like</p>\n\n<pre><code>Foo theFoo = (Foo)iterator.next();\n</code></pre>\n\n<p>It avoids potential confusion by being strict about what type of object to expect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T22:05:34.247",
"Id": "4353",
"Score": "0",
"body": "Thanks, I also see that being strict would also enforce that people dont start equating arrays to trees !!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T21:12:39.653",
"Id": "2812",
"ParentId": "2811",
"Score": "1"
}
},
{
"body": "<p>The next method should throw an exception in case iterator reach the end. It is neither safe nor convenient to get an NPE after the iterator was used improperly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T00:55:48.430",
"Id": "2813",
"ParentId": "2811",
"Score": "1"
}
},
{
"body": "<p>If you don't define your own iterator, but use java.util.Iterator, you get this error from the compiler:</p>\n\n<pre><code>Iterator.java:9: Iterator is not abstract and does not override abstract method remove() in java.util.Iterator\n</code></pre>\n\n<p>To use it, where an Iterator is expected, you have to use the java.util.Iterator, which will not be too easy - removing from an array - but you could probably look up, how it is done in the Java source.</p>\n\n<p>But then the compiler is your friend, and tells you, what is wrong. </p>\n\n<p>For a tree, you could write implement multiple iterators - for depth-first traversal, or top-down. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T05:38:09.603",
"Id": "2819",
"ParentId": "2811",
"Score": "1"
}
},
{
"body": "<p>I would write an iterator for arrays that way:</p>\n\n<pre><code>import java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class ArrayIterator<E> implements Iterator<E> {\n\n private final E[] arr;\n private int currentIndex = 0;\n\n public ArrayIterator(E... arr) {\n if(arr == null) {\n throw new IllegalArgumentException(\"Array is null\");\n }\n this.arr = arr;\n }\n\n public boolean hasNext() {\n return currentIndex < arr.length;\n }\n\n public E next() {\n if (! hasNext()) {\n throw new NoSuchElementException();\n }\n return arr[currentIndex++];\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\"Not supported.\");\n }\n\n}\n</code></pre>\n\n<p>To your second question: I assume you want to traverse the tree in-order, and that the nodes have no link to the parent, only to the children. Then you need a node list from the root node to the current node, which can store if a node was already visited or not, too. </p>\n\n<p>Then you go left as deep as possible, storing the path in the node list. This is your first current node. When you need the next one, take its parent (from the node list). Next would be the right children of that node (if there are any) or its own parent. The best way to understand this is to take a sheet of paper, draw different trees, and look how the traversal must work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T05:26:34.847",
"Id": "4407",
"Score": "0",
"body": "Note, this will not be usable for arrays of primitives, e.g. `int[]`, `boolean[]`, ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T08:23:08.407",
"Id": "4411",
"Score": "0",
"body": "@Matt: Yes, you would need specialized versions of that class, but this is a consequence from the insane way Java handles primitive arrays. You have that problem for all other collection stuff as well. On the other hand it's very easy to fix `E` to a wrapper like `Integer` and to adapt `array` and the constructor accordingly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T17:20:22.013",
"Id": "2825",
"ParentId": "2811",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "2825",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T20:43:27.530",
"Id": "2811",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"iterator"
],
"Title": "Iterator pattern/iterator class"
}
|
2811
|
<p>The basic idea is this:</p>
<p>There are two buttons: a <code>DoWork</code> button and a <code>Cancel</code> button.</p>
<p>The <code>DoWork</code> button should launch a thread to do some work, unless that thread was already launched and not canceled.</p>
<p>The <code>Cancel</code> button should cancel the worker thread, if it's running.</p>
<p>Please ignore the fact that it calls <code>Thread.Abort()</code> for the moment, that is a separate issue that I will address later.</p>
<p>Also, how does one generally show the correctness of one's own multithreaded code? It seems much more difficult to debug.</p>
<p>Here's the code:</p>
<pre><code> private Thread m_WorkingThread;
private bool m_finishedWorking;
public Form()
{
InitializeComponent(); // initialize all the form controls.
m_WorkingThread = null;
m_finishedWorking = false;
}
private void bDoWork_Click(object sender, EventArgs e)
{
if (m_WorkingThread != null)
if(m_WorkingThread.IsAlive || m_finishedWorking)
return;
ThreadStart ts = new ThreadStart(DoWork);
Thread t = new Thread(ts);
t.Start();
m_WorkingThread = t;
}
private void bCancel_Click(object sender, EventArgs e)
{
AbortThread(m_WorkingThread);
m_finishedWorking = false;
}
private void AbortThread(Thread t)
{
if (t != null)
if (t.IsAlive)
t.Abort();
}
private void DoWork()
{
// do some work here, maybe using Invokes / BeginInvokes to update any controls.
m_finishedWorking = true;
}
</code></pre>
|
[] |
[
{
"body": "<p>Trying to use shared variables is generally a <strong>Bad Thing(TM)</strong>. The usual way to do cross-thread locking / resource checking is via a mutex.</p>\n\n<p>Something like this, though I haven't compiled or checked it:</p>\n\n<pre><code>private Thread m_WorkingThread;\nprivate static Mutex m_FinishedWorking = new Mutex(); \n\npublic Form()\n{\n InitializeComponent(); // initialize all the form controls.\n m_WorkingThread = null;\n}\n\nprivate void bDoWork_Click(object sender, EventArgs e)\n{ \n if (m_WorkingThread != null)\n if(m_WorkingThread.IsAlive)\n return;\n\n ThreadStart ts = new ThreadStart(DoWork);\n Thread t = new Thread(ts);\n t.Start();\n m_WorkingThread = t;\n\n}\nprivate void bCancel_Click(object sender, EventArgs e)\n{\n AbortThread(m_WorkingThread);\n}\nprivate void AbortThread(Thread t)\n{\n if (t != null)\n if (t.IsAlive)\n t.Abort();\n}\nprivate void DoWork()\n{\n m_FinishedWorking.WaitOne();\n // do some work here, maybe using Invokes / BeginInvokes to update any controls.\n\n // Must be called if the thread is aborted.\n m_FinishedWorking.ReleaseMutex(); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T11:34:01.043",
"Id": "4380",
"Score": "3",
"body": "Mutex is a bit overkill as it works across multiple processes. One should use locks (i.e. Monitor) when there is no need to synchronize across processes. Anyway, I don't see here any need for the locks assuming that the bDoWork_Click() is always called from the UI thread. It only creates a new thread if the existing thread is not alive. However, the resources used by DoWork() must be protected with locks if they are shared with other threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-09T01:49:45.363",
"Id": "4422",
"Score": "0",
"body": "@mgronber: I would like to accept your comment. :-P"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T15:03:34.907",
"Id": "2822",
"ParentId": "2816",
"Score": "1"
}
},
{
"body": "<p>Have you considered using <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow\"><code>BackgroundWorker</code></a>? It might save you some trouble.</p>\n\n<p>However, it does use ThreadPool and you are better to create your own threads if you have any of the following <a href=\"http://msdn.microsoft.com/en-us/library/0ka9477y.aspx\" rel=\"nofollow\">requirements</a>:</p>\n\n<ul>\n<li>You require a foreground thread.</li>\n<li>You require a thread to have a particular priority.</li>\n<li>You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting.</li>\n<li>You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment.</li>\n<li>You need to have a stable identity associated with the thread, or to dedicate a thread to a task.</li>\n</ul>\n\n<p>I add my comment to the answer of \"Peter K.\" here as it seemed to please you.</p>\n\n<blockquote>\n <p>Mutex is a bit overkill as it works\n across multiple processes. One should\n use locks (i.e. Monitor) when there is\n no need to synchronize across\n processes. Anyway, I don't see here\n any need for the locks assuming that\n the bDoWork_Click() is always called\n from the UI thread. It only creates a\n new thread if the existing thread is\n not alive. However, the resources used\n by DoWork() must be protected with\n locks if they are shared with other\n threads.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-09T01:08:24.213",
"Id": "4420",
"Score": "0",
"body": "I have, but I am not too familiar with it except that it uses the threadpool. Ultimately I need to have threads that start when somebody clicks a button, and pause the other threads until that \"top\" thread finishes. Consequently there can be many running threads (like if the user keeps clicking various things) and I hear the threadpool is not so good for such things (many / long-running threads.) In general though you might be right, I really don't know anything about them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-09T10:23:54.477",
"Id": "4431",
"Score": "0",
"body": "I don't really understand what you mean by pausing the other threads. I hope that you are not going to suspend any background threads because you should not do that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-09T20:56:26.853",
"Id": "4439",
"Score": "0",
"body": "Yeah, by pausing I don't mean in the traditional sense. Each thread calls something like while(paused[threadId]) Thread.Sleep(someAmount), before doing any substantial work. Or is that still a bad approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-10T11:05:57.343",
"Id": "4464",
"Score": "1",
"body": "You could also use ManualResetEventSlim instance to control the state for each thread. Instead of while loop you would just call paused[threadId].Wait() and the thread will stay there paused until the corresponding ManualResetEventSlim instance is Set(). With Reset() you can request a pause again and the thread will pause when it reaches the Wait(). It should do what you want. Your current implementation may not work correctly unless there is a memory barrier that forces the value of paused[threadId] to be read from the memory and not from the cache."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-13T15:36:35.027",
"Id": "4503",
"Score": "0",
"body": "Great. I'll try to use those instead of a list of bools, unless you know how to get a list of volatile bools. :-P (Although I guess I could have a list of locks associated w/ each bool.) And the lists themselves would need to have locks associated w/ them. yay multithreading."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T11:38:57.050",
"Id": "2845",
"ParentId": "2816",
"Score": "5"
}
},
{
"body": "<p>I could not find something wrong in your code.</p>\n\n<p>But I would suggest, of course depending on your Framework Version, to use Tasks instead of Threads - System.Threading.Tasks offers you a very good API.</p>\n\n<p>Here a quick example, maybe not bulletproof - but I think you will get the idea:</p>\n\n<pre><code>private Task task;\nprivate CancellationTokenSource tokensource;\nprivate CancellationToken token; \n\npublic Form1() {\n InitializeComponent();\n tokensource = new CancellationTokenSource();\n token = tokensource.Token;\n this.Cancel.Enabled = false;\n}\n\nprivate void DoWork_Click(object sender, EventArgs e) {\n if (task != null && !task.IsCompleted) return;\n\n this.DoWork.Enabled = false;\n this.Cancel.Enabled = true;\n task = Task.Factory.StartNew(() => DoWorkAction(), token)\n .ContinueWith(_ => { this.DoWork.Enabled = true; this.Cancel.Enabled = false; }, \n TaskScheduler.FromCurrentSynchronizationContext());\n}\n\nprivate void Cancel_Click(object sender, EventArgs e) {\n tokensource.Cancel();\n}\n\nprivate void DoWorkAction() {\n Thread.Sleep(5000);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-09T01:48:24.800",
"Id": "4421",
"Score": "0",
"body": "Thanks. I'll look into them. Unfortunately I think it uses ThreadPool, which I am hoping to avoid."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T05:52:54.130",
"Id": "2866",
"ParentId": "2816",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2845",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T03:29:49.893",
"Id": "2816",
"Score": "1",
"Tags": [
"c#",
"multithreading",
"form"
],
"Title": "Is my multithreaded form code correct?"
}
|
2816
|
<ul>
<li><code>Ax, Ay, Az: [N-by-N]</code></li>
<li><code>B=AA</code> (dyadic product) </li>
</ul>
<p>means </p>
<pre><code>B(i,j)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)]
</code></pre>
<p><code>B(I,j)</code>: a 3x3 matrix.</p>
<p>One way to construct <code>B</code> is:</p>
<pre><code>N=2;
Ax=rand(N); Ay=rand(N); Az=rand(N);
t=1;
F=zeros(3,3,N^2);
for i=1:N
for j=1:N
F(:,:,t)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)];
t=t+1; %# t is just a counter
end
end
%# then we can write
B = mat2cell(F,3,3,ones(N^2,1));
B = reshape(B,N,N)';
B = cell2mat(B);
</code></pre>
<p>Is there a faster way than this, especially when <code>N</code> is large?</p>
|
[] |
[
{
"body": "<p>There is a problem with vector multiplication in the second loop. You should transpose the second vector before doing multiplication.</p>\n\n<pre><code>F(:,:,t)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)]';\n</code></pre>\n\n<p>One of the ways to speed things up is to apply vectorization instead of two <code>for</code> loops, such as with <a href=\"http://en.wikipedia.org/wiki/Dyadic_product#Matrix_representation\" rel=\"nofollow\">Dyadics</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-21T10:10:30.527",
"Id": "7040",
"ParentId": "2817",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7040",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T04:22:15.007",
"Id": "2817",
"Score": "3",
"Tags": [
"performance",
"algorithm",
"matrix",
"matlab"
],
"Title": "Creating a matrix from a dyadic product"
}
|
2817
|
<p>The C in CRUD Silverlight:</p>
<ul>
<li>Create new Silverlight business application "CRUD"</li>
<li>Add ADO.NET Entity Data Model to CRUD.web</li>
<li>Select the db, the tables, build the project</li>
<li>Add Domain Service Class to CRUD.web</li>
<li>Select the tables and also select the allow editing option for the table "tname"</li>
<li>Build the project</li>
<li>Keep two textboxes "ID" and "NAME" on MainPage.xaml</li>
<li>Keep a button "SAVE NEW RECORD" on MainPage.xaml</li>
<li>Build</li>
<li><p>Add the following code</p>
<pre><code>Partial Public Class MainPage
Inherits UserControl
Dim dserv As New DomainService1
//default methods generated
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
'declare a table object
Dim table As New tname
'assign values to fields
table.ID = TextBox1.Text
table.NAME = TextBox2.Text
'add table object entity
dserv.tnames.Add(table)
'submit the changes, to make it permenant in the db
dserv.SubmitChanges()
End Sub
</code></pre></li>
<li><p>Record inserted</p></li>
</ul>
<p>Is this the easiest way for having no side effects to add a new record? Is this the optimal way to add a new record?</p>
|
[] |
[
{
"body": "<p>I don't think it's best-practice to put any logic that isn't strictly presentation-specific directly into a code-behind event handler like this, let alone that a <code>UserControl</code> knows anything about any <code>DomainService1</code> object.</p>\n\n<p>If you're shooting for best-practices, you need to look into the <em>Model-View-ViewModel</em> pattern; it's not the job of any UI component to perform any kind of business or data logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T14:26:02.760",
"Id": "58131",
"Score": "0",
"body": "Seems like the OP is more looking for what's **easiest** though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T15:39:06.497",
"Id": "58140",
"Score": "0",
"body": "@Simon true, but the post is also tagged [best-practices]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T15:47:05.010",
"Id": "58142",
"Score": "0",
"body": "That's true, I would give you an upvote but I'm out of them for the time being (as usual)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T01:33:47.880",
"Id": "35463",
"ParentId": "2824",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T17:17:17.643",
"Id": "2824",
"Score": "3",
"Tags": [
".net",
"vb.net",
"silverlight",
"crud"
],
"Title": "C in CRUD for Silverlight"
}
|
2824
|
<p>This is the way I'm currently getting data from XML, but it seems to be really inefficient, checking every localname in every iteration. How should I be doing it?</p>
<p>Here is a sample of the XML I am trying to parse, followed by my code.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<hash>
<result>
<properties type="array">
<property>
<last-account-review-at>2011-04-26 00:00:04</last-account-review-at>
<unit-balance type="integer">-104</unit-balance>
<daily-consumption type="decimal">10.8</daily-consumption>
<status>active</status>
<end-date></end-date>
<icp-number>0001234567RN602</icp-number>
<address>
<property-name nil="true"></property-name>
<flat-number>3</flat-number>
<suburb>Suburbia</suburb>
<street-number>21</street-number>
<region>Nether</region>
<street-name>Easy</street-name>
<district>Metropolis</district>
</address>
<start-date>2010-05-05</start-date>
<status-detail nil="true"></status-detail>
</property>
</properties>
<account-number>9001234567</account-number>
</result>
<version>1.0</version>
</hash>
</code></pre>
<p>I don't have any issues with the maintainability of my code, it's more that it seems like I shouldn't be comparing against so many things at every iteration.</p>
<pre><code>public static class DataRetrieval
{
private static XmlNameTable _nt;
private static object _propertyElement;
private static object _unitBalanceElement;
private static object _dailyConsumptionElement;
private static object _statusElement;
static DataRetrieval()
{
_nt = new NameTable();
_propertyElement = _nt.Add("property");
_unitBalanceElement = _nt.Add("unit-balance");
_dailyConsumptionElement = _nt.Add("daily-consumption");
_statusElement = _nt.Add("status");
}
public static bool ParseCustomerData(string raw, out List<PropertyDetails> properties)
{
bool parsedOK = false;
properties = new List<PropertyDetails>();
PropertyDetails property = null;
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
settings.NameTable = _nt;
XmlReader reader = XmlReader.Create(new StringReader(raw), settings);
object localname;
bool continueReading = true;
int dataItemsRead = 0;
const int DataItemsToRead = 3;
try
{
while (continueReading)
{
if (reader.IsStartElement())
{
localname = reader.LocalName;
if (localname == _propertyElement)
{
if (property != null)
{
if (dataItemsRead == DataItemsToRead)
{
properties.Add(property);
dataItemsRead = 0;
}
else
{
break;
}
}
property = new PropertyDetails();
continueReading = reader.Read();
}
else if (localname == _unitBalanceElement)
{
property.UnitBalance = reader.ReadElementContentAsInt();
dataItemsRead++;
}
else if (localname == _dailyConsumptionElement)
{
property.DailyConsumption = reader.ReadElementContentAsDouble();
dataItemsRead++;
}
else if (localname == _statusElement)
{
if (property.SetStatus(reader.ReadElementContentAsString()))
{
dataItemsRead++;
}
}
else
{
continueReading = reader.Read();
}
}
else
{
continueReading = reader.Read();
}
}
}
catch (XmlException e)
{
Debug.WriteLine("XmlException: {0}", e.Message);
}
parsedOK = dataItemsRead == DataItemsToRead;
if ((property != null) && (parsedOK))
{
properties.Add(property);
}
return parsedOK;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You could try using <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx\" rel=\"noreferrer\"><code>XDocument</code></a> instead. </p>\n\n<p>It would also help to see an example of the <code>xml</code> you're trying to parse in order to properly suggest a refactoring of your code. </p>\n\n<p>EDIT:<br>\nYou could do this (<code>XDocument</code> + <code>LINQ</code>): </p>\n\n<pre><code>string sXml = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\"?>\n <hash>\n <result>\n <properties type=\"\"array\"\">\n <property>\n <last-account-review-at>2011-04-26 00:00:04</last-account-review-at>\n <unit-balance type=\"\"integer\"\">-104</unit-balance>\n <daily-consumption type=\"\"decimal\"\">10.8</daily-consumption>\n <status>active</status>\n <end-date></end-date>\n <icp-number>0001234567RN602</icp-number>\n <address>\n <property-name nil=\"\"true\"\"></property-name>\n <flat-number>3</flat-number>\n <suburb>Suburbia</suburb>\n <street-number>21</street-number>\n <region>Nether</region>\n <street-name>Easy</street-name>\n <district>Metropolis</district>\n </address>\n <start-date>2010-05-05</start-date>\n <status-detail nil=\"\"true\"\"></status-detail>\n </property>\n </properties>\n <account-number>9001234567</account-number>\n </result>\n <version>1.0</version>\n </hash>\";\n\nvar xml = XDocument.Parse(sXml);\n\nvar r = from x in xml.Descendants(\"property\")\n select new \n {\n unitBalance = x.Element(\"unit-balance\").Value,\n dailyConsumption = x.Element(\"daily-consumption\").Value,\n status = x.Element(\"status\").Value\n };\n\nthis._propertyElement = xml.Descendants(\"property\");\nthis._unitBalanceElement = r.ElementAt(0).unitBalance;\nthis._dailyConsumptionElement = r.ElementAt(0).dailyConsumption;\nthis._statusElement = r.ElementAt(0).status;\n</code></pre>\n\n<p><em><strong>Note: I didn't include any error checking, just wanted to show some possibilities.</em></strong> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-10T09:16:49.500",
"Id": "4463",
"Score": "0",
"body": "Personally i love XDocument with linq it provides cleaner and better options."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T00:34:02.807",
"Id": "2828",
"ParentId": "2826",
"Score": "8"
}
},
{
"body": "<p>Have a look at </p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/fr-fr/library/bb387065.aspx\" rel=\"nofollow\">Linq to XML</a> (MSDN)</p>\n</blockquote>\n\n<p>The venerable <a href=\"http://weblogs.asp.net/scottgu/default.aspx\" rel=\"nofollow\">Scott Gu</a> has a nice piece of Linq to XML <a href=\"http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx\" rel=\"nofollow\">here</a>. That should help get you started!</p>\n\n<p>Using Linq to XML should definately make your code easier to read and maintain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T01:48:01.943",
"Id": "2829",
"ParentId": "2826",
"Score": "8"
}
},
{
"body": "<p>If your'e dealing with a given scheme definition in .xsd you can use the <a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s%28v=VS.100%29.aspx\" rel=\"nofollow\">xsd.exe tool</a> to generate matching classes. Using those generated classes provides type safety.\n<a href=\"http://www.codingday.com/xml-c-class-generator-for-c-using-xsd-for-deserialization/\" rel=\"nofollow\">Here</a> you can find an easy example.</p>\n\n<p>If you don't like xsd.exe <a href=\"http://xsd2code.codeplex.com/\" rel=\"nofollow\">xsd2code</a> is another alternative for code generation. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T15:30:09.217",
"Id": "2833",
"ParentId": "2826",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T23:52:26.673",
"Id": "2826",
"Score": "4",
"Tags": [
"c#",
"xml"
],
"Title": "There has to be a better way of parsing XML in C# than what I'm doing"
}
|
2826
|
<p>I know that getopts is available but I wanted to write my own as a way of improving my bash. Below I show two function definitions and an example of the use of them in a bash script. Finally I show the output of the script.</p>
<p>Please comment.</p>
<pre><code>#!/bin/bash
# Produce a string variable which can be used by function isoption
# to give calling scripts an easy way to determine what options are
# are provided in its command line regardless of their order.
# Call this function as:
#
# mygetopts "$@"
#
# Non-option arguments in the command line of the caller are
# passed back to the caller in array NONOPTARGS and can be used like this:
#
# name=NONOPTARGS[0]
#
# NOTE: Option globbing is not allowed
function mygetopts ()
{
# Initialize a string variable which will be made to contain all
# option names in "$@". Since this string will be used by function
# isoption a weird variable name is used to avoid collision with
# variable names in calling script since it cannot be made local.
O1P2T3I4O5N6="-" # O1P2T3I4O5N6 is avaiable to caller
declare -i i=0 # i is local to function
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
echo "Usage: $0 \"\$@\"" >&2
return 1
fi
for arg in "$@" ; do # arg will be each positional parameter
if [[ ${arg:0:1} == - ]] # if $arg begins with -
# Pack all option names separated by -
then O1P2T3I4O5N6=${O1P2T3I4O5N6}${arg:1}-
else NONOPTARGS[i++]=$arg
fi
#echo "O1P2T3I4O5N6 =$O1P2T3I4O5N6"
#echo "NONOPTARGS = ${NONOPTARGS[@]}"
done
return 0
}
function isoption ()
{
if [[ $O1P2T3I4O5N6 =~ ^.*-${1}-.*$ ]]
then return 0
else return 1
fi
}
</code></pre>
<pre><code>#!/bin/bash
# Example of using functions mygetopts and isoption to provide easy
# access to all command line options as well as non-option arguments
# regardless of their order.
#
# To use these functions place the file MYFUNCTIONS in your $HOME
# directory and source it in your bash script before using the
# functions. Alternately it can be sourced by your .bash_profile
set +vx # Change + to - to enable tracing
echo
echo These $# command line arguments are provided:
echo "$@"
. ~/MYFUNCTIONS # source the function definitions
echo
echo These functions are defined:
compgen -A function # Show what functions are defined
echo
mygetopts "$@" # Call mygetopts with all command line arguments
echo mygetopts returns this string with all options separated by -
echo O1P2T3I4O5N6 = $O1P2T3I4O5N6 # Show the string of all options
echo Examples of the use of isoption function:
if isoption f; then echo f found ; else echo f Not found; fi
if isoption z; then echo z found ; else echo z Not found; fi
if isoption abcd; then echo abcd found ; else echo abcd Not found; fi
if isoption abcde; then echo abcde found ; else echo abcde Not found; fi
echo
echo Examples of the accessing of non-option arguments:
inputfilename=${NONOPTARGS[0]}
outputfilename=${NONOPTARGS[1]}
echo inputfilename=$inputfilename
echo outputfilename=$outputfilename
</code></pre>
<pre><code>***13:00:47 617 ~/work>testmygetopts -bde -f infile -abcd -x outfile -y
</code></pre>
<p>These 7 command line arguments are provided:</p>
<p>-bde -f infile -abcd -x outfile -y</p>
<p>These functions are defined:</p>
<ul>
<li><code>isoption</code></li>
<li><code>mygetopts</code></li>
</ul>
<p><code>mygetopts</code> returns this string with all options separated by -</p>
<pre><code>O1P2T3I4O5N6 = -bde-f-abcd-x-y-
</code></pre>
<p>Examples of the use of isoption function:</p>
<pre><code>f found
z Not found
abcd found
abcde Not found
</code></pre>
<p>Examples of the accessing of non-option arguments:</p>
<pre><code>inputfilename=infile
outputfilename=outfile
</code></pre>
|
[] |
[
{
"body": "<p>The bash code all looks reasonably fine to me.</p>\n\n<p>The -h and --help output doesn't look right (it will print the actual parameters passed, but should print the list of allowable options/parameters?)</p>\n\n<p>Options like --this-will-break won't work with --will or --break.</p>\n\n<p>I'm not clear if parameters with spaces in them will work, as in: testmygetopts \"this is one argument\"</p>\n\n<p>I think 'isoption' could be simplifed to just be the [[ ]] expression (since it will return 0 or 1 already).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-27T09:24:26.743",
"Id": "5012",
"ParentId": "2827",
"Score": "3"
}
},
{
"body": "<p>…</p>\n\n<pre><code>declare -i i=0 # i is local to function\n</code></pre>\n\n<p>Inside a function <code>declare</code> and <code>local</code> do the same thing, but if you're going to write a code comment saying it's local, don't you think the <code>local</code> keyword is more self-documenting? I'd write it…</p>\n\n<pre><code>local -i i=0\n\nif [[ \"$1\" == \"-h\" || \"$1\" == \"--help\" ]]; then\n</code></pre>\n\n<p>…</p>\n\n<p>This is fine, but you don't actually need double quotes inside a double-bracket test. You don't need the double-equals either. That's up to you.</p>\n\n<pre><code>echo \"Usage: $0 \\\"\\$@\\\"\" >&2\n</code></pre>\n\n<p>Use <code>printf</code> and single quotes for better readability. You immediately know the <code>\"$@\"</code> won't expand in single quotes, and the <code>\"$0\"</code> gets expanded before <code>printf</code> interpolates it.</p>\n\n<pre><code>printf 'Usage: %s \"$@\"\\n' \"$0\" >&2\n</code></pre>\n\n<p>…</p>\n\n<pre><code>for arg in \"$@\" ; do # arg will be each positional parameter\n</code></pre>\n\n<p>Same as <code>for arg</code> without the <code>in \"$@\"</code> part. Up to you.</p>\n\n<pre><code>if [[ ${arg:0:1} == - ]] # if $arg begins with -\n</code></pre>\n\n<p>More efficiently written:</p>\n\n<pre><code>if [[ $arg = -* ]]\n</code></pre>\n\n<p>…</p>\n\n<pre><code>function isoption ()\n{\n\n if [[ $O1P2T3I4O5N6 =~ ^.*-${1}-.*$ ]] \n then return 0\n else return 1 \n fi\n}\n</code></pre>\n\n<p>A nice bash feature is that return always returns the value of $?, so you could write this:</p>\n\n<pre><code>[[ $O1P2T3I4O5N6 =~ ^.*-${1}-.*$ ]]\nreturn\n</code></pre>\n\n<p>But if you prefer explicit, your code is fine.</p>\n\n<hr>\n\n<p><strong>On to the example part:</strong></p>\n\n<pre><code>echo\necho These $# command line arguments are provided: \necho \"$@\"\n</code></pre>\n\n<p>This use of echo is the only thing I think it actually wrong. Echo <em>takes</em> options (-neE), so you should never give it an unsanitized <code>\"$@\"</code> to output. Use <code>printf</code> here.</p>\n\n<pre><code>printf '%s ' \"$@\"; echo\n</code></pre>\n\n<p>And the rest is fine. Very nice job!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T14:08:32.807",
"Id": "6312",
"ParentId": "2827",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-05T23:54:20.767",
"Id": "2827",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Functions for scanning command line options"
}
|
2827
|
<p>Is there anything wrong with this implementation of Queue with array?</p>
<p>I have started front = rear = -1. </p>
<p>Some references tend to start front = 0 like this:<a href="http://hamilton.bell.ac.uk/swdev2/notes/notes_13.pdf" rel="nofollow">enter link description here</a></p>
<p>I think if front starts with 0, the source code becomes cumbersome.</p>
<pre><code>#include <stdio.h>
#include<ctype.h>
#define SIZE 5
int queue[SIZE] = {0};
int front = -1;
int rear = -1;
void PrintQueue()
{
int i=0;
if(!IsEmpty())
{
for(i=front+1 ; i<=rear ; i++)
{
printf("%d, ", queue[i]);
}
printf("\n");
}
else
{
printf("Queue is empty.\n");
}
}
int IsEmpty()
{
if(front==rear)
{
front = rear = -1;
return 1;
}
else
{
return 0;
}
}
void Enque(int value)
{
if(rear<SIZE-1)
{
++rear;
queue[rear] = value;
}
else
{
printf("Queue overflow!\n");
}
}
int Dequeue()
{
int ret = 0;
if(!IsEmpty())
{
++front;
ret = queue[front];
}
else
{
printf("Queue underflow!\n");
ret = -99;
}
return ret;
}
main()
{
int value = 0;
int menu = 0;
while(1)
{
printf("Menu\n");
printf("--------\n");
printf("1. Enque\n");
printf("2. Deque\n");
printf("3. IsEmpty\n");
printf("4. Print\n");
printf("5. Clrscr\n");
printf("6. Exit\n");
scanf(" %d", &menu);
switch(menu)
{
case 1:
printf("Enter an element : ");
scanf(" %d", &value);
Enque(value);
break;
case 2:
printf("Dequed, %d.\n", Dequeue());
break;
case 3:
if(IsEmpty())printf("Queue is empty.\n");
else printf("Que has some values.\n");
break;
case 4:
PrintQueue();
break;
case 5:
system("cls");
break;
case 6:
exit(0);
break;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T09:05:19.977",
"Id": "4369",
"Score": "1",
"body": "**Enqueue** and **Dequeue**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T13:54:42.250",
"Id": "4370",
"Score": "0",
"body": "COULD NOT UNDERSTAND!"
}
] |
[
{
"body": "<p>Most implementations of a Queue use <code>front</code> to point to the head element of the queue and <code>rear</code> to point to the first empty element at the rear of the queue:</p>\n\n<pre><code>front rear\nv v\n[1][2][3][4][ ][ ]\n</code></pre>\n\n<p>Your implementation has them pointing one element previous.</p>\n\n<p>To change your code to work like this would be a matter of change front/rear to start at 0 and then reversing your increment/read:</p>\n\n<pre><code>void Enqueue(int value)\n{\n if(rear<SIZE-1)\n {\n queue[rear] = value;\n ++rear;\n }\n else\n {\n printf(\"Queue overflow!\\n\");\n }\n}\n</code></pre>\n\n<p>Review:</p>\n\n<p>Your <code>IsEmpty</code> function has the side effect of resetting the queue. The name does not reflect this; it sounds like it should be merely checking whether the queue is empty. There's not really anything wrong with that. Pragmatically, such an operation should be transparent. However, I'd put a comment in there describing the side effect.</p>\n\n<p>You could also implement a <a href=\"http://en.wikipedia.org/wiki/Circular_queue\" rel=\"nofollow\">circularly linked queue</a> in which you insert elements in a (conceptual) ring. Basically, when you get to the end of the array, you start inserting at the begining again. However, this means that when <code>front = back</code> the buffer could be full <em>or</em> empty. Just check <code>rear + 1</code> to see if it's empty.</p>\n\n<p>Oh, and <em>please</em> spell \"queue\" and its varients correctly...it's really bugging me :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T13:59:10.723",
"Id": "2832",
"ParentId": "2831",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "2832",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T07:13:41.457",
"Id": "2831",
"Score": "2",
"Tags": [
"c",
"array",
"queue"
],
"Title": "What value the rear and front counter of an Array implementation of Queue start with? -1 or 0 or 1?"
}
|
2831
|
<p>Please make some comment about this code of QuickSort.</p>
<p>My code is based on the example shown in <a href="http://rads.stackoverflow.com/amzn/click/0070380015" rel="nofollow">this book</a>.</p>
<pre><code>#include <stdio.h>
#include <conio.h>
#include <math.h>
#define SIZE 12
struct StackItem
{
int StartIndex;
int EndIndex;
};
struct StackItem myStack[SIZE * SIZE];
int stackPointer = 0;
int myArray[SIZE] = {11,44,33,55,77,90,40,60,99,22,88,66};
void Push(struct StackItem item)
{
myStack[stackPointer] = item;
stackPointer++;
}
struct StackItem Pop()
{
stackPointer--;
return myStack[stackPointer];
}
int StackHasItem()
{
if(stackPointer>0)
{
return 1;
}
else
{
return 0;
}
}
void ShowStack()
{
int i =0;
printf("\n");
for(i=0; i<stackPointer ; i++)
{
printf("(%d, %d), ", myStack[i].StartIndex, myStack[i].EndIndex);
}
printf("\n");
}
void ShowArray()
{
int i=0;
printf("\n");
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", myArray[i]);
}
printf("\n");
}
void Swap(int * a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int Scan(int *startIndex, int *endIndex)
{
int partition = 0;
int i = 0;
if(*startIndex > *endIndex)
{
for(i=*startIndex ; i>=*endIndex ; i--)
{
if(myArray[i]<myArray[*endIndex])
{
Swap(&myArray[i], &myArray[*endIndex]);
*startIndex = *endIndex;
*endIndex = i;
partition = i;
break;
}
if(i==*endIndex)
{
*startIndex = *endIndex;
*endIndex = i;
partition = i;
}
}
}
else if(*startIndex < *endIndex)
{
for(i=*startIndex ; i<=*endIndex ; i++)
{
if(myArray[i]>myArray[*endIndex])
{
Swap(&myArray[i], &myArray[*endIndex]);
*startIndex = *endIndex;
*endIndex = i;
partition = i;
break;
}
if(i==*endIndex)
{
*startIndex = *endIndex;
*endIndex = i;
partition = i;
}
}
}
return partition;
}
int GetFinalPosition(struct StackItem item1)
{
struct StackItem item = {0};
int StartIndex = item1.StartIndex ;
int EndIndex = item1.EndIndex;
int PivotIndex = -99;
while(StartIndex != EndIndex)
{
PivotIndex = Scan(&EndIndex, &StartIndex);
printf("\n");
}
return PivotIndex;
}
void QuickSort()
{
int splitPoint = 0;
struct StackItem item;
struct StackItem item1={0};
struct StackItem item2={0};
item.StartIndex = 0;
item.EndIndex = SIZE-1;
Push(item);
while(StackHasItem())
{
item = Pop();
splitPoint = GetFinalPosition(item);
if(splitPoint>=0 && splitPoint<=(SIZE-1))
{
if(item.StartIndex <= (splitPoint-1))
{
item1.StartIndex = item.StartIndex;
item1.EndIndex = splitPoint-1;
Push(item1);
}
if((splitPoint+1) <= item.EndIndex)
{
item2.StartIndex = splitPoint+1;
item2.EndIndex = item.EndIndex;
Push(item2);
}
}
}
}
main()
{
ShowArray();
QuickSort();
ShowArray();
}
</code></pre>
|
[] |
[
{
"body": "<p>You've implemented your own stack. C has a perfectly good stack, so don't make your own. Use recursive functions.</p>\n\n<p>\"Scan\" means to look for something, but you modify the list while scanning. Its not a good name for the function</p>\n\n<p>\"GetFinalPosition\" begins with Get which usually indicates the the function doesn't modify anything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-11T16:05:58.830",
"Id": "4475",
"Score": "0",
"body": "Not sure I'd agree with the recursive function advice - the stack size may be limited and this will produce an arbitrary upper limit on the number of items that can be sorted, and a failure mode that's difficult to guard against."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-11T18:18:12.620",
"Id": "4477",
"Score": "0",
"body": "@Paul R, I see your point. However, for a production quicksort the best strategy is to bail out to another sort algorithm if pathological behavior is detected. At that point, the data you are sorting would have to be too large to fit into memory. Then you have other issues to worry about."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T02:34:44.327",
"Id": "2839",
"ParentId": "2834",
"Score": "4"
}
},
{
"body": "<p>This doesn't look like any quicksort I'd know -- the logic's so convoluted I'm surprised it works at all. I would recommend taking a look at <a href=\"https://codereview.stackexchange.com/questions/1259/quicksort-application\">this question</a> since it covers the same topic as yours.</p>\n\n<p>I would suggest implementing this exercise in a recursive fashion first since it's typically easier than its iterative counterpart.</p>\n\n<p>As Winston already mentioned, the function names you chose does not correctly reflect what that function is really doing. Go through each of your functions and try to come up with a description that accurately describes what it is trying to do. If you have to use the conjuction 'and' in that description then that function probably has too many responsibilities.</p>\n\n<p>Here are some guiding questions to help you critique your own code:</p>\n\n<ul>\n<li>Are there any duplicate code present? This includes copy-and-pasted code with special tweaks to get the desired behavior.</li>\n<li>What are the preconditions, postconditions and invariants assumed for each of your functions above?</li>\n<li>How many things are each of your functions doing? List and enumerate them.</li>\n<li>Are those things related or unrelated to each other?</li>\n<li>Does the function name reflect that?</li>\n<li>Your <code>push()</code> and <code>pop()</code> manipulates the number of elements on the statically allocated stack. What happens if you push and pop beyond the minimum/maximum range permissible?(This is related to point #2)</li>\n</ul>\n\n<p>Lastly, the book that you linked is quite old if the reviews are any indication(published in 1986). <a href=\"https://stackoverflow.com/questions/741012/is-the-c-programming-language-book-current\">TCPL</a> is the usual recommended source for learning C programming.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T03:08:06.267",
"Id": "2840",
"ParentId": "2834",
"Score": "4"
}
},
{
"body": "<p>In addition to what the others said: I'd dump the <code>#include <conio.h></code> as it is not platform independent and not needed either (like <code>math.h</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T15:16:46.077",
"Id": "2853",
"ParentId": "2834",
"Score": "4"
}
},
{
"body": "<p>Your test harness (main(), ShowArray(), etc) should be in its own module.</p>\n\n<p>The QuickSort() function implementation should be in a separate .c file with the interface defined in a corresponding .h file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-11T16:08:19.437",
"Id": "2915",
"ParentId": "2834",
"Score": "0"
}
},
{
"body": "<p>You want us to make comments about your code, but I think what your code needs are comments. </p>\n\n<pre><code>/* comment */\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-12T08:38:31.967",
"Id": "2921",
"ParentId": "2834",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T16:48:55.543",
"Id": "2834",
"Score": "1",
"Tags": [
"c",
"quick-sort"
],
"Title": "C: QuickSort following the book \"Schaum's Outlines\""
}
|
2834
|
<p>I have over 300 questions that I plan to include in the program. The flow is pretty much like this:</p>
<ul>
<li>Create a window with the question</li>
<li>Store answer in variable</li>
<li>Create NEW window with question</li>
<li>Store NEW answer</li>
</ul>
<p>(This continues on for over 300 questions.)</p>
<p>I have 2 questions:</p>
<ol>
<li>Will this eventually lead to a crash since I'm creating so many windows?</li>
<li>Everything works with this code if you select 'Yes' to the second question (A2) but it does not work if you select 'No'. Can you please see if you can find what's wrong with it?</li>
</ol>
<pre><code>import wx
a1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',
"Don't remember", 'None of the above']
a2 = ['No', 'Yes']
a4 = ['No', 'Yes']
class Fruit(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))
#create panel and button
panel = wx.Panel(self)
# B1 - create multiple choice list
box = wx.MultiChoiceDialog(None, """
A1. What kind of fruit did you buy at the store?""", 'Fruit', a1)
if box.ShowModal() == wx.ID_OK:
a_1 = box.GetSelections()
print (a_1, '\n')
# A2 - create single choice list
box = wx.SingleChoiceDialog(None, """
A2. Do you like eating fruit?
""", 'Fruit', a2)
if box.ShowModal() == wx.ID_OK:
a_2 = box.GetStringSelection()
print (a_2, '\n')
if a_2 == 'Yes':
box = wx.TextEntryDialog(None, "A3. What kind of fruit is your favorite? ", "Fruit", "")
if box.ShowModal() == wx.ID_OK:
a_3 = box.GetValue()
print (a_3, '\n')
box = wx.SingleChoiceDialog(None, """
A4. Did you eat the fruit that you bought?
""", 'Fruit', a4)
if box.ShowModal() == wx.ID_OK:
a_4 = box.GetStringSelection()
print (a_4, '\n')
</code></pre>
|
[] |
[
{
"body": "<pre><code>import wx\n\na1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',\n \"Don't remember\", 'None of the above']\n\na2 = ['No', 'Yes']\n\na4 = ['No', 'Yes']\n</code></pre>\n\n<p>The Python style guide recommend ALL_CAPS for global constants.</p>\n\n<pre><code>class Fruit(wx.Frame):\n\n def __init__(self, parent, id):\n wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))\n\n #create panel and button\n panel = wx.Panel(self)\n\n # B1 - create multiple choice list\n box = wx.MultiChoiceDialog(None, \"\"\"\n\nA1. What kind of fruit did you buy at the store?\"\"\", 'Fruit', a1)\n</code></pre>\n\n<p>When strings get long enough that they force breaking across multiple lines, its usually best to move them to global constants</p>\n\n<pre><code> if box.ShowModal() == wx.ID_OK:\n a_1 = box.GetSelections()\n\n\n print (a_1, '\\n')\n</code></pre>\n\n<p>I don't think this does what you think it does. For python 2.x (which unless wxPython has been ported to python 3.x recently, must be what you are using), you shouldn't put parenthesis around your print statements. </p>\n\n<pre><code> # A2 - create single choice list\n box = wx.SingleChoiceDialog(None, \"\"\"\nA2. Do you like eating fruit?\n\"\"\", 'Fruit', a2)\n if box.ShowModal() == wx.ID_OK:\n a_2 = box.GetStringSelection()\n\n print (a_2, '\\n')\n\n if a_2 == 'Yes':\n box = wx.TextEntryDialog(None, \"A3. What kind of fruit is your favorite? \", \"Fruit\", \"\")\n if box.ShowModal() == wx.ID_OK:\n</code></pre>\n\n<p>If the answer to the previous question was \"Yes\", then box is now the result of asking question A3. However, otherwise its the still the previous question. As a result, it'll ask the same question again. You probably want to indent this if block so that it only happens if a_2 was Yes.</p>\n\n<pre><code> a_3 = box.GetValue()\n\n\n print (a_3, '\\n')\n\n\n box = wx.SingleChoiceDialog(None, \"\"\"\nA4. Did you eat the fruit that you bought?\n\"\"\", 'Fruit', a4)\n if box.ShowModal() == wx.ID_OK:\n a_4 = box.GetStringSelection()\n\n print (a_4, '\\n')\n</code></pre>\n\n<p>As for your questions:</p>\n\n<ol>\n<li>You can probably get away with creating that many windows. However, you can make sure that a dialog gets destroyed by calling its Destroy() method. </li>\n<li>I explained above what was wrong with your logic.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T23:25:49.843",
"Id": "4372",
"Score": "0",
"body": "Thank you. So basically I need to change a1 to A1, and maybe create another module with all of the questions and answers and just import it to keep my code clean? Anyways, thanks for taking the time to give me a detailed answer. For some reason I keep having trouble with the indented blocks so I will try to check that next time when something goes wrong. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T23:45:36.750",
"Id": "4373",
"Score": "0",
"body": "@Jerry, if you elaborate on what you plan on doing with the answers I can suggest the best way to structure that part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T23:48:52.667",
"Id": "4374",
"Score": "0",
"body": "Hey Winston, after the answers are all entered, I will be attempting to use pyodbc to write them to an MS Access Database. Hopefully it won't be too hard, but I am already finding your approach much easier than mine :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T01:12:45.893",
"Id": "4376",
"Score": "0",
"body": "@Jerry, basically, what I think should happen is to make a list of all questions that you can then just process in a for loop. There is some trickiness in doing that, but its probably the best way."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T23:17:00.447",
"Id": "2838",
"ParentId": "2837",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-06T22:36:17.373",
"Id": "2837",
"Score": "2",
"Tags": [
"python",
"wxpython"
],
"Title": "Questionnaire program using many wxPython windows"
}
|
2837
|
<p>I was thinking of building a F/OSS project as a cPanel for Ubuntu Server, since Ubuntu doesn't have this, and yet making it easy for a hosting company to use this, where users will find it just as intuitive as cPanel.</p>
<p>Trouble is, PHP web pages on Ubuntu run as <code>www-data</code>, and lots of senior PHP guys recommend <strong>not</strong> running a PHP page as <code>root</code>, and <strong>not</strong> shelling out and running a Bash script that may have a sticky bit applied on its permissions. They say <em>that's a way to get hacked</em>.</p>
<p>It then dawned on me how to get around this. Make a Bash script daemon in <code>/etc/init.d</code> that watches a named pipe connection, sitting in a loop. The loop will hang, but that's perfectly okay because it will be in the background, and in a sense it means that the script is dormant and not soaking up CPU cycles. That's cool! It's certainly better than a sleep loop, and means the process only wakes up when there's something that needs to be processed. The sleep loop technique, on the other hand, may be checking for PHP communication when there may not be any, and so the sleep loop soaks up unnecessary CPU. That's why I like the pipe-wait-loop strategy.</p>
<p>So, then all the PHP page has to do is do normal file I/O to like <code>/tmp/pipe</code> (my pipe, for instance) and the Bash script daemon in the background will wake up out of dormancy in that loop, and process a command as root. It can look in a database for new things it needs to do, and then do those tasks. When done, it can return values to the database and the PHP page can wait in a jQuery/AJAX loop until it receives a response back.</p>
<p>Because the PHP page doesn't actually compose the root commands it needs to run, and merely writes some records to a database table, and sends a string of <code>"run"</code> to the pipe, it safely passes on a request to the secure daemon in the background.</p>
<p>What do you think of this IPC technique? Good? Bad?</p>
<p>BTW, my demo <code>/usr/sbin/foo</code> command looks like this. Its point is to demonstrate that <code>/tmp/foo-was-here</code> was created by the root user account, triggered by a PHP page. It's just the start of something bigger.</p>
<pre><code>#!/bin/bash
if [ ! -f /tmp/foo ]; then
mkfifo /tmp/foo
fi
while true; do
cat /tmp/foo;
touch '/tmp/foo-was-here';
done
</code></pre>
|
[] |
[
{
"body": "<p>I'd say: go run a <a href=\"http://www.php.net/gearman\" rel=\"nofollow\">gearman</a> daemon as the correct user, and set some gearman workers as priviliged users up with something like <a href=\"http://www.supervisord.org\" rel=\"nofollow\">supervisord</a>. Both are in the Debian packages, so I assume they'll be in the Ubuntu packages also....</p>\n\n<p>Do set up gearman with a maximum number of tries, or you could encounter a Poison Message problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T00:49:47.060",
"Id": "2863",
"ParentId": "2841",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T05:01:48.173",
"Id": "2841",
"Score": "2",
"Tags": [
"php",
"security",
"bash",
"shell"
],
"Title": "Concept for PHP Controlled, Privileged Execution (for a cPanel knockoff on Ubuntu Server)"
}
|
2841
|
<p>I found a example of Java PostMethod <a href="http://www.java2s.com/Code/Java/Apache-Common/HttppostmethodExample.htm">here</a>.</p>
<p>But I want to post several times by using for loop. I made it like this.</p>
<pre><code>
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PostMethodExample {
public static void main(String args[]) {
HttpClient client = new HttpClient();
client.getParams().setParameter("http.useragent", "Test Client");
BufferedReader br = null;
PostMethod method = new PostMethod("http://search.yahoo.com/search");
method.addParameter("p", "\"java2s\"");
try{
String[] parameters = { "Google", "Yahoo", "MSN" };
for (String s in parameters){
int returnCode = client.executeMethod(method);
method.addParameter("p", s);
if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
// still consume the response body
method.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String readLine;
while(((readLine = br.readLine()) != null)) {
System.err.println(readLine);
}
}
method.releaseConnection();
method = new PostMethod("http://search.yahoo.com/search");
}
} catch (Exception e) {
System.err.println(e);
} finally {
method.releaseConnection();
if(br != null) try { br.close(); } catch (Exception fe) {}
}
}
}
</code></pre>
<p>I modified code just inside of <code>try</code> block. I don't think this is the best way. Help me to improve this code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T18:19:46.767",
"Id": "4398",
"Score": "4",
"body": "for (String s in parameters)? Is it supposed to compile? And don't swallow exceptions, report them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-19T20:58:59.287",
"Id": "16170",
"Score": "4",
"body": "While `System.err.println(e)` isn't really swallowing an exception, it's not really reporting it properly either. If you must print somewhere instead of logging, at least use `e.printStackTrace()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-19T21:03:08.597",
"Id": "16171",
"Score": "0",
"body": "I don't think you want to modify the inside of the `try` block, as you've effectively prevented the finally block from releasing each connection you're attempting."
}
] |
[
{
"body": "<p>I think this pattern of creating an instance, running it through the loop, and at the end of the loop re-initializing it, is a bad one. This case is a good example of what can go wrong... because you have introduced a bug as a result</p>\n\n<p>The first time through the loop your <code>method</code> is configured as:</p>\n\n<pre><code>PostMethod method = new PostMethod(\"http://search.yahoo.com/search\");\nmethod.addParameter(\"p\", \"\\\"java2s\\\"\");\n</code></pre>\n\n<p>but for the remaining loop iterations the <code>method</code> is simply:</p>\n\n<pre><code>method = new PostMethod(\"http://search.yahoo.com/search\");\n</code></pre>\n\n<p>Similarly, another bug that has 'creeped' (crept?) in is you change the 'p' parameter <strong>after</strong> the request is posted....</p>\n\n<pre><code>int returnCode = client.executeMethod(method);\nmethod.addParameter(\"p\", s);\n</code></pre>\n\n<p>There is no reason, in this case, why you can't initialize the <code>method</code> inside the loop, it makes more sense, and you eliminate bugs....:</p>\n\n<pre><code>for (String s in parameters){\n\n final PostMethod method = new PostMethod(\"http://search.yahoo.com/search\");\n method.addParameter(\"p\", s);\n int returnCode = client.executeMethod(method);\n\n ....\n\n method.releaseConnection();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T14:28:00.807",
"Id": "35836",
"ParentId": "2842",
"Score": "5"
}
},
{
"body": "<p><strong>Avoid catching all exceptions</strong></p>\n\n<p>Do not use <code>catch (Exception e)</code> as this will also catch <code>NullPointerException</code>, <code>ArrayIndexOutOfBoundsException</code> and a whole lot of other ones. <strong>Only catch the Exceptions you need to catch</strong>, such as <code>IOException</code>. It is said that one should <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=27\">be specific in throws clause</a>, but that applies for <strong>catch</strong> as well.</p>\n\n<p>And as stated in the comments to your question, <code>System.err.println(e)</code> does not give full information about the exception. If you don't have a logger system nearby that can handle exceptions completely, at least use <code>e.printStackTrace();</code>. It is however recommended that you should <em>handle</em> and exception, and not only <em>report</em> it. For example by displaying a more accurate error message to the user.</p>\n\n<p>Also, I would say that your line <code>if(br != null) try { br.close(); } catch (Exception fe) {}</code> should be on multiple lines. Even if it increases line count, it improves readability.</p>\n\n<pre><code>if (br != null) {\n try {\n br.close();\n }\n catch (Exception fe) {\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T14:59:28.430",
"Id": "35841",
"ParentId": "2842",
"Score": "6"
}
},
{
"body": "<p>I find your indentation a bit strange. You have two-space indentation in one place, and eight-space in another. Keep it consistent.</p>\n\n<p>Java conventions recommend four-space indents.</p>\n\n<pre><code>public class PostMethodExample {\n\n public static void main(String args[]) {\n HttpClient client = new HttpClient();\n client.getParams().setParameter(\"http.useragent\", \"Test Client\");\n\n BufferedReader br = null;\n\n PostMethod method = new PostMethod(\"http://search.yahoo.com/search\");\n method.addParameter(\"p\", \"\\\"java2s\\\"\");\n\n try{\n String[] parameters = { \"Google\", \"Yahoo\", \"MSN\" };\n\n for (String s in parameters){\n int returnCode = client.executeMethod(method);\n method.addParameter(\"p\", s);\n if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {\n System.err.println(\"The Post method is not implemented by this URI\");\n // still consume the response body\n method.getResponseBodyAsString();\n } else {\n br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));\n String readLine;\n while(((readLine = br.readLine()) != null)) {\n System.err.println(readLine);\n }\n }\n method.releaseConnection();\n method = new PostMethod(\"http://search.yahoo.com/search\");\n }\n } catch (Exception e) {\n System.err.println(e);\n } finally {\n method.releaseConnection();\n if(br != null) try { br.close(); } catch (Exception fe) {}\n }\n }\n}\n</code></pre>\n\n<p>Also, you have places where you do:</p>\n\n<pre><code>try{\n</code></pre>\n\n<p>and places where you do:</p>\n\n<pre><code>if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {\n</code></pre>\n\n<p>Again, consistency. Always put a space before the opening brace, or never. I recommend always, as that is more readable.</p>\n\n<hr>\n\n<p>And as it was mentioned in a comment:</p>\n\n<blockquote>\n <p><code>for (String s in parameters)</code>? Is it supposed to compile?</p>\n</blockquote>\n\n<p>I don't think Java supports this kind of statement. Have you tested the code?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-15T01:44:43.543",
"Id": "113996",
"ParentId": "2842",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-07T09:07:22.910",
"Id": "2842",
"Score": "5",
"Tags": [
"java"
],
"Title": "Java using PostMethod multiple times"
}
|
2842
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.