body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've written a simple program in Python which does the following:</p>
<p><strong>Input:</strong> an integer \$n\$</p>
<p><strong>Output:</strong> a \$2^n x 2^n\$ matrix containing small \$L\$s which fill the entire matrix except one single square. Each L has its unique number, and consists of three squares.</p>
<p>It's a fairly simple program, and you can see clearly what it does by typing in a few different \$n\$s.</p>
<p><strong>What I'd like to do:</strong> Keep the actual algorithm as it is now (the <code>rec()</code> function), but improve my C-like code to make full use of Python's features.</p>
<pre><code>#!/usr/bin/env python
import sys, math
ur = [[1,0],
[1,1]]
ul = [[0,1],
[1,1]]
lr = [[1,1],
[1,0]]
ll = [[1,1],
[0,1]]
shapeCounter = 1
matrix = []
def printMatrix():
for row in matrix:
for element in row:
if(element >= 10):
print("%d" % element),
else:
print(" %d" % element),
print
print
def square(n):
global matrix
matrix = [[0]*(2**n) for x in xrange(2**n)]
matrix[0][len(matrix) - 1] = -1
rec(0, 0, len(matrix) - 1, len(matrix) - 1)
matrix[0][len(matrix) - 1] = 0
printMatrix()
def writeRect(rect, x, y):
global shapeCounter
matrix[y][x] += rect[0][0] * shapeCounter
matrix[y+1][x] += rect[1][0] * shapeCounter
matrix[y][x+1] += rect[0][1] * shapeCounter
matrix[y+1][x+1] += rect[1][1] * shapeCounter
shapeCounter += 1
def rec(sx, sy,
ex, ey):
if(ex - sx < 1 or ey - sy < 1):
return
#print("(%d,%d) (%d,%d)" %(sx,sy,ex,ey))
if(matrix[sy][sx] != 0):
rect = ul
elif(matrix[ey][sx] != 0):
rect = ll
elif(matrix[sy][ex] != 0):
rect = ur
elif(matrix[ey][ex] != 0):
rect = lr
hx = sx + (ex - sx) / 2
hy = sy + (ey - sy) / 2
writeRect(rect, hx, hy)
rec(sx, sy, hx, hy)
rec(hx + 1, sy, ex, hy)
rec(sx, hy + 1, hx, ey)
rec(hx + 1, hy + 1, ex, ey)
if __name__=='__main__':
square(int(sys.argv[1]))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T19:19:32.157",
"Id": "25795",
"Score": "1",
"body": "Get out of the habit of using global variables like that. You're just asking for trouble when you do."
}
] |
[
{
"body": "<pre><code>#!/usr/bin/env python\n\nimport sys, math\n\nur = [[1,0],\n [1,1]]\n\nul = [[0,1],\n [1,1]]\n\nlr = [[1,1],\n [1,0]]\n\nll = [[1,1],\n [0,1]]\n</code></pre>\n\n<p>Rather then creating four separate variables, I'd suggest making a list. I'd also suggest using the <code>numpy</code> library for its array type. It makes working with 2D arrays much nicer then using lists of lists.</p>\n\n<pre><code>shapeCounter = 1\n\nmatrix = []\n</code></pre>\n\n<p>Don't use global variables. Instead, pass matrix in as the parameter to the function.</p>\n\n<pre><code>def printMatrix():\n for row in matrix:\n for element in row:\n if(element >= 10):\n</code></pre>\n\n<p>Parens aren't needed here</p>\n\n<pre><code> print(\"%d\" % element),\n else:\n print(\" %d\" % element),\n print\n print\n</code></pre>\n\n<p>Note that if you used <code>numpy</code>, that library would already be able to nicely print a matrix.</p>\n\n<pre><code>def square(n):\n global matrix\n</code></pre>\n\n<p>This function should really create and return the matrix</p>\n\n<pre><code> matrix = [[0]*(2**n) for x in xrange(2**n)]\n</code></pre>\n\n<p>In numpy, this would be <code>matrix = numpy.zeros( (2**n, 2**n) )</code></p>\n\n<pre><code> matrix[0][len(matrix) - 1] = -1\n rec(0, 0, len(matrix) - 1, len(matrix) - 1)\n matrix[0][len(matrix) - 1] = 0\n printMatrix()\n</code></pre>\n\n<p>Functions that do work on your variables shouldn't print them. Your main control function should do the printing.</p>\n\n<pre><code>def writeRect(rect, x, y):\n global shapeCounter\n</code></pre>\n\n<p>This isn't a terrible use of a global, but I'd avoid it. I'd have an object this attribute was stored on.</p>\n\n<pre><code> matrix[y][x] += rect[0][0] * shapeCounter\n matrix[y+1][x] += rect[1][0] * shapeCounter\n matrix[y][x+1] += rect[0][1] * shapeCounter\n matrix[y+1][x+1] += rect[1][1] * shapeCounter\n shapeCounter += 1\n\ndef rec(sx, sy, \n ex, ey):\n</code></pre>\n\n<p>I wouldn't use abbreviations. Use <code>start_x</code>, <code>end_y</code> to make your code clearer.</p>\n\n<pre><code> if(ex - sx < 1 or ey - sy < 1):\n return\n #print(\"(%d,%d) (%d,%d)\" %(sx,sy,ex,ey))\n\n if(matrix[sy][sx] != 0):\n rect = ul\n elif(matrix[ey][sx] != 0):\n rect = ll\n elif(matrix[sy][ex] != 0):\n rect = ur\n elif(matrix[ey][ex] != 0):\n rect = lr\n</code></pre>\n\n<p>You don't need all those parens</p>\n\n<pre><code> hx = sx + (ex - sx) / 2\n hy = sy + (ey - sy) / 2\n\n writeRect(rect, hx, hy)\n\n rec(sx, sy, hx, hy)\n rec(hx + 1, sy, ex, hy)\n rec(sx, hy + 1, hx, ey)\n rec(hx + 1, hy + 1, ex, ey)\n\nif __name__=='__main__':\n square(int(sys.argv[1]))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T18:57:05.820",
"Id": "25830",
"Score": "0",
"body": "In newer versions of python, print is deprecated as a keyword and requires brackets like any other function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T19:00:49.950",
"Id": "25831",
"Score": "0",
"body": "@Aleksandar, when I said the parens are unnecessary, I'm referring to the if statement, not print."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T19:02:22.647",
"Id": "25833",
"Score": "0",
"body": "Your code view segment shows print, that's what led me to my conclusion. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T19:04:38.917",
"Id": "25835",
"Score": "0",
"body": "You'll see that may comments are always after the code they are commenting on, not before. But I might still object to the usage here for being inconsistent."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T19:52:36.120",
"Id": "15856",
"ParentId": "15852",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15856",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T19:10:37.353",
"Id": "15852",
"Score": "2",
"Tags": [
"python",
"algorithm",
"matrix"
],
"Title": "Outputting a 2^n x 2^n matrix"
}
|
15852
|
<p>I wrote this class which is a priority queue based on a numeric property of any object. As far as I can tell, the following code is working as intended. Are there any stylistic tendencies that I am getting wrong, or any gotchas I should look out for?</p>
<pre><code>//Constants
PriorityQueue.MAX_HEAP = 0;
PriorityQueue.MIN_HEAP = 1;
/**
* This is an improved Priority Queue data type implementation that can be used to sort any object type.
* It uses a technique called a binary heap.
*
* For more on binary heaps see: http://en.wikipedia.org/wiki/Binary_heap
*
* @param criteria The criteria by which to sort the objects. This should be a property of the objects you're sorting.
* @param heapType either PriorityQueue.MAX_HEAP or PriorityQueue.MIN_HEAP.
**/
function PriorityQueue(criteria,heapType) {
this.length = 0; //The current length of heap.
var queue = [];
var isMax = false;
//Constructor
if (heapType==PriorityQueue.MAX_HEAP) {
isMax = true;
} else if (heapType==PriorityQueue.MIN_HEAP) {
isMax = false;
} else {
throw heapType + " not supported.";
}
/**
* Inserts the value into the heap and sorts it.
*
* @param value The object to insert into the heap.
**/
this.insert = function(value) {
if (!value.hasOwnProperty(criteria)) {
throw "Cannot insert " + value + " because it does not have a property by the name of " + criteria + ".";
}
queue.push(value);
length++;
bubbleUp(length-1);
}
/**
* Peeks at the highest priority element.
*
* @return the highest priority element
**/
this.getHighestPriorityElement = function() {
return queue[0];
}
/**
* Removes and returns the highest priority element from the queue.
*
* @return the highest priority element
**/
this.shiftHighestPriorityElement = function() {
if (length < 0) {
throw ("There are no more elements in your priority queue.");
}
var oldRoot = queue[0];
var newRoot = _queue.pop();
length--;
queue[0] = newRoot;
swapUntilQueueIsCorrect(0);
return oldRoot;
}
var bubbleUp = function(index) {
if (index==0) {
return;
}
var parent = getParentOf(index);
if (evaluate(index,parent)) {
swap(index,parent);
bubbleUp(parent);
} else {
return;
}
}
var swapUntilQueueIsCorrect = function(value) {
left = getLeftOf(value);
right = getRightOf(value);
if (evaluate(left,value)) {
swap(value,left);
swapUntilQueueIsCorrect(left);
} else if (evaluate(right,value)) {
swap(value,right);
swapUntilQueueIsCorrect(right);
} else if (value==0) {
return;
} else {
swapUntilQueueIsCorrect(0);
}
}
var swap = function(self,target) {
var placeHolder = queue[self];
queue[self] = queue[target];
queue[target] = placeHolder;
}
/*
/*Helpers
*/
var evaluate = function(self,target) {
if (queue[target]==null||queue[self]==null) {
return false;
}
if (isMax) {
if (queue[self][criteria] > queue[target][criteria]) {
return true;
} else {
return false;
}
} else {
if (queue[self][criteria] < queue[target][criteria]) {
return true;
} else {
return false;
}
}
}
var getParentOf = function(index) {
return Math.floor(index/2)-1;
}
var getLeftOf = function(index) {
return index*2 + 1;
}
var getRightOf = function(index) {
return index*2 + 2;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You're off to a great start. +1 for providing comments.</p>\n\n<p>Here are some tips:</p>\n\n<h2>1) Define variables before modifying them.</h2>\n\n<p>So the constants <code>MAX_HEAP</code> and <code>MIN_HEAP</code> should be defined after <code>PriorityQueue</code>.</p>\n\n<p>Old Code:</p>\n\n<pre><code>PriorityQueue.MAX_HEAP = 0;\nPriorityQueue.MIN_HEAP = 1;\n\nfunction PriorityQueue(criteria, heapType) {\n //...\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>function PriorityQueue(criteria, heapType) {\n //...\n}\nPriorityQueue.MAX_HEAP = 0;\nPriorityQueue.MIN_HEAP = 1;\n</code></pre>\n\n<p>Side note: In <code>shiftHighestPriorityElement()</code>, <code>_queue</code> isn't defined. I think it should be <code>queue</code>.</p>\n\n<h2>2) Use <code>this</code> to attach attributes to a Constructor.</h2>\n\n<p><a href=\"https://stackoverflow.com/questions/1114024/constructors-in-javascript-objects\">More info</a></p>\n\n<p>Example:\nOld Code:</p>\n\n<pre><code>//..\nfunction PriorityQueue(criteria, heapType) {\n this.length = 0;\n var queue = [];\n var isMax = false;\n //...\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>//..\nfunction PriorityQueue(criteria, heapType) {\n this.length = 0;\n this.queue = [];\n this.isMax = false;\n//...\n</code></pre>\n\n<h2>3) Split up functions longer than 8 - 12 lines of code into smaller functions.</h2>\n\n<p>Use the prototype on an object to attach functions to the constructor instead of including all the functionality within.</p>\n\n<p>Old Code:</p>\n\n<pre><code>function PriorityQueue(criteria, heapType) {\n //...\n this.insert = function (value) {\n if (!value.hasOwnProperty(criteria)) {\n throw \"Cannot insert \" + value + \" because it does not have a property by the name of \" + criteria + \".\";\n }\n queue.push(value);\n length++;\n bubbleUp(length - 1);\n }\n //...\n var swap = function (self, target) {\n var placeHolder = queue[self];\n queue[self] = queue[target];\n queue[target] = placeHolder;\n }\n //...\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>function PriorityQueue(criteria, heapType) {\n//...\n}\nPriorityQueue.prototype.insert = function (value) {\n if (!value.hasOwnProperty(this.criteria)) {\n throw \"Cannot insert \" + value + \" because it does not have a property by the name of \" + this.criteria + \".\";\n }\n this.queue.push(value);\n this.length++;\n this.bubbleUp(this.length - 1);\n}\nPriorityQueue.prototype.swap = function (self, target) {\n var placeHolder = this.queue[self];\n this.queue[self] = this.queue[target];\n this.queue[target] = placeHolder;\n}\n</code></pre>\n\n<h2>4) Sometimes it's better to just return an boolean expression.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>if (queue[self][criteria] < queue[target][criteria]) {\n return true;\n} else {\n return false;\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>return (queue[self][criteria] < queue[target][criteria]);\n</code></pre>\n\n<h2>5) Make sure to create test units.</h2>\n\n<p>Try out <a href=\"http://api.qunitjs.com/equal/\" rel=\"nofollow noreferrer\">qunit.js</a></p>\n\n<h2>6) Simplify <code>if</code> and <code>else</code> conditions.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>var isMax = false;\n\n//Constructor\nif (heapType==PriorityQueue.MAX_HEAP) {\n isMax = true;\n} else if (heapType==PriorityQueue.MIN_HEAP) {\n isMax = false;\n} else {\n throw heapType + \" not supported.\";\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>this.isMax = !!heapType;\nif ( heapType !== 0 || heapType !== 1 ){\n throw heapType + \" not supported.\";\n}\n</code></pre>\n\n<h2>7) Use <code>===</code> instead of <code>==</code> when comparing for value and type of primitive values.</h2>\n\n<p>Old code:</p>\n\n<pre><code>} else if (value == 0) {\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>} else if (value === 0) {\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>} else if (!value) { \n</code></pre>\n\n<h2>Final code:</h2>\n\n<pre><code>function PriorityQueue(criteria, heapType) {\n this.criteria = criteria;\n this.length = 0;\n this.queue = [];\n this.isMax = !!heapType;\n if ( heapType !== 0 || heapType !== 1 ){\n throw heapType + \" not supported.\";\n }\n}\nPriorityQueue.prototype.insert = function (value) {\n if (!value.hasOwnProperty(this.criteria)) {\n throw \"Cannot insert \" + value + \" because it does not have a property by the name of \" + this.criteria + \".\";\n }\n this.queue.push(value);\n this.length++;\n this.bubbleUp(this.length - 1);\n};\nPriorityQueue.prototype.getHighestPriorityElement = function () {\n return this.queue[0];\n};\nPriorityQueue.prototype.shiftHighestPriorityElement = function () {\n if (length < 0) {\n throw(\"There are no more elements in your priority queue.\");\n }\n var oldRoot = this.queue[0];\n var newRoot = this.queue.pop();\n this.length--;\n this.queue[0] = newRoot;\n this.swapUntilQueueIsCorrect(0);\n return oldRoot;\n};\nPriorityQueue.prototype.bubbleUp = function (index) {\n if (index === 0) {\n return;\n }\n var parent = this.getParentOf(index);\n if (this.evaluate(index, parent)) {\n this.swap(index, parent);\n this.bubbleUp(parent);\n } else {\n return;\n }\n};\nPriorityQueue.prototype.swapUntilQueueIsCorrect = function (value) {\n var left = this.getLeftOf(value),\n right = this.getRightOf(value);\n\n if (this.evaluate(left, value)) {\n this.swap(value, left);\n this.swapUntilQueueIsCorrect(left);\n } else if (this.evaluate(right, value)) {\n this.swap(value, right);\n this.swapUntilQueueIsCorrect(right);\n } else if (value === 0) {\n return;\n } else {\n this.swapUntilQueueIsCorrect(0);\n }\n};\nPriorityQueue.prototype.swap = function (self, target) {\n var placeHolder = this.queue[self];\n this.queue[self] = this.queue[target];\n this.queue[target] = placeHolder;\n};\nPriorityQueue.prototype.evaluate = function (self, target) {\n if (this.queue[target] === null || this.queue[self] === null) {\n return false;\n }\n if (this.isMax) {\n return (this.queue[self][this.criteria] > this.queue[target][this.criteria]);\n } else {\n return (this.queue[self][this.criteria] < this.queue[target][this.criteria]);\n }\n};\nPriorityQueue.prototype.getParentOf = function (index) {\n return Math.floor(index / 2) - 1;\n};\nPriorityQueue.prototype.getLeftOf = function (index) {\n return index * 2 + 1;\n};\nPriorityQueue.prototype.getRightOf = function (index) {\n return index * 2 + 2;\n};\nPriorityQueue.MAX_HEAP = 0;\nPriorityQueue.MIN_HEAP = 1;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T04:03:19.783",
"Id": "26170",
"Score": "0",
"body": "Wow! These are some great tips. Thanks much Larry."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-28T11:00:10.727",
"Id": "267526",
"Score": "1",
"body": "For anyone who, like me, wants to use this code for their own purposes, there is a small error. The getParentOf function uses a Math.floor . All odd indices will evaluate to having a wrong parent (e.g. index 1 will evaluate to parent -1). This can be fixed by changing Math.floor to Math.ceil"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T16:03:08.513",
"Id": "15874",
"ParentId": "15853",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "15874",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T19:33:13.877",
"Id": "15853",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"algorithm",
"object-oriented",
"priority-queue"
],
"Title": "Javascript PriorityQueue based on object property"
}
|
15853
|
<p>This script is meant to look for an id in the data attribute in each containment div, then send an Ajax call to get the amount of retweets, calculate the karma based on those retweets and then display that number in a div.</p>
<p>This code looks like spaghetti. How do I improve this to make each function more independent? There is some abstraction function that I can't figure out.</p>
<p>My other question is, how can I use a jQuery deferred object to create a promise and update the div once I get a response?</p>
<pre><code>function get_retweet(id) {
var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json',
karma;
$.ajax({
url: url,
type: 'GET',
dataType:'jsonp',
crossDomain: true,
success: function(data) {
display_karma(data.retweet_count);
},
error: function() {alert('fail');}
}));
}
function calc_karma(tweets) {
return tweets *10 +10;
}
function display_karma(retweets) {
var id, karma,
el =$('.tweetContainer');
//id = $(el).data(el, tweet_id);
id = '248988915661410304';
karma = calc_karma(retweets);
el.find('.tcPoints').text(karma);
}
function start_get_karma() {
var id;
$('.tweetContainer').each(function(index,el) {
//id = $(el).data(el, tweet_id);
id = '248988915661410304';
get_retweet(id);
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T06:59:55.430",
"Id": "25807",
"Score": "3",
"body": "I don't think this code is spaghetti."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T07:01:56.783",
"Id": "25809",
"Score": "0",
"body": "Although there is a global variable and unnecessary declaration, this code is not spaghetti. It is well separated and clearly readable."
}
] |
[
{
"body": "<p>I think your problem is best solved by using some MVC framework like <a href=\"http://angularjs.org/\" rel=\"nofollow\">AngularJS</a>. It helps you handle deferred promise and update your views automatically out of the box.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T02:10:05.320",
"Id": "25798",
"Score": "5",
"body": "I think for something as small as his code any MVC-ish framework is pure overkill."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T02:47:37.493",
"Id": "25802",
"Score": "1",
"body": "I beg to differ. MVC encourages cleaner code with clear separation between Model and View. Also, it's not fun at all to try to use a framework after your codebase get large enough for you to consider using one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T07:00:53.073",
"Id": "25808",
"Score": "3",
"body": "@tanyehzheng I beg to differ. If you need an MVC framework to encourage cleaner code with clear separation, you're doing something wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T14:47:39.257",
"Id": "25819",
"Score": "0",
"body": "@FlorianMargaine Je m'insurge. AngularJS is a nice way to structure very simple codebases too, and should IMHO be avoided only if the AngularJS code is too big for your requirements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T17:42:34.333",
"Id": "25828",
"Score": "1",
"body": "@Cygal I'm sorry, but that's a very stupid statement. I'm repeating myself: if you need AngularJS to structure your codebase, you're doing something wrong. Seriously."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T06:23:21.980",
"Id": "25851",
"Score": "1",
"body": "I didn't say I need it."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T01:46:18.447",
"Id": "15863",
"ParentId": "15860",
"Score": "1"
}
},
{
"body": "<p>You can use jQuerys .when function. As $.ajax returns a defered/promise object you can pass that object to jquery.when. Like this.</p>\n\n<pre><code>function get_retweet(id) {\n var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json',\n karma; \n\n // return the defered object\n return $.ajax({\n url: url,\n type: 'GET',\n dataType:'jsonp',\n crossDomain: true,\n error: function() {alert('fail');}\n }));\n}\n\n\nfunction start_get_karma() {\n var id;\n\n $('.tweetContainer').each(function(index,el) {\n //id = $(el).data(el, tweet_id);\n id = '248988915661410304';\n $.when( get_retweet(id) ).then(function( data ){\n display_karma(data.retweet_count);\n })\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T12:39:07.057",
"Id": "15871",
"ParentId": "15860",
"Score": "6"
}
},
{
"body": "<p>Here are some tips:</p>\n\n<ol>\n<li><p><strong>Use <code>$.getJSON()</code> to get JSON.</strong></p>\n\n<p>Also, name the first parameter <code>json</code> for clarity.</p>\n\n<p>Note from documentation for <code>jQuery.getJSON()</code></p>\n\n<blockquote>\n <p><strong>JSONP</strong></p>\n \n <p>If the URL includes the string \"callback=?\" (or similar, as defined by\n the server-side API), the request is treated as JSONP instead. See the\n discussion of the jsonp data type in $.ajax() for more details.</p>\n</blockquote>\n\n<p><a href=\"http://api.jquery.com/jQuery.getJSON/\" rel=\"nofollow\">More information here</a></p>\n\n<p>Old Code:</p>\n\n<pre><code>var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json',\n karma; \n$.ajax({\n url: url,\n type: 'GET',\n dataType:'jsonp',\n crossDomain: true,\n success: function(data) {\n display_karma(data.retweet_count);\n },\n error: function() {alert('fail');}\n}));\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json?callback=?';\n$.getJSON( url, function (json) {\n display_karma(json.retweet_count);\n}).error(function () {\n alert('fail');\n});\n</code></pre></li>\n<li><p><strong>Eliminate commented code. Use a source control system like git, svn, mercurial to keep track of changes.</strong></p>\n\n<p><a href=\"http://sixrevisions.com/resources/git-tutorials-beginners/\" rel=\"nofollow\">Here's a good start for it</a></p>\n\n<p>Old Code:</p>\n\n<pre><code>function start_get_karma() {\n var id;\n\n $('.tweetContainer').each(function(index,el) {\n //id = $(el).data(el, tweet_id);\n id = '248988915661410304';\n get_retweet(id);\n });\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>function start_get_karma() {\n var id = '248988915661410304';\n $('.tweetContainer').each(function (index, el) {\n get_retweet(id);\n });\n}\n</code></pre></li>\n<li><p><strong>Function calls are expensive, so use a basic loop instead of <code>each()</code> when appropriate.</strong></p>\n\n<p>Old Code:</p>\n\n<pre><code>$('.tweetContainer').each(function (index, el) {\n get_retweet(id);\n});\n</code></pre>\n\n<p>New Code A:</p>\n\n<pre><code>for(var i = 0; len = $('.tweetContainer').length; i < len; i++){\n get_retweet(id);\n}\n</code></pre>\n\n<p>However, there's a problem. Making multiple calls to <code>get_retweet()</code> with the same static value doesn't make sense. So just make one call.</p>\n\n<p>New Code B:</p>\n\n<pre><code>if( $('.tweetContainer').length ){\n get_retweet(id);\n}\n</code></pre></li>\n<li><p><strong>Don't declare variables if they're only used once.</strong></p>\n\n<p>Old Code: </p>\n\n<pre><code>function display_karma(retweets) {\n var id, karma,\n el =$('.tweetContainer');\n id = '248988915661410304';\n karma = calc_karma(retweets);\n el.find('.tcPoints').text(karma);\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>function display_karma(retweets) {\n var id = '248988915661410304';\n $('.tweetContainer').find('.tcPoints').text(calc_karma(retweets));\n}\n</code></pre></li>\n<li><p><strong>Have variable names give a hint to the type.</strong></p>\n\n<p><code>retweets</code> sounds like a function or array. Try naming it <code>retweet_amount</code> or something similar.</p>\n\n<p>Final Code:</p>\n\n<pre><code>function calc_karma(tweets) {\n return (tweets * 10) + 10;\n}\nfunction display_karma(retweet_amount) {\n $('.tweetContainer').find('.tcPoints').text(calc_karma(retweet_amount));\n}\nfunction get_retweet(id) {\n var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json?callback=?';\n $.getJSON( url, function (json) {\n display_karma(json.retweet_count);\n }).error(function () {\n alert('fail');\n });\n}\nfunction start_get_karma() {\n var id = '248988915661410304';\n if( $('.tweetContainer').length ){\n get_retweet(id);\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T19:39:45.463",
"Id": "15884",
"ParentId": "15860",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "15884",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T23:57:20.823",
"Id": "15860",
"Score": "9",
"Tags": [
"javascript",
"jquery",
"ajax",
"twitter"
],
"Title": "Calculate karma based on retweets"
}
|
15860
|
<p>First off, let me say that <a href="http://imar.spaanjaars.com/416/building-layered-web-applications-with-microsoft-aspnet-20-part-1" rel="nofollow">this article</a> pretty much changed how I program, for the better. Until I read this article, I was a spaghetti programming master --- if there were awards for crappiest, least organized, and impossible to read programming, I would have been world champion. But that article taught me to utilize classes (mind-blowing, I know), rather than just copy/paste the same logic around to the necessary pages. With that in mind, I modeled my application (described below) on the examples found in that article. I highly recommend that article for anyone else who's looking to make the jump from newb coding via facerolling on the keyboard to newb coding with some thought behind it.</p>
<p>I've been simultaneously building upon and maintaining this web application for a year now, and I feel that while the layered approach has helped me to stay more organized, I'm not utilizing very much (if any) extra power from having layers.</p>
<p>In my web application Project, I have a folder I created called Classes. The structure looks like this:</p>
<pre><code>/Classes
/ClientManagement
/DataAccess
ClientDB.cs
/Logic
ClientManager.cs
/Objects
Client.cs
</code></pre>
<p>The above is extremely abbreviated (for example, ClientManagement actually has about 20 Objects, 20 Managers, and 20 DBs), and there are other base folders like EmployeeManagement, InventoryManagement, etc. Each "Management" base folder corresponds to a schema in the database, so that for example, in my SQL Server database, I have [myDatabase].[ClientManagement].[Clients].</p>
<p>Each class in the Objects folder looks something like:</p>
<pre><code>public class Client
{
//fields
private int? _clientID = null;
private string _clientName = null;
//properties
public int? ClientID
{
get { return _clientID; }
set { _clientID = value; }
}
public int? ClientName
{
get { return _clientName; }
set { _clientName = value; }
}
//constructor
public Client()
{
}
}
</code></pre>
<p>Once again, very abbreviated here. I am aware of auto-implemented properties in C#, I just chose to manually implement them.</p>
<p>Upon Object instantiation, I set everything to null. It is easier to check for null than to check for "empty" or "zero" values, in my opinion. This way when it comes time to validate an object before saving it to a database, it's very black and white --- if any field that does not allow nulls in the database is found to be null, throw an error, else continue on to save.</p>
<p>Next up, here's what a Manager (Logic) class looks like:</p>
<pre><code>public static class ClientManager
{
public static Client GetItem(int? clientID)
{
return ClientDB.GetItem(clientID);
}
public static ClientList GetList()
{
return ClientDB.GetList();
}
public static int? Save(Client incomingClient)
{
Validate(incomingClient);
return ClientDB.Save(incomingClient);
}
public static void Validate(Client incomingClient)
{
if (incomingClient.ClientName == null)
{
throw new Exception(@"Cannot save a Client without entering a Client Name.");
}
}
}
</code></pre>
<p>As you can see, most of the calls to the manager/logic class are simply forwarded to the DB class. This is where I feel I could use improvement by actually <em>doing</em> something useful in the Manager class, I just don't know what.</p>
<p>The Validate() method is a last resort check. There is already validation checking in each page's code behind. There really is no apparent way that you could ever reach the Validate() method in the Manager class, but it's there anyway because you never know. I've purposely chosen to have it throw a hard exception, because if somehow the user reaches that point, something is seriously wrong somewhere and needs to be addressed immediately.</p>
<p>A DB/DataAccess class looks like this:</p>
<pre><code>public static class ClientDB
{
public static Client GetItem(int? clientID)
{
Client selectedClient = null;
//make db connection, call stored procedure, fill selectedClient.
return selectedClient;
}
public static ClientList GetList()
{
ClientList list = null;
//make db connection, call stored procedure, fill list.
return list;
}
public static int Save(Client incomingClient)
{
int result;
//make db connection, call stored procedure, get result code
return result;
}
private static Client FillDataRecord(IDataReader datareader)
{
Client theclient = new Client();
theclient.ClientID = datareader.GetInt32(datareader.GetOrdinal("ClientID"));
theclient.ClientName = datareader.GetString(datareader.GetOrdinal("ClientName"));
return theclient;
}
}
</code></pre>
<p>As you can see, my web application is broken up into different layers which makes organization a breeze. But, I feel that currently I'm not utilizing the power of layers --- the logic layer does nothing at all but just forward the calls to the DB layer. I think part of my problem is that I simply don't know what I CAN do that is useful.</p>
<p>Currently my system works and my goals are achieved. Some people might say, "then what's the problem?" And while that makes me happy (it means I've done my job with some degree of success, horray), I want to know more advanced techniques.</p>
<p>In the article I originally linked to above, it uses the example of checking roles in the logic layer. In my case, I don't need to do that. We're checking roles pretty much on every action the user takes at the page level.</p>
<p>If I can't figure out something else useful to do at the logic layer, I am thinking about cutting out the logic layer all together, since all it does is forward calls anyway. This would eliminate some .cs files and make it even easier to navigate/maintain.</p>
<p>Ideas, thoughts? What can I do better? What has worked for you? Are there any things related to layered web applications that you know now that you wish you knew when you first started?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T14:15:48.293",
"Id": "25818",
"Score": "0",
"body": "\"Upon Object instantiation, I set everything to null.\" Well, if all your objects are nullable types as per your example, you don't have to set anything at all -- `null` is the default for those types. It's unnecessary (re) initialization and only serves to decrease performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T00:02:34.393",
"Id": "25843",
"Score": "0",
"body": "Haha wow, learn something new every day. Thanks!"
}
] |
[
{
"body": "<p>Fist off, congratulations on your transformation. It's always nice to hear about people seeing the light!</p>\n\n<p>Second I tend to agree with you. If the layer is doing nothing but passing calls to another layer, it is not needed. I would take it out. If, in the future you decide, or figure out what that layer contributes to the project as a whole, you can easily put it back in.</p>\n\n<p>Another thing I'd be careful of is creating public static classes. They have their uses, but too many of them and you start moving from OOP back to procedural programming. What I'm talking about is the ClientDB class. I would rather see it as a class that is injected where it is needed, either manually or using a Inversion of Control (IOC) container.</p>\n\n<p>For more on dependency injection and IOC, read <a href=\"http://blog.ploeh.dk/\">this blog</a>. Then you will become truly enlightened.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T02:40:02.633",
"Id": "15865",
"ParentId": "15864",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "15865",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T01:56:23.343",
"Id": "15864",
"Score": "4",
"Tags": [
"c#",
"asp.net"
],
"Title": "Fully utilizing the layers of an n-layered web application"
}
|
15864
|
<p>I have written this jQuery code to traverse the HTML markup. Basically, I am selecting <code>data-icount</code> attribute of each anchor tag and appending it to anchor text as <code>(28)</code> e.g. the ALL becomes <code>ALL (38)</code> in the example. <code>38</code> here is the sum of all the <code>data-icount</code>s under that <code>li</code>. Similarly, <code>summers</code> become <code>summers (2)</code> because it has two data-icount 0 and 2 so 0+2 =2.</p>
<p>Working example <a href="http://jsfiddle.net/GQkB8/" rel="nofollow noreferrer">here</a>.</p>
<p>I am sure there must be an improved process to do this - any comments/suggestions would be appreciated.</p>
<pre><code><script>
$(document).ready(function(){
var $lis = $("#tree li");
$lis.each(function(index) {
var $this = $(this);
var $sub_uls = $this.children('ul');
var $child_a = $this.children('a');
var num_sub_uls = $sub_uls.length;
var count_icount = 0;
if(num_sub_uls > 0) {
//var sub_lis = $this.children('a');
var sub_lis = $sub_uls.find('a');
//console.log('Total anchors: '+sub_lis.length);
sub_lis.each(function(index2) {
count_icount += parseInt($(this).attr('data-icount'));
//console.log(count_icount);
});
//console.log("out of loop");
} else {
count_icount = parseInt($child_a.attr('data-icount'));
}
var a_txt = $child_a.text();
$child_a.text(a_txt+' ('+count_icount+') ');
});
});
</script>
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><ul id="tree" class="tree">
<li class="">
<a data-icount="0" href="/some/thing/1">ALL </a>
<ul >
<li class="">
<a data-icount="7" href="/some/thing/2" >Fruits</a>
<ul >
<li class="">
<a data-icount="5" href="/some/thing/4" >Summers</a>
<ul >
<li class=""><a data-icount="0" href="/some/thing/7">Mango</a></li>
<li class=""><a data-icount="2" href="/some/thing/8" >Water melon</a></li>
</ul>
</li>
<li class="">
<a data-icount="0" href="/some/thing/5" >Winters</a>
<ul >
<li class=""><a data-icount="0" href="/some/thing/9" >Tangerines</a></li>
<li class=""><a data-icount="0" href="/some/thing/10" >Pomegranate</a></li>
</ul>
</li>
<li class=""><a data-icount="1" href="/some/thing/12" >Others</a></li>
</ul>
</li>
<li class="open">
<a data-icount="0" href="/some/thing/3" class="selected">Furniture</a>
<ul >
<li class=""><a data-icount="6" href="/some/thing/6" >Home</a></li>
<li class=""><a data-icount="0" href="/some/thing/11" >Garden</a></li>
</ul>
</li>
<li class=""><a data-icount="10" href="/some/thing/13" >Games</a>
<ul >
<li class=""><a data-icount="5" href="/some/thing/36" >Playstation</a></li>
</ul>
</li>
<li class=""><a data-icount="2" href="/some/thing/37" >Clothes</a></li>
</ul>
</li>
</ul>
</code></pre>
|
[] |
[
{
"body": "<p>Here are some tips:</p>\n\n<h2>1) Don't create variables if they're only used once or are a don't perform complex operations.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>var num_sub_uls = $sub_uls.length;\nvar count_icount = 0;\nif(num_sub_uls > 0) {\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var count_icount = 0;\nif($sub_uls.length) {\n</code></pre>\n\n<h2>2) Provide the base when using <code>parseInt()</code>.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>count_icount = parseInt($child_a.attr('data-icount'));\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>count_icount = parseInt($child_a.attr('data-icount'), 10);\n</code></pre>\n\n<h2>3) Eliminate commented code sections.</h2>\n\n<p>Old code:</p>\n\n<pre><code>var sub_lis = $sub_uls.find('a');\n//console.log('Total anchors: '+sub_lis.length);\nsub_lis.each(function(index2) {\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var sub_lis = $sub_uls.find('a');\nsub_lis.each(function(index2) {\n</code></pre>\n\n<h2>4) Simplify if conditions by using Truthy & Falsey .</h2>\n\n<pre><code>Boolean(undefined); // => false\nBoolean(null); // => false\nBoolean(false); // => false\nBoolean(0); // => false\nBoolean(\"\"); // => false\nBoolean(NaN); // => false\n\nBoolean(1); // => true\nBoolean([1,2,3]); // => true\nBoolean(function(){}); // => true\n</code></pre>\n\n<p><a href=\"http://james.padolsey.com/javascript/truthy-falsey/\" rel=\"nofollow\">More here</a> </p>\n\n<p>Old Code:</p>\n\n<pre><code>if(num_sub_uls > 0) {\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>if(num_sub_uls) {\n</code></pre>\n\n<h2>5) Use <code>.append()</code> to append text to an element in jQuery.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>var a_txt = $child_a.text();\n$child_a.text(a_txt+' ('+count_icount+') ');\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>$child_a.children('a').append( ' (' + count_icount + ') ' );\n</code></pre>\n\n<h2>6) Simplify your <code>if</code> and <code>else</code> conditions.</h2>\n\n<p>Check if <code>count_icount</code> is greater than 0, instead of checking for <code>sub_list.length</code>;</p>\n\n<p>Old Code:</p>\n\n<pre><code>if(num_sub_uls > 0) {\n var sub_lis = $sub_uls.find('a');\n sub_lis.each(function(index2) {\n count_icount += parseInt($(this).attr('data-icount'));\n });\n} else {\n count_icount = parseInt($child_a.attr('data-icount'));\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>$sub_uls.find('a').each(function(index2) {\n count_icount += parseInt($(this).attr('data-icount'));\n});\nif( !count_icount ){\n count_icount = parseInt($this.children('a').attr('data-icount'), 10);\n}\n</code></pre>\n\n<h2>7) Use <code>.data()</code> instead of <code>.attr()</code> to access properties that begin with <code>data-</code>.</h2>\n\n<p><a href=\"http://api.jquery.com/data/\" rel=\"nofollow\">.data()</a> Documentation</p>\n\n<p>Example:</p>\n\n<pre><code><a id=\"thing2\" data-icount=\"9\" href=\"/some/thing/2\" >Fruits</a>\n</code></pre>\n\n<p>Use </p>\n\n<pre><code>$(\"#thing2\").data( \"icount\" ) == \"9\";\n</code></pre>\n\n<p>Instead of </p>\n\n<pre><code>$(\"#thing2\").attr( \"data-icount\" ) == \"9\";\n</code></pre>\n\n<h2>Final code:</h2>\n\n<pre><code>$(function () {\n $(\"#tree li\").each(function () {\n var $this = $(this),\n count_icount = $this.find(\"a\").data('icount');\n\n $this.children('ul').find('a').each(function () {\n count_icount += parseInt($(this).data('icount'), 10);\n });\n if (!count_icount) {\n count_icount = parseInt($this.children('a').data('icount'), 10);\n }\n $this.children('a').append(' (' + count_icount + ') ');\n });\n});\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/GQkB8/2/\" rel=\"nofollow\">http://jsfiddle.net/GQkB8/2/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T06:35:38.500",
"Id": "25852",
"Score": "0",
"body": "While I +1 this It would be good to explain a few things here. Specifically A lot of new javascripters will not understand the whole `parseInt(\"09\")` issue. It would be good to include that detail here so others can understand your reasoning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T07:30:36.547",
"Id": "25856",
"Score": "0",
"body": "Thanks Larry. I'll keep parseInt tip in my mind. Some of the other things like comments, and `num_lis_length > 0` I kept to make code more obvious to understand but I get your point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:27:05.250",
"Id": "26278",
"Score": "0",
"body": "Hi Larry - the count of very first LI's Anchor (`<a data-icount=\"0\" href=\"/some/thing/1\">ALL </a>` doesn't get added? for example, if I change it to `5` i.e. `<a data-icount=\"5\" href=\"/some/thing/1\">ALL </a>` it still reads as `(38)` ... any ideas how to fix this? thx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:34:56.380",
"Id": "26280",
"Score": "0",
"body": "In fact that is true with all other Anchors ... that is it shows count of children only ... can it be changed to include the parent count itself too? e.g. in the demo markup, `Summers (2) ` becomes `Summers (7)` because `Summers` itself has `5` as icount."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T20:29:29.937",
"Id": "26313",
"Score": "0",
"body": "@HappyApe You found a bug with your original code then. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T22:02:38.627",
"Id": "26322",
"Score": "0",
"body": "@HappyApe The value of the current list wasn't being set. Change `count_icount` to `count_icount = $this.find(\"a\").data('icount');` I updated my code to fix the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T13:53:56.063",
"Id": "26361",
"Score": "0",
"body": "Excellent! thanks very much Larry! yes I found bug in my code.. lol ... actually I had written that code and then got busy so I couldn't really test it after you gave your answer but seems all ok now. Cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T13:55:18.557",
"Id": "26362",
"Score": "0",
"body": "Also noticed that you replaced `attr()` with `data()` - nice :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T16:46:03.983",
"Id": "15875",
"ParentId": "15867",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15875",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T11:04:56.260",
"Id": "15867",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Traversing un-ordered list and appending attibute values to the list item"
}
|
15867
|
<p>I would really appreciate a review of my first game. It is a <a href="https://en.wikipedia.org/wiki/Bejeweled"><em>Bejeweled</em></a>-like game written in Python with <a href="http://pygame.org/">Pygame</a>:</p>
<pre><code>import pygame, random, time, sys
from pygame.locals import *
pygame.init()
NUM_SHAPES = 7 #7
PUZZLE_COLUMNS = 6 #6
PUZZLE_ROWS = 12 #12
SHAPE_WIDTH = 50 #50
SHAPE_HEIGHT = 50 #50
FPS = 15
WINDOW_WIDTH = PUZZLE_COLUMNS * SHAPE_WIDTH
WINDOW_HEIGHT = PUZZLE_ROWS * SHAPE_HEIGHT + 75
BACKGROUND = pygame.image.load("images/bg.png")
CIRCLE = pygame.image.load("images/circle.png")
DIAMOND = pygame.image.load("images/diamond.png")
HEXAGON = pygame.image.load("images/hexagon.png")
SQUARE = pygame.image.load("images/square.png")
STAR = pygame.image.load("images/star.png")
STAR2 = pygame.image.load("images/star2.png")
TRIANGLE = pygame.image.load("images/triangle.png")
SHAPES_LIST = [CIRCLE, DIAMOND, HEXAGON, SQUARE, STAR, STAR2, TRIANGLE]
for x in xrange(len(SHAPES_LIST) - NUM_SHAPES):
del(SHAPES_LIST[0])
EXPLOSION_1 = pygame.image.load("images/explosion1.png")
EXPLOSION_2 = pygame.image.load("images/explosion2.png")
EXPLOSION_3 = pygame.image.load("images/explosion3.png")
EXPLOSION_4 = pygame.image.load("images/explosion4.png")
EXPLOSION_5 = pygame.image.load("images/explosion5.png")
EXPLOSION_6 = pygame.image.load("images/explosion6.png")
EXPLOSION_LIST = [EXPLOSION_1, EXPLOSION_2, EXPLOSION_3, EXPLOSION_4, EXPLOSION_5, EXPLOSION_6]
BLANK = pygame.image.load("images/blank.png")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
FONT_SIZE = 36
TEXT_OFFSET = 5
MINIMUM_MATCH = 3
SINGLE_POINTS = .9
DOUBLE_POINTS = 3
TRIPLE_POINTS = 9
EXTRA_LENGTH_POINTS = .1
RANDOM_POINTS = .3
DELAY_PENALTY_SECONDS = 10
DELAY_PENALTY_POINTS = .5
FPS_CLOCK = pygame.time.Clock()
DISPLAY_SURFACE = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), DOUBLEBUF)
pygame.display.set_caption("Bilging Puzzle")
def main():
global score
global selector
bilgeBoard = generate_random_board()
selector = (0, 0)
score = 0.0
lastMoveTime = pygame.time.get_ticks()
blit_board(bilgeBoard)
draw_selector(selector)
remove_matches(bilgeBoard, selector)
blit_board(bilgeBoard)
blit_score(score)
blit_time(0)
draw_selector(selector)
while True:
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == K_RIGHT and selector[0] < (PUZZLE_COLUMNS - 2):
selector = (selector[0] + 1, selector[1])
if event.key == K_LEFT and selector [0] > 0:
selector = (selector[0] - 1, selector[1])
if event.key == K_DOWN and selector[1] < (PUZZLE_ROWS - 1):
selector = (selector[0], selector[1] + 1)
if event.key == K_UP and selector[1] > 0:
selector = (selector[0], selector[1] - 1)
if event.key == K_SPACE:
lastMoveTime = pygame.time.get_ticks()
score -= 1
swap_pieces(selector, bilgeBoard)
remove_matches(bilgeBoard, selector)
if moveDelay / (DELAY_PENALTY_SECONDS * 1000) >= 1:
score -= DELAY_PENALTY_POINTS * (moveDelay / (DELAY_PENALTY_SECONDS * 1000))
if event.type == QUIT:
pygame.quit()
sys.exit()
moveDelay = pygame.time.get_ticks() - lastMoveTime
blit_board(bilgeBoard)
blit_score(score)
blit_time(moveDelay / 1000)
draw_selector(selector)
pygame.display.update()
FPS_CLOCK.tick(FPS)
def generate_random_board():
return[ [SHAPES_LIST[random.randrange(0, len(SHAPES_LIST))] for i in range(PUZZLE_COLUMNS)] for x in range(PUZZLE_ROWS) ]
#Time in seconds since last move
def blit_time(time):
font = pygame.font.Font(None, FONT_SIZE)
text = font.render("Move Timer: " + str(time / 60) + ":" + str(time % 60).zfill(2), True, BLACK)
textPosition = text.get_rect()
DISPLAY_SURFACE.blit(text, (TEXT_OFFSET, WINDOW_HEIGHT - (FONT_SIZE * 2)))
def blit_score(score):
font = pygame.font.Font(None, FONT_SIZE)
text = font.render("Score: " + str(score), True, BLACK)
textPosition = text.get_rect()
DISPLAY_SURFACE.blit(text, (TEXT_OFFSET, WINDOW_HEIGHT - FONT_SIZE))
def blit_board(board):
DISPLAY_SURFACE.blit(BACKGROUND, (0, 0))
rowNum = 0
for row in board:
columnNum = 0
for shape in row:
DISPLAY_SURFACE.blit(shape, (SHAPE_WIDTH * columnNum, SHAPE_HEIGHT * rowNum))
columnNum += 1
rowNum += 1
#Accepts a tuple indicating the position of the left shape in the selector relative to the board (as an array) (row, column)
def draw_selector(position):
topLeft = (position[0] * SHAPE_WIDTH, position[1] * SHAPE_HEIGHT)
topRight = (topLeft[0] + SHAPE_WIDTH * 2, topLeft[1])
bottomLeft = (topLeft[0], topLeft[1] + SHAPE_HEIGHT)
bottomRight = (topRight[0], topRight[1] + SHAPE_HEIGHT)
pygame.draw.lines(DISPLAY_SURFACE, WHITE, True, [topLeft, topRight, bottomRight, bottomLeft], 3)
#Accepts a tuple indicating the position of the selector
def swap_pieces(position, board):
x, y = position
board[y][x + 1], board[y][x] = board[y][x], board[y][x + 1]
def remove_matches(board, selector):
matches = find_matches(board)
while matches:
explosion_animation(board, matches)
score_matches(board, selector, matches)
clear_matches(board, matches)
refill_columns(board)
matches = find_matches(board)
selector = (0, 0) #So subsequent matches won't be counted as player matches
def score_matches(board, selector, matches):
global score
playerMatches = []
selector = (selector[1], selector[0])
for match in matches:
for position in match:
if (position == selector or position == (selector[0], selector[1] + 1)) and (not match in playerMatches):
playerMatches.append(match)
if len(playerMatches) == 1:
score += SINGLE_POINTS
elif len(playerMatches) == 2:
score += DOUBLE_POINTS
elif len(playerMatches) == 3:
score += TRIPLE_POINTS
for match in playerMatches:
score += (len(match) - MINIMUM_MATCH) * EXTRA_LENGTH_POINTS
for match in matches:
if not match in playerMatches:
score += RANDOM_POINTS
def find_matches(board):
clearList = []
#First scan the columns for matches
for column in xrange(PUZZLE_COLUMNS):
length = 1
for row in xrange(1, PUZZLE_ROWS):
if board[row][column] == board[row - 1][column]:
length += 1
if not board[row][column] == board[row - 1][column]:
if length >= MINIMUM_MATCH:
match = []
for clearRow in xrange(row - length, row):
match.append((clearRow, column))
clearList.append(match)
length = 1
if row == PUZZLE_ROWS - 1:
if length >= MINIMUM_MATCH:
match = []
for clearRow in xrange(row - (length - 1), row + 1):
match.append((clearRow, column))
clearList.append(match)
#Next scan the rows for matches
for row in xrange(PUZZLE_ROWS):
length = 1
for column in xrange(1, PUZZLE_COLUMNS):
if board[row][column] == board[row][column - 1]:
length += 1
if not board[row][column] == board[row][column - 1]:
if length >= MINIMUM_MATCH:
match = []
for clearColumn in xrange(column - length, column):
match.append((row, clearColumn))
clearList.append(match)
length = 1
if column == PUZZLE_COLUMNS - 1:
if length >= MINIMUM_MATCH:
match = []
for clearColumn in xrange(column - (length - 1), column + 1):
match.append((row, clearColumn))
clearList.append(match)
return clearList
#Accepts list of positions to clear
def clear_matches(board, matches):
for match in matches:
for position in match:
row, column = position
board[row][column] = BLANK
def refill_columns(board):
for column in xrange(PUZZLE_COLUMNS):
for row in xrange(PUZZLE_ROWS):
if board[row][column] == BLANK:
test = 0
length = 0
#Determine how long the clear is
while row + test < PUZZLE_ROWS and board[row + test][column] == BLANK:
length += 1
test += 1
for blankRow in xrange(row, PUZZLE_ROWS):
try:
board[blankRow][column] = board[blankRow + length][column]
except:
board[blankRow][column] = SHAPES_LIST[random.randrange(0, len(SHAPES_LIST))]
def explosion_animation(board, matches):
for frame in EXPLOSION_LIST:
for match in matches:
for position in match:
row, column = position
board[row][column] = frame
blit_board(board)
pygame.display.update()
FPS_CLOCK.tick(FPS)
if __name__ == '__main__':
main()
</code></pre>
<p>Here is a zip with the code and assets: <a href="http://dl.dropbox.com/u/1541103/game.zip">http://dl.dropbox.com/u/1541103/game.zip</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-22T23:07:49.970",
"Id": "397516",
"Score": "0",
"body": "Link is broken now..."
}
] |
[
{
"body": "<h3>1. Introduction</h3>\n\n<p>The code seems pretty good to me overall. I had no difficulty reading it or understanding what it did, and it seems to work well enough. So take all the points below (especially those in section 3) with a pinch of salt. I would have written it differently, but that doesn't mean that every change I have made is an improvement.</p>\n\n<h3>2. Major points</h3>\n\n<ol>\n<li><p>You implement your explosions by writing a little loop that updates the board to put each animation frame in place, and then waits for a frame to pass:</p>\n\n<pre><code>def explosion_animation(board, matches):\n for frame in EXPLOSION_LIST:\n # ...\n blit_board(board)\n pygame.display.update()\n FPS_CLOCK.tick(FPS)\n</code></pre>\n\n<p>The problem with this approach is that no other events can happen during this loop: the score can't update, the player can't move the cursor, and nothing else can animate. For this particular game you only have one thing happening at a time, so you can get away with this approach. But what if you wanted to have several different things happening at the same time?</p>\n\n<p>The usual way to handle many objects which all need to move or animate at the same time is to give each object a <code>tick</code> function that is responsible for updating its internal state based on the amount of time that has passed since the last frame. This means, of course, that you will have to re-organize your code so that you record the set of matches, and keep track of time from when the matches occurred so that you can select the correct frame from the explosion animation.</p>\n\n<p>I've put some revised code at the end of this answer showing one way in which you might go about this. Note that a benefit of this approach is that you can decouple the game's framerate from your animation framerate, so that you can change one without having to change the other.</p></li>\n<li><p>The scoring system is both hard to understand (there's no clear relationship between what I do and the score I get) and very harsh. From reading the code, it seems that I <em>lose a point every time I move</em> (and a further half point for every 10 seconds I take) but only gain 0.9 points when I make a match. No wonder I quickly racked up loads of negative points!</p>\n\n<p>The usual way to indicate the relationship between what the player does and the score they get is to draw the score on the board in a position close to the action happened. If there's a bonus, there needs to be some text of the form \"BONUS\" or \"+100\" or whatever.</p>\n\n<p>The harshness of the scoring system is really up to you as game designer. But look at it like this: it costs you nothing to hand out points by the millions, and there are people out there who will enjoy the game more if you do.</p></li>\n<li><p>The game never ends! It just carries on forever, with no possibility of winning or losing.</p></li>\n</ol>\n\n<h3>3. Minor points</h3>\n\n<ol>\n<li><p>Code that maintains some kind of persistent state and manipulates it is often most clearly written in the form of <a href=\"http://docs.python.org/tutorial/classes.html\">classes and methods</a>. This is particularly so for games, which typically implement some kind of persistent world. It would seem sensible here to have a <code>Game</code> class to represent the global game state, a <code>Board</code> class to represent the playing area, and a <code>Cell</code> class to represent a square on the board.</p></li>\n<li><p>The thing you call a <em>selector</em> is more commonly known as a <a href=\"http://en.wikipedia.org/wiki/Cursor_%28computers%29\"><em>cursor</em></a>.</p></li>\n<li><p>The term <em>blit</em> is short for <a href=\"http://en.wikipedia.org/wiki/Bit_blit\"><em>block transfer</em></a> and means roughly \"to copy blocks of pixels from one part of memory to another.\" Unless you're specifically writing about blitting, I'd use a more general term like <em>draw</em>.</p></li>\n<li><p>If you made <code>selector</code> a (mutable) list rather than an immutable tuple, you'd be able to update its <em>x</em> and <em>y</em> component independently:</p>\n\n<pre><code>selector = [0, 0]\n# ...\nselector[0] += 1 # Move right\n</code></pre></li>\n<li><p>You can use the function <a href=\"http://docs.python.org/library/random.html#random.choice\"><code>random.choice</code></a> to simplify</p>\n\n<pre><code>SHAPES_LIST[random.randrange(0, len(SHAPES_LIST))]\n</code></pre>\n\n<p>to <code>random.choice(SHAPES_LIST)</code>.</p></li>\n<li><p>It's conventional to use <code>_</code> for a loop variable that you don't actually use:</p>\n\n<pre><code>[[random.choice(SHAPES_LIST) for _ in range(PUZZLE_COLUMNS)] for _ in range(PUZZLE_ROWS)]\n</code></pre></li>\n<li><p>The code could be simplified if you kept the board in a single list of length <em>width</em> Γ <em>height</em> (rather than a list of lists). You could replace each pair of nested loops with a single loop, and the matches test would also be simplified.</p></li>\n<li><p>When iterating over the elements of a sequence, if you also want the index of each element, use the function <a href=\"http://docs.python.org/library/functions.html#enumerate\"><code>enumerate</code></a>. So instead of:</p>\n\n<pre><code>rowNum = 0\nfor row in board:\n columnNum = 0\n for shape in row:\n DISPLAY_SURFACE.blit(shape, (SHAPE_WIDTH * columnNum, SHAPE_HEIGHT * rowNum))\n columnNum += 1\n rowNum += 1\n</code></pre>\n\n<p>write:</p>\n\n<pre><code>for j, row in enumerate(board):\n for i, shape = enumerate(row):\n DISPLAY_SURFACE.blit(shape, (SHAPE_WIDTH * i, SHAPE_HEIGHT * j))\n</code></pre></li>\n<li><p>The line</p>\n\n<pre><code>selector = (0, 0) #So subsequent matches won't be counted as player matches\n</code></pre>\n\n<p>seems wrong: if there are subsequent matches at (0,0) then these would be incorrectly counted as player matches. It would be more reliable to add a simple flag instead of a special case:</p>\n\n<pre><code>def remove_matches(board, selector):\n matches = find_matches(board)\n score_player_matches = True\n\n while matches:\n explosion_animation(board, matches)\n score_matches(board, selector, matches, score_player_matches)\n clear_matches(board, matches)\n refill_columns(board)\n matches = find_matches(board)\n score_player_matches = False\n</code></pre></li>\n<li><p>You can simplify your code for finding matches by making use of the function <a href=\"http://docs.python.org/library/itertools.html#itertools.groupby\"><code>itertools.groupby</code></a>.</p></li>\n<li><p>The title \"<a href=\"http://yppedia.puzzlepirates.com/Bilging\">Bilging Puzzle</a>\" is unlikely to mean anything to someone who has not played <em>Yohoho! Puzzle Pirates</em>. (Also, the new shapes pushing in from the bottom make sense in <em>YPP</em> where they represent water coming into the ship from below, but when the shapes are jewels as in <em>Bejeweled</em> it makes more sense for them to enter from the top.)</p></li>\n<li><p>The black text on the dark background is pretty much impossible to read.</p></li>\n<li><p>The loading of the images could be simplified:</p>\n\n<pre><code>SHAPES = 'circle diamond hexagon square star star2 triangle'\nSHAPES_LIST = [pygame.image.load('images/{}.png'.format(shape))\n for shape in SHAPES.split()]\n</code></pre></li>\n<li><p>The cursor can be cut off at the top and the sides by the edge of the window. You need to add a bit of margin around the board.</p></li>\n<li><p>You can use Python's <a href=\"http://docs.python.org/library/string.html#formatstrings\"><code>string.format</code></a> method to replace</p>\n\n<pre><code>\"Move Timer: \" + str(time / 60) + \":\" + str(time % 60).zfill(2)\n</code></pre>\n\n<p>with</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"Move Timer: {}:{:02}\".format(time // 60, time % 60)\n</code></pre></li>\n<li><p>You could cache the font instead of recomputing it every time you want to draw some text.</p></li>\n<li><p>The two lines <code>textPosition = text.get_rect()</code> seem to be useless.</p></li>\n<li><p>The player gets no score for a move that makes four matches (which is possible).</p></li>\n<li><p>There are several copies of the drawing code: two at the start of the function <code>main</code> and one at the end of the main loop. With a bit of reorganization you could arrange to have only one copy.</p></li>\n<li><p>You can avoid having to store the previous frame's value of <a href=\"http://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks\"><code>pygame.time.get_ticks</code></a> and subtract, if you use the return value of <a href=\"http://www.pygame.org/docs/ref/time.html#Clock.tick\"><code>Clock.tick</code></a> method. Note that it's a good idea, when computing the frame time, to clamp the result to 1/FPS, because you can get long frames from time to time, and you don't want these long frames to lead to wild movement. (Long frames can occur when loading assets, as in the first frame of the game here, or when another process on the system happens to hog the CPU.)</p></li>\n</ol>\n\n<h3>4. Revised code</h3>\n\n<p>Here's a revision of your code that implements most of the suggestions above, and includes some bonus improvements for you to discover and reverse engineer.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import pygame, random, time, sys\nfrom pygame.locals import *\nimport itertools\nimport os\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\n\nSHAPE_WIDTH = 50 # Width of each shape (pixels).\nSHAPE_HEIGHT = 50 # Height of each shape (pixels).\nPUZZLE_COLUMNS = 6 # Number of columns on the board.\nPUZZLE_ROWS = 12 # Number of rows on the board.\nMARGIN = 2 # Margin around the board (pixels).\nWINDOW_WIDTH = PUZZLE_COLUMNS * SHAPE_WIDTH + 2 * MARGIN\nWINDOW_HEIGHT = PUZZLE_ROWS * SHAPE_HEIGHT + 2 * MARGIN + 75\nFONT_SIZE = 36\nTEXT_OFFSET = MARGIN + 5\n\n# Map from number of matches to points scored.\nSCORE_TABLE = {0: 0, 1: .9, 2: 3, 3: 9, 4: 27}\nMINIMUM_MATCH = 3\nEXTRA_LENGTH_POINTS = .1\nRANDOM_POINTS = .3\nDELAY_PENALTY_SECONDS = 10\nDELAY_PENALTY_POINTS = .5\n\nFPS = 30\nEXPLOSION_SPEED = 15 # In frames per second.\nREFILL_SPEED = 10 # In cells per second.\n\nclass Cell(object):\n \"\"\"\n A cell on the board, with properties:\n `image` -- a `Surface` object containing the sprite to draw here.\n `offset` -- vertical offset in pixels for drawing this cell.\n \"\"\"\n def __init__(self, image):\n self.offset = 0.0\n self.image = image\n\n def tick(self, dt):\n self.offset = max(0.0, self.offset - dt * REFILL_SPEED)\n\nclass Board(object):\n \"\"\"\n A rectangular board of cells, with properties:\n `w` -- width in cells.\n `h` -- height in cells.\n `size` -- total number of cells.\n `board` -- list of cells.\n `matches` -- list of matches, each being a list of exploding cells.\n `refill` -- list of cells that are moving up to refill the board.\n `score` -- score due to chain reactions.\n \"\"\"\n def __init__(self, width, height):\n self.explosion = [pygame.image.load('images/explosion{}.png'.format(i))\n for i in range(1, 7)]\n shapes = 'circle diamond hexagon square star star2 triangle'\n self.shapes = [pygame.image.load('images/{}.png'.format(shape))\n for shape in shapes.split()]\n self.background = pygame.image.load(\"images/bg.png\")\n self.blank = pygame.image.load(\"images/blank.png\")\n self.w = width\n self.h = height\n self.size = width * height\n self.board = [Cell(self.blank) for _ in range(self.size)]\n self.matches = []\n self.refill = []\n self.score = 0.0\n\n def randomize(self):\n \"\"\"\n Replace the entire board with fresh shapes.\n \"\"\"\n for i in range(self.size):\n self.board[i] = Cell(random.choice(self.shapes))\n\n def pos(self, i, j):\n \"\"\"\n Return the index of the cell at position (i, j).\n \"\"\"\n assert(0 <= i < self.w)\n assert(0 <= j < self.h)\n return j * self.w + i\n\n def busy(self):\n \"\"\"\n Return `True` if the board is busy animating an explosion or a\n refill and so no further swaps should be permitted.\n \"\"\"\n return self.refill or self.matches\n\n def tick(self, dt):\n \"\"\"\n Advance the board by `dt` seconds: move rising blocks (if\n any); otherwise animate explosions for the matches (if any);\n otherwise check for matches.\n \"\"\"\n if self.refill:\n for c in self.refill:\n c.tick(dt)\n self.refill = [c for c in self.refill if c.offset > 0]\n if self.refill:\n return\n elif self.matches:\n self.explosion_time += dt\n f = int(self.explosion_time * EXPLOSION_SPEED)\n if f < len(self.explosion):\n self.update_matches(self.explosion[f])\n return\n self.update_matches(self.blank)\n self.refill = list(self.refill_columns())\n self.explosion_time = 0\n self.matches = self.find_matches()\n self.score += len(self.matches) * RANDOM_POINTS\n\n def draw(self, display):\n \"\"\"\n Draw the board on the pygame surface `display`.\n \"\"\"\n display.blit(self.background, (0, 0))\n for i, c in enumerate(self.board):\n display.blit(c.image,\n (MARGIN + SHAPE_WIDTH * (i % self.w),\n MARGIN + SHAPE_HEIGHT * (i // self.w - c.offset)))\n\n def swap(self, cursor):\n \"\"\"\n Swap the two board cells covered by `cursor` and update the\n matches.\n \"\"\"\n i = self.pos(*cursor)\n b = self.board\n b[i], b[i+1] = b[i+1], b[i]\n self.matches = self.find_matches()\n\n def find_matches(self):\n \"\"\"\n Search for matches (lines of cells with identical images) and\n return a list of them, each match being represented as a list\n of board positions.\n \"\"\"\n def lines():\n for j in range(self.h):\n yield range(j * self.w, (j + 1) * self.w)\n for i in range(self.w):\n yield range(i, self.size, self.w)\n def key(i):\n return self.board[i].image\n def matches():\n for line in lines():\n for _, group in itertools.groupby(line, key):\n match = list(group)\n if len(match) >= MINIMUM_MATCH:\n yield match\n return list(matches())\n\n def update_matches(self, image):\n \"\"\"\n Replace all the cells in any of the matches with `image`.\n \"\"\"\n for match in self.matches:\n for position in match:\n self.board[position].image = image\n\n def refill_columns(self):\n \"\"\"\n Move cells downwards in columns to fill blank cells, and\n create new cells as necessary so that each column is full. Set\n appropriate offsets for the cells to animate into place.\n \"\"\"\n for i in range(self.w):\n target = self.size - i - 1\n for pos in range(target, -1, -self.w):\n if self.board[pos].image != self.blank:\n c = self.board[target]\n c.image = self.board[pos].image\n c.offset = (target - pos) // self.w\n target -= self.w\n yield c\n offset = 1 + (target - pos) // self.w\n for pos in range(target, -1, -self.w):\n c = self.board[pos]\n c.image = random.choice(self.shapes)\n c.offset = offset\n yield c\n\nclass Game(object):\n \"\"\"\n The state of the game, with properties:\n `clock` -- the pygame clock.\n `display` -- the window to draw into.\n `font` -- a font for drawing the score.\n `board` -- the board of cells.\n `cursor` -- the current position of the (left half of) the cursor.\n `score` -- the player's score.\n `last_swap_ticks` -- \n `swap_time` -- time since last swap (in seconds).\n \"\"\"\n def __init__(self):\n pygame.init()\n pygame.display.set_caption(\"Bejewelled Clone\")\n self.clock = pygame.time.Clock()\n self.display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT),\n DOUBLEBUF)\n self.board = Board(PUZZLE_COLUMNS, PUZZLE_ROWS)\n self.font = pygame.font.Font(None, FONT_SIZE)\n\n def start(self):\n \"\"\"\n Start a new game with a random board.\n \"\"\"\n self.board.randomize()\n self.cursor = [0, 0]\n self.score = 0.0\n self.swap_time = 0.0\n\n def quit(self):\n \"\"\"\n Quit the game and exit the program.\n \"\"\"\n pygame.quit()\n sys.exit()\n\n def play(self):\n \"\"\"\n Play a game: repeatedly tick, draw and respond to input until\n the QUIT event is received.\n \"\"\"\n self.start()\n while True:\n self.draw()\n dt = min(self.clock.tick(FPS) / 1000.0, 1.0 / FPS)\n self.swap_time += dt\n for event in pygame.event.get():\n if event.type == KEYUP:\n self.input(event.key)\n elif event.type == QUIT:\n self.quit()\n self.board.tick(dt)\n\n def input(self, key):\n \"\"\"\n Respond to the player pressing `key`.\n \"\"\"\n if key == K_q:\n self.quit()\n elif key == K_RIGHT and self.cursor[0] < self.board.w - 2:\n self.cursor[0] += 1\n elif key == K_LEFT and self.cursor[0] > 0:\n self.cursor[0] -= 1\n elif key == K_DOWN and self.cursor[1] < self.board.h - 1:\n self.cursor[1] += 1\n elif key == K_UP and self.cursor[1] > 0:\n self.cursor[1] -= 1\n elif key == K_SPACE and not self.board.busy():\n self.swap()\n\n def swap(self):\n \"\"\"\n Swap the two cells under the cursor and update the player's score.\n \"\"\"\n swap_penalties = int(self.swap_time / DELAY_PENALTY_SECONDS)\n self.swap_time = 0.0\n self.board.swap(self.cursor)\n self.score -= 1 + DELAY_PENALTY_POINTS * swap_penalties\n self.score += SCORE_TABLE[len(self.board.matches)]\n for match in self.board.matches:\n self.score += (len(match) - MINIMUM_MATCH) * EXTRA_LENGTH_POINTS\n\n def draw(self):\n self.board.draw(self.display)\n self.draw_score()\n self.draw_time()\n self.draw_cursor()\n pygame.display.update()\n\n def draw_time(self):\n s = int(self.swap_time)\n text = self.font.render('Move Timer: {}:{:02}'.format(s / 60, s % 60),\n True, WHITE)\n self.display.blit(text, (TEXT_OFFSET, WINDOW_HEIGHT - (FONT_SIZE * 2)))\n\n def draw_score(self):\n total_score = self.score + self.board.score\n text = self.font.render('Score: {}'.format(total_score), True, WHITE)\n self.display.blit(text, (TEXT_OFFSET, WINDOW_HEIGHT - FONT_SIZE))\n\n def draw_cursor(self):\n topLeft = (MARGIN + self.cursor[0] * SHAPE_WIDTH,\n MARGIN + self.cursor[1] * SHAPE_HEIGHT)\n topRight = (topLeft[0] + SHAPE_WIDTH * 2, topLeft[1])\n bottomLeft = (topLeft[0], topLeft[1] + SHAPE_HEIGHT)\n bottomRight = (topRight[0], topRight[1] + SHAPE_HEIGHT)\n pygame.draw.lines(self.display, WHITE, True,\n [topLeft, topRight, bottomRight, bottomLeft], 3)\n\nif __name__ == '__main__':\n Game().play()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T01:20:27.103",
"Id": "25848",
"Score": "2",
"body": "Dude, this is an __awesome__ review. You really, really have a triple gift: an extraordinarily pleasant prose, clarity of thought and, of course, programming skills! It is amazing that you took the time to do this, I am profoundly impressed!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T22:29:52.107",
"Id": "25902",
"Score": "0",
"body": "Thanks a lot for the **very** thorough review. I will make sure to study this code in depth, thanks again :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:23:36.693",
"Id": "61393",
"Score": "0",
"body": "Splendid review, unbiased, honest and thorough. Well done!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-07T20:22:09.727",
"Id": "144661",
"Score": "0",
"body": "How do you make it match vertical?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-09T09:58:35.083",
"Id": "144840",
"Score": "0",
"body": "@johnny: That might make a good question for [Stack Overflow](http://stackoverflow.com/)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T23:43:55.840",
"Id": "15895",
"ParentId": "15873",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "15895",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T14:43:39.057",
"Id": "15873",
"Score": "12",
"Tags": [
"python",
"pygame"
],
"Title": "A small Bejeweled-like game in Pygame"
}
|
15873
|
<p>I'm using Node.js and am creating some models for my different objects. This is a simplified version of what they look like at the moment.</p>
<pre><code>var Foo = module.exports = function () {
var values = { type: 'foo', prop1: '', prop2: '' };
function model() {}
model.init = function(val) {
_.extend(values, val);
return model;
}
model.store = function(cb) {
db.insert(values.type, values, cb);
}
model.prop1 = function(val) {
if(!arguments.length) return values.prop1;
values.prop1 = val;
return model;
}
return model;
}
</code></pre>
<p>Then I can do:</p>
<pre><code>var foo = Foo();
foo.init({prop1: 'a', prop2: 'b'}).store(function(err) { ... });
</code></pre>
<p>I then create another model:</p>
<pre><code>var Bar = module.exports = function () {
var values = { type: 'foo', prop3: '', prop4: '' };
function model() {}
model.init = function(val) {
_.extend(values, val);
return model;
}
model.store = function(cb) {
db.insert(values.type, values, cb);
}
model.prop3 = function(val) {
if(!arguments.length) return values.prop3;
values.prop3 = val;
return model;
}
return model;
}
</code></pre>
<p>At which point I realize that a lot of the functions, like <code>model.init</code> and <code>model.store</code> will be reused in each of the models. But while they are exactly the same code, they depend on the local values contained in the model closure. </p>
<p>What's the best way to pull these functions out into a common base class that I can then use to extend all of my models with? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T17:27:26.273",
"Id": "25825",
"Score": "0",
"body": "What's the `db` variable? Is that mongodb?"
}
] |
[
{
"body": "<p>Here are some tips:</p>\n\n<h2>1) Turn <code>Model</code> into a constructor that accepts an object as the default values.</h2>\n\n<p>Note: Constructors should start with a capital letter.\nCode:</p>\n\n<pre><code>// Model\nfunction Model(defaultValues) {\n this.values = defaultValues || {};\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var modelFoo = new Model({\n type : 'foo',\n prop1 : '',\n prop2 : ''\n}); \nconsole.log( modelFoo.values.type === \"foo\" ); // true\n</code></pre>\n\n<h2>2) For readability, set the value of <code>module.exports</code> at the end of the file.</h2>\n\n<p>Assuming <code>Foo</code> and <code>Bar</code> are in the same file you can export both of them like so.</p>\n\n<p>Code:</p>\n\n<pre><code>module.exports = {\n \"Foo\" : Foo,\n \"Bar\" : Bar\n};\n</code></pre>\n\n<h2>3) Since <code>Model</code> is a constructor, you can access the interval values by using <code>this</code> and attach functions to it by using <code>prototype</code>.</h2>\n\n<p>Also, returning <code>this</code> gives access to the current object instance.</p>\n\n<p>Old Code:</p>\n\n<pre><code>model.init = function (val) {\n _.extend(values, val);\n return model;\n}\n\nmodel.store = function (cb) {\n db.insert(values.type, values, cb);\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>Model.prototype.init = function (val) {\n this.values = _.extend(this.values, val);\n return this;\n};\nModel.prototype.store = function (cb) {\n db.insert(this.values.type, this.values, cb);\n return this;\n};\n</code></pre>\n\n<h2>4) Make sure that you define db in the module.</h2>\n\n<p>Code:</p>\n\n<pre><code>var db = require(\"db\").db;\n</code></pre>\n\n<h2>5) Create a generic setter and getter function for the properties.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>model.prop1 = function (val) {\n if (!arguments.length)\n return values.prop1;\n values.prop1 = val;\n return model;\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>Model.prototype.createPropSetterAndGetter = function (propName) {\n this[propName] = (function () {\n return function (val) {\n if (!arguments.length) {\n return this.values[propName];\n }\n this.values[propName] = val;\n };\n }());\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var modelBar = new Model({\n type : 'bar',\n prop3 : '',\n prop4 : ''\n});\nconsole.log( typeof modelBar.prop3 === \"undefined\" ); // true\nmodelBar.createPropSetterAndGetter(\"prop3\");\nconsole.log( modelBar.prop3() === \"\" ); // true\nmodelBar.prop3( \"PAY ME!\" );\nconsole.log( modelBar.prop3() === \"PAY ME!\" ); //true and hurry.\n</code></pre>\n\n<h2>Final Result:</h2>\n\n<pre><code>var db = require(\"db\").db;\n\n// Model\nfunction Model(defaultValues) {\n this.values = defaultValues || {};\n}\nModel.prototype.init = function (val) {\n this.values = _.extend(this.values, val);\n return this;\n};\nModel.prototype.store = function (cb) {\n db.insert(this.values.type, this.values, cb);\n return this;\n};\nModel.prototype.createPropSetterAndGetter = function (propName) {\n this[propName] = (function () {\n return function (val) {\n if (!arguments.length) {\n return this.values[propName];\n }\n this.values[propName] = val;\n };\n })();\n};\n// Foo\nvar Foo = function () {\n var modelFoo = new Model({\n type : 'foo',\n prop1 : '',\n prop2 : ''\n });\n modelFoo.createPropSetterAndGetter(\"prop1\");\n return modelFoo;\n};\n// Bar\nvar Bar = function () {\n var modelBar = new Model({\n type : 'bar',\n prop3 : '',\n prop4 : ''\n });\n modelBar.createPropSetterAndGetter(\"prop3\");\n return modelBar;\n};\n\nmodule.exports = {\n \"Foo\" : Foo,\n \"Bar\" : Bar\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T00:26:00.263",
"Id": "25918",
"Score": "0",
"body": "Thanks Larry! I liked the previous structure that I had since it created its own closure which meant that I didn't have to keep calling `this` all the time so I was hoping that there was a way to extend that. But looks like I'll be heading back to standard prototypes. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T17:26:33.593",
"Id": "15878",
"ParentId": "15876",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15878",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T16:51:21.157",
"Id": "15876",
"Score": "4",
"Tags": [
"javascript",
"node.js"
],
"Title": "How to refactor common methods that depend on local variables into a base class"
}
|
15876
|
<p>I'm trying to write a simple class to represent a text file - which one would think should be quite easy. I don't intend to add all bells and whistles to fully represent a text file just enough to be able create/open read and write etc.</p>
<p>The more I look at it the more I think that it's a bad idea or rather that I'm approaching it the wrong way. The main problem that stands out is the exception handling which horrible. I've thrown runtime exceptions for situations that if feel there is no other way to handle them there must be a better way to do this.</p>
<p>The <code>getText()</code> method throws a <code>FileNotFoundException</code> which is ugly for the caller - before this I handled it in the method and created a new file and returned an empty string which is worse, I think.</p>
<p>Initially I read in the text only once on construction and stored the string in a field which suited my needs better (I don't expect the file to be changed and continually having to read it in seems a bit inefficient) but later I decided that this didn't really correctly model a <code>TextFile</code>.</p>
<p>How can I improve this class that should represent a text file?</p>
<pre><code> public class TextFile extends File{
private static final long serialVersionUID = 1L;
/**
* -Create a new textfile, with the supplied text
* -if the file already exists the text
* it will be replaced with supplied text
*
* @param pathname
* @param text
*/
public TextFile(String pathname, String text){
super(pathname);
if(!exists()) {
createNewTextFile();
}else {
try {
setText(text);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
/**
* -Creates a new text file
by opening the file pointed to by the supplied pathname
* -If the file doesn't exist a new empty text file will be created
*
* @param pathname
* @throws IOException
*/
public TextFile(String pathname) {
super(pathname);
if(!exists()) {
createNewTextFile();
}
}
/*
* return the text in the textFile
*/
public String getText() throws FileNotFoundException {
return read();
}
/**
* Set the text in the text file
* @param text
* @throws FileNotFoundException
*/
public void setText(String text) throws FileNotFoundException {
if(!exists()) {
try {
createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
write(text);
}
public void clearText() throws FileNotFoundException {
setText("");
}
private String read() throws FileNotFoundException {
FileInputStream fis = new FileInputStream(getPath());
InputStreamReader isw = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isw);
StringBuffer fileText = new StringBuffer();
String line;
try {
while ((line = reader.readLine()) != null) {
fileText.append(line+"\n");
}
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(fis != null) {
fis.close();
}
isw.close();
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return fileText.toString();
}
private void write(String text) throws FileNotFoundException{
FileOutputStream fos = new FileOutputStream(getPath());
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter writer = new BufferedWriter(osw);
try {
writer.write(text);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
writer.flush();
writer.close();
if(fos != null) {
fos.close();
}
osw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private void createNewTextFile() {
try {
createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Combine the text content from
* a list of files into a single string
*
* @param textFiles
* @return
* @throws FileNotFoundException
*/
public static String textFiles2String(List<TextFile> textFiles)
throws FileNotFoundException{
StringBuilder combined = new StringBuilder();
for(TextFile textFile : textFiles) {
combined.append(textFile.getText());
}
return combined.toString();
}
}
</code></pre>
<hr>
<p><strong>Another version</strong> (still ugly but it makes more sense for my needs)</p>
<ul>
<li><code>getText</code> and <code>setText</code> only work with an in memory copy of the text...</li>
<li>Added <code>commitChangesToFile</code> method to update the file on the disk </li>
<li>Added <code>reReadFile</code> method to update the in memory copy</li>
</ul>
<p></p>
<pre><code>public class TextFile extends File{
private static final long serialVersionUID = 1L;
private String text;
/**
* -Create a new textfile, with the supplied text
* -if the file already exists the text
* it will be replaced with supplied text
*
* @param pathname
* @param text
* @throws
*/
public TextFile(String pathname, String text) {
super(pathname);
this.text = text;
if(!exists()) {
createNewTextFile();
}else {
try{
write(text);
} catch (FileNotFoundException e) {
throw new RuntimeException();
}
}
}
/**
* -Creates a new text file by opening the file pointed to by the supplied pathname
* -If the file doesn't exist a new empty text file will be created
*
* @param pathname
* @throws IOException
*/
public TextFile(String pathname) {
super(pathname);
if(!exists()) {
createNewTextFile();
text = "";
}else{
try{
text = read();
} catch (FileNotFoundException e) {
throw new RuntimeException();
}
}
}
/*
* return the text in the textFile
*/
public String getText() {
return text;
}
/**
*/
public void setText(String text){
this.text = text;
}
public void clearText() {
setText("");
}
public void commitChangesToFile() throws FileNotFoundException {
write(text);
}
public void reReadFile() throws FileNotFoundException {
text = read();
}
/**
* Combine the text content from
* a list of files into a single string
*
* @param textFiles
* @return
* @throws FileNotFoundException
*/
public static String textFiles2String(List<TextFile> textFiles) throws FileNotFoundException{
StringBuilder combined = new StringBuilder();
for(TextFile textFile : textFiles) {
combined.append(textFile.getText());
}
return combined.toString();
}
private String read() throws FileNotFoundException {
FileInputStream fis = new FileInputStream(getPath());
InputStreamReader isw = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isw);
StringBuffer fileText = new StringBuffer();
String line;
try {
while ((line = reader.readLine()) != null) {
fileText.append(line+"\n");
}
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(fis != null) {
fis.close();
}
isw.close();
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return fileText.toString();
}
private void write(String text) throws FileNotFoundException{
FileOutputStream fos = new FileOutputStream(getPath());
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter writer = new BufferedWriter(osw);
try {
writer.write(text);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
writer.flush();
writer.close();
if(fos != null) {
fos.close();
}
osw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private void createNewTextFile() {
try {
createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>I think you shouldn't use inheritance here. The <a href=\"http://docs.oracle.com/javase/6/docs/api/java/io/File.html\" rel=\"nofollow noreferrer\"><code>java.io.File</code></a> class is <em>an abstract representation of file and directory pathnames</em> (from the javadoc) and it has methods that a <code>TextFile</code> should not have: <code>list</code>, <code>listFiles</code>, <code>mkdir</code>, etc. <em>Effective Java, 2nd Edition, Item 16: Favor composition over inheritance</em> is a good source for this topic.</p></li>\n<li><p>Instead of the <code>read</code> and <code>write</code> methods I'd use <a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File,%20java.lang.String%29\" rel=\"nofollow noreferrer\"><code>FileUtils.readFileToString</code></a> and <a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#writeStringToFile%28java.io.File,%20java.lang.String,%20java.nio.charset.Charset%29\" rel=\"nofollow noreferrer\"><code>writeStringToFile</code></a> or at least check (or copy) their source. \"... take advantage of the knowledge of the experts who wrote it and the\nexperience of those who used it before you.\" (From <em>Effective Java, 2nd Edition, Item 47: Know and use the libraries</em>)</p></li>\n<li><p>You should specify the charset when you create the <code>OutputStreamWriter</code>. The default could vary from system to system and you may loose non-ASCII characters.</p></li>\n<li><p>Notice the difference between <code>StringBuffer</code> and <code>StringBuilder</code>: <a href=\"https://stackoverflow.com/a/355094/843804\"><code>StringBuilder</code> and <code>StringBuffer</code> in Java on Stack Overflow</a> (The <code>read</code> method could use <strong>non</strong>-thread safe <code>StringBuilder</code> although <code>FileUtils</code> is better. You use the <code>StringBuilder</code>s as local variables inside a method and currently they can't be accessed by other threads so it's enough to use non-thread-safe version.)</p></li>\n<li><p>The code currently throws <code>RuntimeException</code>s on IO errors and <code>RuntimeException</code>s usually stops the whole application. A well-written application or library should handle disks without empty space and other IO errors, so I think throwing checked <code>IOException</code>s would be fine here. Further reading: <em>Effective Java, 2nd Edition, Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors</em></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T21:44:56.123",
"Id": "25837",
"Score": "1",
"body": "Great answer, thanks again! I will have to check out Effective Java.. [1] Initally I didnt extend File - but then I thought hey why not i get all this stuff that I need.. I carelessly didnt think much more about it! [2] I have used the commons before, didn't spot that util though.. very handy and much better written then my read an write. [3] Had charsets in back of my mind, it was one of those things I ment to check out.. thanks for spotting this [4] this was a case of being better safe than sorry but... I dont think Ill have multiple threads operating on.. [5] Good point!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T22:00:50.530",
"Id": "25841",
"Score": "0",
"body": "\"You use the StringBuilders as local variables inside a method and currently they can't be accessed by other threads so it's enough to use non-thread-safe version.\"- Good point - I think I need another cup of coffee!! :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T21:15:23.647",
"Id": "15888",
"ParentId": "15885",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15888",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T19:53:23.763",
"Id": "15885",
"Score": "7",
"Tags": [
"java",
"object-oriented",
"error-handling"
],
"Title": "Class representing a text file"
}
|
15885
|
<p>I was working on a task to implement auto suggest from an array of couple of thousands of strings. </p>
<p>Of course, the first and the easiest implementable was to go through each element and do <code>a[i].startWith(query)</code>. Technically the time complexity of this algorithm then would be \$O(n+(q*m))\$. Here, <code>n</code> equals the number of elements in the array, <code>q</code> equals the number of total matches and <code>m</code> equals the number of characters in the query (I am not sure how accurate I am here).</p>
<p>Regardless, I have created a following <code>Trie</code> which at every node keeps track of every child that has a word ending there.</p>
<p>For example, if the query is <code>"can"</code> then with only three traversal the tree will return <code>cancel, cancer, can and cancellation</code> because the node <code>'n'</code> will have connections to all the sub trees that has a word ending!</p>
<p>I would really like to hear some comments on this.</p>
<pre><code>package utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author Sapan
*/
public class Trie {
private Map<Character, Trie> children;
private String word = null;
private Set<Trie> connections;
static int count = 0;
public Trie() {
this.children = new HashMap<>();
connections = new HashSet<>();
}
/*
* Builds a Trie with given query
*/
public void add(String word) {
if (word == null || "".equals(word.trim())) {
throw new IllegalArgumentException("Query can not be empty or null");
}
Trie t = this;
for (Character c : word.toCharArray()) { //for every character in query do the following....
//add character to the current instance and get the child instance right after adding the current char
if (!t.children.containsKey(c)) {
t.children.put(c, new Trie());
}
t = t.children.get(c);
}
t.word = word;
}
public Set search(String word) {
count = 0;
Trie current = this;
Set<Trie> matches = new HashSet();
for (Character c : word.toCharArray()) {
++count;
current = current.children.get(c);
if (current == null){
return matches;
}
}
//System.out.println(current);
if (current == null) {
return matches;
}
matches = current.connections;
return matches;
}
public Set build() {
//matches = new HashSet<>();
++count;
for (Character c : this.children.keySet()) {
this.connections.addAll(this.children.get(c).build());
}
if (this.word != null && this.word.length() > 0) {
this.connections.add(this);
}
if (this.children.keySet().isEmpty()) {// we are at the leaf node
this.connections.add(this);
}
return this.connections;
}
public static void main(String[] args) {
Trie t = new Trie();
t.add("can");
t.add("kangaroo");
t.add("roo");
t.add("rash");
t.add("ram");
t.add("rat");
t.add("kansas");
t.add("banana");
t.add("ban");
t.add("cancel");
t.add("cancer");
t.add("add");
t.add("addition");
t.add("sub");
t.add("subtraction");
t.add("ape");
t.add("apple");
// t.build();
t.build();
System.out.println(t);
System.out.println(t.count+"----");
//System.out.println(t);
// List<Trie> l = t.search("ap");
//System.out.println(l);
// for (char c = 'a'; c <= 'z'; c++) {
Set<Trie> l = t.search("ca");
System.out.println(t.count);
System.out.println("words starting from ca ");
for (Trie trie : l) {
System.out.println(trie.word);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Eclipse says that the second <code>null</code> check in the <code>search</code> method is dead code:</p>\n\n<pre><code>if (current == null) {\n return matches;\n}\n</code></pre>\n\n<p>Furthermore, it could be refactored to the following:</p>\n\n<pre><code>public Set<Trie> search(final String word) {\n count = 0;\n Trie current = this;\n for (final Character c: word.toCharArray()) {\n ++count;\n current = current.children.get(c);\n if (current == null) {\n return Collections.emptySet();\n }\n }\n return current.connections;\n}\n</code></pre></li>\n<li><p>You should specify the return types:</p>\n\n<pre><code>public Set<Trie> search(final String word) { ... }\npublic Set<Trie> build() {... }\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>public Set search(final String word) { ... }\npublic Set build() {... }\n</code></pre></li>\n<li><p>Consider using </p>\n\n<ul>\n<li><a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29\" rel=\"nofollow\"><code>StringUtils.isBlank</code></a> instead of the <code>(word == null || \"\".equals(word.trim()))</code> and</li>\n<li><a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isNotEmpty%28java.lang.String%29\" rel=\"nofollow\"><code>StringUtils.isNotEmpty</code></a> instead of <code>(this.word != null && this.word.length() > 0)</code>. </li>\n</ul>\n\n<p>I've found them more readable.</p></li>\n<li><p>If I'm right you could iterate over the values directly in the <code>build</code> method:</p>\n\n<pre><code>for (final Trie childTrie: children.values()) {\n connections.addAll(childTrie.build());\n}\n</code></pre></li>\n<li><p>I'd separate the builder logic from the <code>Trie</code> class. Currently clients can easily misuse this class:</p>\n\n<pre><code>t.build();\nt.add(\"can2\");\n</code></pre>\n\n<p>(<em>Effective Java, 2nd Edition, Item 2: Consider a builder when faced with many constructor parameters</em>)</p></li>\n<li><p><code>connections</code> does not seem a good name. It took some time to figure out that this set contains the descendant <code>Trie</code> objects which has a <code>word</code>. I might call it <code>descendantsWithWord</code>. Furthermore, it could contain only the words (strings), not the <code>Trie</code> objects, so it could be simply <code>Set<String> descendantWords</code>.</p></li>\n<li><p>The static <code>count</code> field does not smells well. It is used for two different purposes. I'd create a <code>createdTrieObjects</code> field:</p>\n\n<pre><code>private int createdTrieObjects = 1;\n</code></pre>\n\n<p>and increment it in the <code>add</code> method:</p>\n\n<pre><code>t.children.put(c, new Trie());\ncreatedTrieObjects++;\n</code></pre>\n\n<p>On the other hand, in the <code>search</code> method you could return a <code>SearchResult</code> object which contains the search depth (it's the <code>count</code> currently) and the result strings:</p>\n\n<pre><code>public class SearchResult {\n\n private final Set<String> words;\n private final int searchDepth;\n\n ...\n\n}\n</code></pre>\n\n<p>It contains only a set of string instead of the <code>Set<Trie></code> collection. I think clients should not know about the internal <code>Trie</code> objects. If you don't need the search depth return with <code>Set<String></code> only:</p>\n\n<pre><code>public Set<String> search(final String wordStart) {\n Trie current = this;\n for (final Character c: wordStart.toCharArray()) {\n current = current.children.get(c);\n if (current == null) {\n return Collections.emptySet();\n }\n }\n return Collections.unmodifiableSet(current.descendantWords);\n}\n</code></pre>\n\n<p>Please note the <code>Collections.unmodifiableSet</code> call. It prohibits malicious clients to modify the <code>Trie</code>'s internal structure. (<em>Effective Java, 2nd Edition, Item 39: Make defensive copies when needed</em>)</p></li>\n<li><p>You could eliminate the <code>build</code> method and the <code>word</code> field if you fill the <code>descendantWords</code> in the <code>add</code> method:</p>\n\n<pre><code> public void add(final String word) {\n checkArgument(StringUtils.isNotBlank(word), \"word can not be blank\");\n Trie current = this;\n descendantWords.add(word);\n for (final Character c: word.toCharArray()) {\n if (!current.children.containsKey(c)) {\n current.children.put(c, new Trie());\n createdTrieObjects++;\n }\n current = current.children.get(c);\n current.descendantWords.add(word);\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Some small notes about the edit:</p>\n\n<ol>\n<li><p>Instead of the checked <code>IllegalAccessException</code> I'd throw runtime <code>IllegalStateException</code>. It's rather a programming error if a client tries to add new element to a built trie. (<em>Effective Java, 2nd Edition, Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors</em>)</p></li>\n<li><p>About the <code>s</code> variable in the <code>search</code> method: Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>You could copy the <code>descendantsWithWord</code> set with the <code>HashSet</code>'s constructor instead of the <code>for</code> loop in the <code>search</code> method:</p>\n\n<pre><code>return new HashSet<String>(current.descendantWords);\n</code></pre></li>\n<li><p>The <code>isBuilt</code> flag should be at the beginning of the class with the other fields.</p></li>\n</ol>\n\n<p>Here is the refactored version:</p>\n\n<pre><code>import java.util.Collections;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.commons.lang3.StringUtils;\n\nimport static com.google.common.base.Preconditions.*;\n\npublic class Trie {\n\n private final Map<Character, Trie> children = new HashMap<Character, Trie>();\n private final Set<String> descendantWords = new HashSet<String>();\n\n public Trie() {\n }\n\n public void add(final String word) {\n checkArgument(StringUtils.isNotBlank(word), \"word can not be blank\");\n Trie current = this;\n descendantWords.add(word);\n for (final Character c: word.toCharArray()) {\n if (!current.children.containsKey(c)) {\n current.children.put(c, new Trie());\n }\n current = current.children.get(c);\n current.descendantWords.add(word);\n }\n }\n\n public Set<String> search(final String wordStart) {\n checkNotNull(wordStart, \"wordStart cannot be null\");\n Trie current = this;\n for (final Character c: wordStart.toCharArray()) {\n current = current.children.get(c);\n if (current == null) {\n return Collections.emptySet();\n }\n }\n return Collections.unmodifiableSet(current.descendantWords);\n }\n}\n</code></pre>\n\n<hr>\n\n<p><em>Edit for the comment:</em></p>\n\n<p>In your original implementation there is a set (<code>descendantsWithWord</code>) in every node which refers to <code>Trie</code> objects. In this answer there is a set (<code>descendantWords</code>) in every level which refers to <code>String</code> objects. </p>\n\n<p>The size of the sets are the same, <code>String</code>s (as well as other objects, like <code>Trie</code>s) are on the heap, the set contains only references to objects, so it does not count if they are <code>String</code>s, <code>Trie</code>s or other <code>Object</code>s, there is no difference in memory consumption and there is no duplication. The only difference is the method where the trie builds the set and the generic type of the set (references in the set).</p>\n\n<p>I'm not too familiar with tries and articles on the Wikipedia do not mention that trie nodes should or should not store each descendants (not just references to the nodes of the next level), so I'm not sure that this is \"officially\" a trie or not.</p>\n\n<p>Anyway, if I'm right you need fast search, so memory consumption looks is secondary here. Precalculating and storing the result in a cache (i.e. <code>descendantWords</code>) seems a better solution that traversing a subtree and building strings from characters on every search request as you did it too.</p>\n\n<p>Furthermore, I'd consider using a <code>Map<String, Set<String>></code> structure:</p>\n\n<pre><code>c, [can, cancel, cancer]\nca, [can, cancel, cancer]\ncan, [can, cancel, cancer]\ncanc, [cancel, cancer]\ncance, [cancel, cancer]\ncancel, [cancel]\ncancer, [cancel]\n...\n</code></pre>\n\n<p>It's very similar to the trie above since (1) the trie's nodes are the same as the keys in this map and (2) the values of the map are the same as the <code>descendantWords</code> set in the trie. An advantage could be a simpler implementation, especially with a <code>Multimap</code> from Guava:</p>\n\n<pre><code>public class AutoSuggestCache {\n\n private final SetMultimap<String, String> words = HashMultimap.create();\n\n public AutoSuggestCache() {\n }\n\n public void add(final String word) {\n checkArgument(StringUtils.isNotBlank(word), \"word can not be blank\");\n for (int endIndex = 0; endIndex < word.length(); endIndex++) {\n final String wordStart = word.substring(0, endIndex);\n words.put(wordStart, word);\n }\n }\n\n public Set<String> search(final String wordStart) {\n checkNotNull(wordStart, \"wordStart cannot be null\");\n return Collections.unmodifiableSet(words.get(wordStart));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T15:08:05.500",
"Id": "25879",
"Score": "0",
"body": "The count variable was just for testing only, I got rid of it.. But I really wonder that in your 7th point why do we use SearchResult object rather then just letting the Search method return Set<String>? Do you think the changed Search method will not be enough?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T17:43:35.203",
"Id": "25889",
"Score": "0",
"body": "@Grrrrr: I've created the `SearchResult` object only because of the `count` variable. If you don't need it you could return with `Set<String>`. Check the update, please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T21:43:01.283",
"Id": "26162",
"Score": "0",
"body": "Adding the words to the list while calling the \"add\" method also occurred to me but I thought that this way there will be an extra copy of the every word at every level! Is it not better to keep a reference to the node? (I am not sure if I am being too abstract here!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T21:56:10.650",
"Id": "26230",
"Score": "0",
"body": "@Grrrrr: Check the edit please. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T22:58:41.907",
"Id": "15893",
"ParentId": "15887",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "15893",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T21:09:34.290",
"Id": "15887",
"Score": "11",
"Tags": [
"java",
"trie"
],
"Title": "Trie implementation for left to right wildcard search"
}
|
15887
|
<p>I've quickly made a function to deny or allow access to files that are only used thru Ajax calls.</p>
<p><strong>Key Generator</strong></p>
<pre><code>/**
* Generate a key for file access permission
*
* Function that returns a key to grant access to a PHP file
* that will be consulted by an ajax call.
*
* @param str $salt Any given string to append to the session ID
*
* @return str Access Key
*/
public function file_access_key_generator($salt) {
return sha1(session_id() . $salt);
}
</code></pre>
<p><strong>Key Validation</strong></p>
<pre><code>/**
* Match file access permission key
*
* Function to match the given key with the one generated.
*
* @param str $salt Any given string to append to the session ID
* @param str $key Key to match
*
* @return bollean
*/
public function file_access_key_check($salt, $key) {
return ($this->file_access_key_generator($salt) == $key) ? true : false;
}
</code></pre>
<p>The goal, as mentioned, is to prevent direct access to files that should only be accessed thru an Ajax Call within the application.</p>
<p>The methodology implemented is as follows:</p>
<pre><code>// Generate the key to pass with the Ajax Post variables
$check = $this->my_class->file_access_key_generator(basename(__FILE__, '.php'));
// Validating the key
if (isset($_POST['check']) &&
$my_class->file_access_key_check(basename(__FILE__, '.php'), $_POST['check'])) {
// do stuff...
} else {
// friendly user message stating that the access to the file isn't autorized
}
</code></pre>
<p>Essentially, what is being done is to generate a key combining the file name and the session ID. Both must match otherwise the access isn't allowed.</p>
<p>Does this secures the access to the file or some considerations are to be made in order to actually secure the file that receives Ajax calls, thus preventing a direct browser access or the file being included within another one?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T00:30:32.177",
"Id": "25845",
"Score": "0",
"body": "Whoever told you, that simple SHA1 hash with salt is secure, lied. Also .. where is the rest of the code? This seems more like topic for general StackOverflow site, because there is almost no code to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T10:25:58.507",
"Id": "25863",
"Score": "0",
"body": "@tereΕ‘ko The method implemented is as simple as observed. Other security levels are implemented thru the server and Apache configurations. Nonetheless, I believe that a single line of code can be improved if necessary. The accepted answer, mentions a few improvements about the code presented here. I'll be placing, later on, a new question with a more extensive overview, just after I'm finished rectifying this method."
}
] |
[
{
"body": "<p>Short version:</p>\n\n<ol>\n<li>You may trust your own PHP code, if you write it well.</li>\n<li>You should not trust data received by cookies, <code>$_GET</code> or <code>$_POST</code>.</li>\n<li>Attempting to distinguish data sent from your JavaScript application from malicious input relies on methods that are both hard and easily bypassed.</li>\n</ol>\n\n<p>Long version:</p>\n\n<p>First of all, do you really need the <code>? true : false</code>?\nThe == operator already returns a boolean.</p>\n\n<p>Forbidding direct access is a complex (impossible?) task.\nThe user might just watch the web traffic you send your own Ajax application, and then imitate the output your app would send.</p>\n\n<p>Even if you could prevent that, it'd probably still be pointless - the user could just edit the JavaScript code in many ways (so many in fact that it's probably worthless to try to detect them) so the application would be manipulated into doing what the \"attacker\" wants.</p>\n\n<p>If you are not concerned about the current application user but rather protecting your user against third parties, then using HTTPS might be the best option. Why re-implement what's already available and designed by people who are - let's face it - smarter than both of us combined (and with the added advantage that it's been around for some time, so its flaws have already had more time to be detected and fixed!)</p>\n\n<p>At some point you are using <code>__FILE__</code> to detect if the code is authorized? Does this mean the attacker can directly execute PHP code on your server?\nIf not, then your <code>__FILE__</code> check is worthless.\nIf so, then your <code>__FILE__</code> check is still worthless, as the attacker can just directly call the file functions bypassing your whole security system.</p>\n\n<p>Remember this:</p>\n\n<ol>\n<li>Users can manipulate all sent data. Cookies, <code>$_GET</code> and <code>$_POST</code> data can all be manipulated by the user.</li>\n<li>All data you send your client-side application can be inspected by the user. See Firebug for a good example. If you send <code>some_hash</code> to the client, the user has ways to find that out.</li>\n<li>You may, however, protect your user against third parties.</li>\n<li>Code that is executed in the client-side can be manipulated. HTML, CSS and JavaScript can all be edited.</li>\n<li>Fortunately, those edits are local. Meaning that an user can change the JavaScript that's executed on his computer, but fortunately not the JavaScript that's executed in someone else's computer - provided the server is well implemented.</li>\n</ol>\n\n<p>Ajax code is typically executed client-side (I'm going to bet it's also true in your case), so all your JavaScript can be modified. Your \"receive token\" function can just be modified to include an <code>alert</code> function.</p>\n\n<pre><code>function receive_token() {\n var key = ajax_request_token();\n //Code injected by the user\n alert(key);\n //End code injected by the user\n return key;\n}\n</code></pre>\n\n<p>The user could then proceed to use your key token to pretend he's the application.</p>\n\n<p>Not sure what you mean by \"the file being included within another one\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T10:14:53.407",
"Id": "25862",
"Score": "0",
"body": "Thank you for your insight on this. I'll be improving the function based on your observations. I'll probably be posting a more extensive question after improving this function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T22:34:08.103",
"Id": "15892",
"ParentId": "15889",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15892",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T21:47:04.203",
"Id": "15889",
"Score": "1",
"Tags": [
"security",
"php5"
],
"Title": "File access permission/deny function"
}
|
15889
|
<p>This gets every form element and calculates its width, then changes the input fields depending on the parent-form width:</p>
<pre><code>$ ->
# Alter 'input' Width
inputResize = ->
$('form').each ->
tF = $(this)
formWidth = tF.width()
tF.find('input').each ->
tE = $(this)
inputBorder = (tE.outerWidth() - tE.innerWidth())
inputPadding = parseInt(tE.css('padding-left')) + parseInt(tE.css('padding-right'))
tE.css 'width', ->
(formWidth - inputBorder - inputPadding)
# on Resize
$(window).resize ->
inputResize()
# on Init
inputResize()
</code></pre>
<p>It works as intended, but to learn a bit more I just want to know if there is a smarter way to write this little code in CoffeeScript.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T00:22:22.673",
"Id": "25844",
"Score": "1",
"body": "There is no point in optimizing coffeescript. If you want to write optimal code, write it in native javascript (and that means - no jquery)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T00:36:44.817",
"Id": "25846",
"Score": "0",
"body": "What's coffee script?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T07:25:24.400",
"Id": "25855",
"Score": "0",
"body": "Coffeescript is a little language that compiles to javascript: http://coffeescript.org"
}
] |
[
{
"body": "<p>This is pretty good, you could do that, don't know if you find it much more readable:</p>\n\n<pre><code>$ ->\n # Alter 'input' Width\n inputResize = -> \n $('form').each ->\n tF = $ @\n formWidth = tF.width()\n tF.find('input').each ->\n tE = $ @\n inputBorder = (tE.outerWidth() - tE.innerWidth())\n inputPadding = parseInt(tE.css 'padding-left') + parseInt(tE.css 'padding-right')\n tE.css 'width', -> (formWidth - inputBorder - inputPadding)\n # on Resize\n $(window).resize -> inputResize()\n # on Init\n inputResize()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T07:24:18.083",
"Id": "25854",
"Score": "0",
"body": "Thank you! I didnΒ΄t know the `$ @` :) - learned something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T15:03:23.197",
"Id": "25878",
"Score": "0",
"body": "One last question: Would it be possible to use loops where i used `each()` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T20:34:29.967",
"Id": "25900",
"Score": "0",
"body": "Yes, and the performance would be a little better. But I usually care more about readability. You could do: for input in tF.find('input'), then replace tE = $ @ by tE = $ input"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T15:40:16.203",
"Id": "15891",
"ParentId": "15890",
"Score": "2"
}
},
{
"body": "<p>Here are a few tips:</p>\n<h2>1) Use standard naming convention.</h2>\n<p><code>tE</code> and <code>tF</code> sound like booleans and not a refence to an element.\nTry names like <code>el</code>, <code>$this</code> or <code>that</code> instead.</p>\n<h2>2) Separate complex logic into smaller functions.</h2>\n<p>There's too much going on here.</p>\n<pre><code> inputResize = -> \n $('form').each ->\n tF = $(this)\n formWidth = tF.width()\n tF.find('input').each ->\n tE = $(this)\n inputBorder = (tE.outerWidth() - tE.innerWidth())\n inputPadding = parseInt(tE.css('padding-left')) + parseInt(tE.css('padding-right'))\n tE.css 'width', ->\n (formWidth - inputBorder - inputPadding)\n \n</code></pre>\n<p>Since tF is only used then you can get rid of it and use <code>$(this)</code> directly.\nNext, extract the input width size calculation to one function and you get something like this.</p>\n<pre><code> getNewInputSize = (el, formWidth) ->\n inputBorder = el.outerWidth() - el.innerWidth()\n inputPadding = parseInt( el.css("padding-left"), 10) + parseInt(el.css("padding-right"), 10)\n formWidth - inputBorder - inputPadding\n\n resizeFormInputs = ->\n $("form").each ->\n formWidth = $(this).width()\n $(this).find("input").each ->\n $(this).css "width", getNewInputSize($(this), formWidth)\n</code></pre>\n<p>Final Code:</p>\n<pre><code>$ ->\n getNewInputSize = (el, formWidth) ->\n inputBorder = el.outerWidth() - el.innerWidth()\n inputPadding = parseInt( el.css("padding-left"), 10) + parseInt(el.css("padding-right"), 10)\n formWidth - inputBorder - inputPadding\n\n resizeFormInputs = ->\n $("form").each ->\n formWidth = $(this).width()\n $(this).find("input").each ->\n $(this).css "width", getNewInputSize($(this), formWidth)\n \n $(window).resize(resizeFormInputs).triggerHandler "resize"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T02:07:58.470",
"Id": "15941",
"ParentId": "15890",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15941",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T15:30:22.957",
"Id": "15890",
"Score": "4",
"Tags": [
"coffeescript"
],
"Title": "Altering input field width"
}
|
15890
|
<p>I've an <code>AbstractMessage</code> object (a hierarchy, actually). It represents a small text message and can be sent using <strong>different transport methods</strong>: HTTP, REST and a "mailer" transport. Each transport relies on an external library for executing the transport itself, injected using a DI container.</p>
<p>Message itself <strong>may have different representations</strong> (query string, resource string or an instance of<code>\Swift_Message</code>), based on the transport used. A transport should use the more appropriate representation, again injected using constructor injection.</p>
<pre><code>interface TransportInterface
{
public function executeTransport(AbstractMessage $message, array &$fails = array());
}
class HttpTransport implements TransportInterface
{
/**
* @var \Guzzle\Service\Client
*/
private $client;
/**
* @var Converter\MessageConverterInterface
*/
private $converter;
public function __construct(Client $client, MessageConverterInterface $converter)
{
$this->client = $client;
$this->converter = $converter;
}
public function executeTransport(AbstractMessage $message, array &$fails = array())
{
$representation = $this->converter->convert($message);
/* ... */
}
}
class RestTransport implements TransportInterface
{
/**
* @var \Guzzle\Service\Client
*/
private $client;
/**
* @var Converter\MessageConverterInterface
*/
private $converter;
public function __construct(Client $client, MessageConverterInterface $converter)
{
$this->client = $client;
$this->converter = $converter;
}
public function executeTransport(AbstractMessage $message, array &$fails = array())
{
$representation = $this->converter->convert($message);
/* ... */
}
}
class MailerTransport implements TransportInterface
{
/**
* @var \Swift_Mailer
*/
private $mailer;
/**
* @var Converter\MessageConverterInterface
*/
private $converter;
public function __construct(Swift_Mailer $mailer,
MessageConverterInterface $converter)
{
$this->mailer = $mailer;
$this->converter = $converter;
}
public function executeTransport(AbstractMessage $message, array &$fails = array())
{
$representation = $this->converter->convert($message);
/* ... */
}
}
</code></pre>
<p>The <code>MessageConverterInterface</code> and the actual helper may be fairly simple:</p>
<pre><code>interface MessageConverterInterface
{
/**
* @param AbstractMessage $message
* @return mixed
*/
public function convert(AbstractMessage $message);
}
class MessageHelper
{
/**
* @var Transport\TransportInterface
*/
private $mailer;
public function send(AbstractMessage $message, array &$fails = array())
{
$this->transport->executeTransport($message, $fails);
}
}
</code></pre>
<p><strong>Question</strong>: is this a good OO pattern for the library design? Does the pattern have a name?</p>
|
[] |
[
{
"body": "<p>I would use an abstract class instead of, or in addition to, an interface. You have quite a bit of repetition that could be removed by doing so. The only problem then would be that you would have to use protected instead of private properties and methods, at least for those that you need to share between the abstract class and inheriting class, but I don't think that should make too much of a difference. Remember: You can't create an instance of an abstract class, so you have to use some other \"initiator\" and call that in each constructor.</p>\n\n<pre><code>abstract class AbstractTransport {\n\n protected\n /** @var \\Guzzle\\Service\\Client */\n $client,\n\n /** @var \\Swift_Mailer */\n $mailer,\n\n /** @var Converter\\MessageConverterInterface */\n $converter\n ;\n\n protected function initClient( Client $client, MessageConverterInterface $converter ) {\n $this->client = $client;\n $this->converter = $converter;\n }\n\n protected function initMailer( Swift_Mailer $mailer, MessageConverterInterface $converter ) {\n $this->mailer = $mailer;\n $this->converter = $converter;\n }\n\n public function executeTransport( AbstractMessage $message, array &$fails = array() ) {\n $representation = $this->converter->convert( $message );\n }\n}\n</code></pre>\n\n<p>You might also want to be careful with referencing. It can sometimes be hard to determine where a variable was changed if you don't know that it was assigned by reference somewhere. This is entirely your choice, just a suggestion. I would, however, like to point out that if this parameter is referenced, then setting a default value to it is kind of pointless. If the parameter has not been set, then that value can't be used and should therefore not be used at all to avoid the overhead.</p>\n\n<p>I've never heard of, nor could find a library design pattern, so I can't be sure. As for the name of the pattern you are using? I honestly don't know. But it doesn't matter. Functional code is much better than any code that adheres to a design pattern just for the sake of doing so. Many times I see programmers attempting to force their code into a design pattern, and some times its not even the right pattern. Design patterns are not necessary at this stage. Code for functionality. Once you are comfortable with OOP, then you can start worrying about design patterns and how and when to apply them.</p>\n\n<p>Now, as to whether this is good OOP or not; It appears to be fine, however, this code is incomplete, so it is hard to tell. The concepts seem fine, but the implementation is unsure. You are using encapsulation, inheritance, and a sort of polymorphism. Those are some of the main points of OOP, and you seem to grasp them fairly well, though you could probably stand to look into polymorphism a bit more. You are also using interfaces and dependency injection. These are also important concepts. A couple more points that might help is to ensure you are following the Single Responsibility Principle (can't be sure) and the \"Don't Repeat Yourself\" (DRY) principle. As I pointed out above, you could use some help with DRY.</p>\n\n<p>Finally, your code samples could have easily been reduced to a single interface and class with a note that the other related classes only differed in the commented area. The other classes, except that last, are redundant, whereas that last is unnecessary in this context. If you would have submitted complete classes, this would not be the case. The second interface was slightly relevant, but was also unnecessary.</p>\n\n<p>I hope this helps!</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Example implementation of above code:</p>\n\n<pre><code>class RestTransport extends AbstractTransport {\n public function __construct( $client, $converter ) {\n $this->initClient( $client, $converter );\n }\n}\n</code></pre>\n\n<p>Per comment, here's how to do it with separate classes for each type:</p>\n\n<pre><code>//only worth it if both client and mailer implementations share more than this\nabstract class AbstractTransport implements TransportInterface {\n public function executeTransport( AbstractMessage $message, array &$fails = array() ) {\n $representation = $this->converter->convert( $message );\n }\n}\n\nclass Client extends AbstractTransport {\n public function __construct( Client $client, MessageConverterInterface $converter ) {\n $this->client = $client;\n $this->converter = $converter;\n }\n\n public function executeTransport( AbstractMessage $message, array &$fails = array() ) {\n parent::executeTransport( $message, $fails );\n\n /*\n assuming there will be shared aspects unique to clients\n you can use polymorphism to further extend method\n same in the mailer\n otherwise it is unnecessary to redefine here\n */\n }\n}\n\nclass RestTransport extends Client {\n public function executeTransport( AbstractMessage $message, array &$fails = array() ) {\n parent::executeTransport( $message, $fails );\n\n /* ... */\n }\n}\n</code></pre>\n\n<p>And you'd do pretty much the same thing with the mailer, and any of its classes. The problem with this implementation is that the parent classes, in this case \"Client\", can be instantiated, and by itself it doesn't do anything. This is why I was originally suggesting the abstract class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T15:35:23.410",
"Id": "25881",
"Score": "0",
"body": "I like your analysis that follows your code, so I upvoted your answer. But I really don't like the idea of one class with `init*` methods. And in addition, `init*` methods should be public in order to inject the dependencies using the DI container (or constructor injection should be used)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T15:53:34.620",
"Id": "25882",
"Score": "0",
"body": "@Gremo: The idea behind it was that your individual constructors would call the init* methods they need, and that those init* methods were separate in case you wanted to add something later so that you'd only have to write the code once. Another solution would be to use a couple of actual classes to extend from, one for the client and one for the mailer, each with their specific constructor. This would accomplish the same thing, but require two additional classes. I'll work on adding an example in my answer, should be available soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T16:19:37.040",
"Id": "25884",
"Score": "0",
"body": "@Gremo: Hopefully that edit makes it a little more clear."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T14:11:36.313",
"Id": "15912",
"ParentId": "15899",
"Score": "5"
}
},
{
"body": "<p>@Gremo the use case you've outlined looks like it would be a good candidate to apply the Decorator pattern. Interfaces and Abstract classes are great, but that locks you into an inheritance chain that you might not want in the future. What if you need to modify the message in some way, e.g adding data in a REST call.</p>\n\n<p>A Decorator (or a series of decorators) could handle the responsibilities of your different transport messages, while still supporting dependency injections. The lose coupling this offers, frees you up to design other types of decorators that could handle your messages in other ways that may be completely unrelated to your transport mechanisms (such as persisting the message in a datastore.)</p>\n\n<p>In any case, I've whipped up a rough example of how you might accomplish that.</p>\n\n<pre><code>/**\n * IDecorator\n * \n * Interface\n * \n */\ninterface IDecorator\n{\n # +------------------------------------------------------------------------+\n # ACCESSORS\n # +------------------------------------------------------------------------+\n\n public function __get($index);\n\n public function __set($index, $value);\n\n public function __call($method, $args);\n\n}\n\n\n/**\n * MessageDecorator\n * \n */\nclass MessageDecorator implements IDecorator\n{\n # +------------------------------------------------------------------------+\n # MEMBERS\n # +------------------------------------------------------------------------+\n protected $message;\n\n # +------------------------------------------------------------------------+\n # ACCESSORS\n # +------------------------------------------------------------------------+\n /**\n * Fluent interface for getters\n * \n * @param mixed $index The property\n * @return mixed The return value\n */\n public function __get($index)\n {\n return $this->message->$index;\n }\n\n /**\n * Fluent interface for setters\n * \n * @param mixed $index The property\n * @param mixed $value The property's value\n */\n public function __set($index, $value)\n {\n $this->message->$index = $value;\n } \n\n /**\n * Supports a fluent interface into the decorated class\n * \n * @param method $method A class method\n * @param mixed $args One or many arguments\n * @return mixed The results of the method call if the method exists\n * or a reference to the current decorator (proxy)\n */\n public function __call($method, $args)\n {\n try\n {\n $obj = call_user_func_array( array( $this->message, $method ), $args );\n\n return ( $obj === $this->message ) ? $this : $obj;\n }\n catch( Exception $e )\n {\n throw new Exception(__METHOD__ . ' threw an exception: ' . $e->getMessage());\n }\n }\n\n /**\n * Get/set the original content for reference if needed.\n * \n * @return AbstractMessage Returns a AbstractMessage instance \n */\n public function message( AbstractMessage $message = null )\n {\n if( $message != null )\n {\n $this->message = $message;\n }\n else\n {\n return $this->message;\n }\n }\n\n # +------------------------------------------------------------------------+\n # CONSTRUCTOR\n # +------------------------------------------------------------------------+\n public function __construct( AbstractMessage $message, array &$fails = array() )\n {\n }\n\n}\n\n/**\n * HTTPMessageTransport\n * \n */\nclass HTTPMessageTransport extends MessageDecorator\n{\n\n public function __construct( AbstractMessage $message, array &$fails = array() )\n {\n parent:__construct( $messsage, $fails );\n }\n\n public function send(Client $client, MessageConverterInterface $converter)\n {\n /* Message deployment logic... */\n }\n}\n\n/**\n * RESTMessageTransport\n * \n */\nclass RESTMessageTransport extends MessageDecorator\n{\n\n public function __construct( AbstractMessage $message, array &$fails = array() )\n {\n parent:__construct( $messsage, $fails );\n }\n\n public function send(Client $client, MessageConverterInterface $converter)\n {\n /* Message deployment logic... */\n }\n}\n\n/**\n * MessageCache\n * \n * Assumes a DAOMessageDecorator implementing IDecorator\n */\nclass DAOMessage extends DAOMessageDecorator\n{\n\n public function __construct( AbstractMessage $message )\n {\n parent:__construct( $messsage );\n }\n\n public function save( PDO $pdo )\n {\n /* Message persistence logic... */\n }\n}\n</code></pre>\n\n<p><strong>Example usage:</strong></p>\n\n<pre><code>// Original message\n$message = new AbstractMessage(...);\n$fails = array(...);\n\n// HTTP\n$http_transport = new HTTPMessageTransport( $message, $fails );\n$http_transport->send( $client, $converter );\n\n// REST\n$rest_transport = new RESTMessageTransport( $message, $fails );\n$rest_transport->send( $client, $converter );\n\nor\n\n$message = new AbstractMessage(...);\n$fails = array(...);\n\n// HTTP\n$http_transport = new HTTPMessageTransport( $message, $fails );\n$http_transport->send( $client, $converter );\n\n// REST\n$rest_transport = new RESTMessageTransport( $http_transport->message(), $fails );\n$rest_transport->send( $client, $converter );\n\n// RDBS\n$db_cache = new MessageCache( $rest_transport->message );\n$db_cache->save( $pdo );\n</code></pre>\n\n<p>Even though the different transports are extending the <code>MessageDecorator</code> class in the examples above, you could always create a new category of decorators that implement the <code>IDecorator</code> interface. In the end your original message can still be preserved and passed around amongst other decorators (unrelated to the message transport decorators)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-18T04:08:17.430",
"Id": "17660",
"ParentId": "15899",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T07:18:54.610",
"Id": "15899",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"design-patterns",
"php5"
],
"Title": "When an object has different representations... what's the OO pattern?"
}
|
15899
|
<p>I have a class extending the Dictionary class. This class is used for storing some information (modeled in <code>CustomClass</code>) and accessing it through an integer ID.</p>
<p>To extend this class I have added a <code>TryAdd</code> method, specific to my workflow, which implement different behaviours for the cases of trying to add a new or a already existing <code>CustomClass</code> object.</p>
<pre><code>public class CustomDictionary : Dictionary<int, CustomClass>
{
private void TryAdd(int ID, CustomClass customObject)
{
if (this.ContainsKey(ID))
{
//some operations
}
else
{
//some others operations
this.Add(customObject);
}
}
}
</code></pre>
<p>There will be only one instance object for this class. I want to add locks to provide thread safety and syncronisation for the object of type <code>CustomDictionary</code>.
TryAdd and data accessing operation will frequently occur in parallel for this structure.</p>
<p>Have in mind that at the moment I can't use framework 4.0 so I can't use <code>ConcurrentCollections</code>.</p>
<p>To ensure thread safety I put <code>this.Add(customObject);</code> within a <code>lock(this)</code> but I have read that this is very bad.</p>
<p>Then I read about locking using a private object.</p>
<pre><code>public class CustomDictionary : Dictionary<int, CustomClass>
{
private object lockObject = new Object();
private void TryAdd(int ID, CustomClass customObject)
{
if (this.ContainsKey(ID))
{
//some operations
}
else
{
//some others operations
lock(lockObject)
{
this.Add(customObject);
}
}
}
}
</code></pre>
<p>Is this the good way of doing it? Should I also lock the <code>CustomDictionary</code> object when I read data from that object?</p>
<p>Any improvements for the implementation of this class would be helpfull.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T07:44:55.123",
"Id": "25857",
"Score": "3",
"body": "You should put the lock around all the code in the TryAdd method. If two threads both hit the 'ContainsKey' before an addition is performed, both threads will then add the object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T12:11:17.590",
"Id": "25871",
"Score": "0",
"body": "I think you'd want to change your code to `lock(lockObject)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T15:25:25.190",
"Id": "25880",
"Score": "0",
"body": "The whole .NET standard Dictionary object is not thread safe, even for read operations. You can't really derive from it and hope it will work. The best is to enclose all actions externally with a lock. Or use .NET 4 of course :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T06:47:07.860",
"Id": "25922",
"Score": "0",
"body": "@Rob Klein: the `lock(object)` was a mistake."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T06:48:10.963",
"Id": "25923",
"Score": "0",
"body": "@SimonMourier: Using .NET 4 is always suggested, but like I said in the question, it is not an option. I am lobbying for almost a year for .NET 4 with no results; I gotta stick with what I have."
}
] |
[
{
"body": "<p>First of all, it's very good that you read about the evilness of <code>lock(this)</code>. Avoid it at all costs :)</p>\n\n<p>As for your solution, it's not thread safe, in terms of functionality:</p>\n\n<p>Thread A tries to add an object to id = 123.<br>\nSince this object doesn't exist, the <code>ContainsKey</code> returns <code>false</code>, so the false part of the condition takes place.<br>\nThen Thread A acquires the lock and starts to add its object.</p>\n\n<p>However, Thread A hasn't yet completed its processing, and the system now switches to Thread B.</p>\n\n<p>Strangely enough, Thread B wants to add its own object with the same id = 123 (!).</p>\n\n<p>And, what do you know, since Thread A hasn't finished its processing, Thread B asks if the dictionary <code>ContainsKey(123)</code> and gets <code>false</code>. That's the problem.</p>\n\n<p>Even worse, when Thread B starts its processing of adding the object, an exception would be thrown, since there's already a key assigned with 123.</p>\n\n<p>So, no, the suggested code is not thread safe. That's a classic race condition.</p>\n\n<p>How to resolve this?</p>\n\n<p>Option 1: Double check on read operations</p>\n\n<p>Inside the lock, you can call again to the <code>ContainsKey</code>, which is a read operation. MS provided a cheering statement, that read operations on its data structures (dictionary, list, etc.) are all thread safe.</p>\n\n<p><strong>Update:</strong> from <a href=\"http://msdn.microsoft.com/en-us/library/xfhwa508.aspx\" rel=\"nofollow\">MSDN</a>: A Dictionary can support multiple readers concurrently, <strong>as long as the collection is not modified</strong> (my emphasis). So please ignore this option.</p>\n\n<p>Option 2: Use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx\" rel=\"nofollow\">ReaderWriterLockSlim</a> Class</p>\n\n<p>This class is optimized to the scenario of multiple reads / seldom writes. So when you want to write, you upgrade your lock to have \"write\" scope, and you continue your code.</p>\n\n<p>Option 3: Use a simple lock on the entire <code>TryAdd</code> method. This is very straight forward.</p>\n\n<p>All options are fine, and my personal bias is towards option 2.</p>\n\n<p>Update: see also a related post at Ayende: <a href=\"http://ayende.com/blog/4823/why-is-this-not-thread-safe\" rel=\"nofollow\">Why is this not thread safe?</a></p>\n\n<p>Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T09:46:21.990",
"Id": "26006",
"Score": "0",
"body": "Thank you for your well documentated answer. It really helped me understand this issue and I've implemented the second option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T18:05:48.320",
"Id": "26036",
"Score": "0",
"body": "@CoralDoe, my pleasure!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T12:10:18.653",
"Id": "15909",
"ParentId": "15900",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15909",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T07:23:53.687",
"Id": "15900",
"Score": "4",
"Tags": [
"c#",
"locking"
],
"Title": "Improving handling of data structure used in parallel"
}
|
15900
|
<p>This is my socket.cpp </p>
<pre><code>#pragma hdrstop
#include "MySocketClient.h"
MySocketClient::MySocketClient() throw(SocketException){
WSAData data;
InitializeCriticalSection(&sect_);
if(WSAStartup(MAKEWORD(2,2),&data)!=0){
throw SocketException("Cant load WinSock library");
}
connected_=false;
}
//-----------------------------------------------------------------------------
MySocketClient::~MySocketClient(){
WSACleanup();
}
//-----------------------------------------------------------------------------
void MySocketClient::receive(void){
char recBuf[1024];
while(1){
EnterCriticalSection(&sect_);
memset(recBuf,0,1024);
int recLen=recv(sock_,recBuf,1024,0);
if(recLen==0){
onDisconnect(sock_);
connected_=false;
break;
}else if(recLen<0){
connected_=false;
onConnectionError(sock_);
break;
}else{
onReceive(sock_,recBuf,recLen);
}
LeaveCriticalSection(&sect_);
}
}
//------------------------------------------------------------------------------
void MySocketClient::sendData(char *sendBuf,int sendLen) throw(SocketException){
onSendData(sendBuf,sendLen);
if(send(sock_,sendBuf,sendLen,0)<0){
onConnectionError(sock_);
}
Sleep(200);
}
//------------------------------------------------------------------------------
void MySocketClient::Connect(string hostname,unsigned short port) throw(SocketException){
sock_=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock_==INVALID_SOCKET){
throw SocketException("Cant create socket");
}
HOSTENT *host=gethostbyname(hostname.c_str());
if(host==NULL){
throw SocketException("Cant resolve host");
}
addr_.sin_family=AF_INET;
addr_.sin_port=htons(port);
addr_.sin_addr.S_un.S_addr=*(unsigned long*)host->h_addr_list[0];
if(connect(sock_,(sockaddr*)&addr_,sizeof(sockaddr))==SOCKET_ERROR){
throw SocketException("Connect Error");
}
DWORD dwThreadId;
threadHandle_=CreateThread(NULL,0,startReceive,this,0,&dwThreadId);
if(threadHandle_==NULL){
connected_=false;
shutdown(sock_,SD_BOTH);
closesocket(sock_);
throw SocketException("Receive thread create error");
}
connected_=true;
onConnect(sock_);
}
//------------------------------------------------------------------------------
void MySocketClient::Disconnect(void){
TerminateThread(threadHandle_,0);
shutdown(sock_,SD_BOTH);
closesocket(sock_);
}
//Virtual functions
void MySocketClient::onReceive(SOCKET sock,char *recBuf,int recLen) throw(SocketException){
}
void MySocketClient::onDisconnect(SOCKET sock){
}
void MySocketClient::onConnectionError(SOCKET sock){
}
void MySocketClient::onSendData(char *sendBuf,int sendLen){
}
void MySocketClient::onConnect(SOCKET sock){
}
#pragma package(smart_init)
</code></pre>
<p>This is mysocket.h</p>
<pre><code>//---------------------------------------------------------------------------
#ifndef MySocketClientH
#define MySocketClientH
#include <winsock2.h>
#include <string.h>
#include "socketException.h"
#include <process.h>
using namespace std;
class MySocketClient{
private :
sockaddr_in addr_;
unsigned short port_;
string hostname_;
CRITICAL_SECTION sect_;
HANDLE threadHandle_;
bool connected_;
protected :
SOCKET sock_;
//Virtual functions
virtual void onConnect(SOCKET sock);
virtual void onReceive(SOCKET sock,char *recBuf,int recLen) throw(SocketException);
virtual void onDisconnect(SOCKET sock) ;
virtual void onConnectionError(SOCKET sock);
virtual void onSendData(char *sendBuf,int sendLen);
private :
void receive(void);
static DWORD WINAPI startReceive(LPVOID param){
MySocketClient *_this=(MySocketClient*)param;
_this->receive();
return 0;
}
public :
MySocketClient() throw(SocketException);
~MySocketClient();
void sendData(char *sendBuf,int sendLen) throw(SocketException);
void Connect(string hostname,unsigned short port) throw(SocketException);
void Disconnect(void);
bool isConnected(void){
return connected_;
}
};
#endif
</code></pre>
<p>The question that i asked is on the followink link <a href="https://stackoverflow.com/questions/12471761/creating-multiple-tcp-socket-connections">https://stackoverflow.com/questions/12471761/creating-multiple-tcp-socket-connections</a></p>
|
[] |
[
{
"body": "<p>The code generally looks ok. Does it work as expected?</p>\n\n<p>What is the reason for using a critical section in <code>MySocketClient::receive()</code>? Are you sharing common data between multiple threads? It doesnt appear so, and even if you were, this wouldnt protect anything since each instance has its own critical section variable. In order for multiple threads to execute code mutually exclusively, then they all need to use the same critical section variable. So, to summarize, I think you can remove the critical section variable.</p>\n\n<p>Regarding the design, it would be more cohesive if you separated the socket communication from the thread handling in separate classes. It will work as is, but it would be cleaner to separate them.</p>\n\n<p>Its generally cleaner to initialize the class variables in the constructor with a constructor initializer list as follows:</p>\n\n<pre><code>MySocketClient::MySocketClient() throw(SocketException) : \n connected_(false), sock_(-1) // etc\n{\n}\n</code></pre>\n\n<p>If you plan on leaving the thread creation code in Connect(), then all code should be placed before creating the thread to avoid race conditions, as follows:</p>\n\n<pre><code>void MySocketClient::Connect(string hostname,unsigned short port) throw(SocketException){\n\n // ...\n\n // Notice I moved these 2 lines \n connected_=true;\n onConnect(sock_);\n\n DWORD dwThreadId;\n threadHandle_=CreateThread(NULL,0,startReceive,this,0,&dwThreadId);\n if(threadHandle_==NULL){\n connected_=false;\n shutdown(sock_,SD_BOTH);\n closesocket(sock_);\n throw SocketException(\"Receive thread create error\");\n }\n\n // Dont put any code here that accesses instance variables to avoid race conditions\n}\n</code></pre>\n\n<p>One last thing, its usually considered good form to provide a way to exit the infinite while loop. So you should consider changing is as follows:</p>\n\n<pre><code>void MySocketClient::receive(void){\n char recBuf[1024];\n while(run_){\n // ...\n }\n}\n</code></pre>\n\n<p>Then, add a setter/getter to the MySocketClient class to set the field, thus allowing the client to exit gracefully. It should be protected, preferably by a read/write lock.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T12:48:49.877",
"Id": "26146",
"Score": "0",
"body": "i think i should some code to store the handles of thread in an array and write a function to pass the thread handle when any communication need to be stopped and Can you please give a main file where i should i create class objects dynamically depending upon the no of ip i have.As i am not able to do this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T05:32:45.353",
"Id": "26236",
"Score": "1",
"body": "@Dany I added a main() on my original stack overflow answer you can use. You shouldnt need the thread id (handle) for anything except for a call to pthread_join()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-11T08:25:57.820",
"Id": "26731",
"Score": "0",
"body": "sir my design changes somewhat i need some what of your help....can i mail you the code that i made as its an sample code pasting won't be good idea,you can send me the mail at trn200190@gmail.com please sir"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T08:09:01.130",
"Id": "15902",
"ParentId": "15901",
"Score": "3"
}
},
{
"body": "<p>It could be that at 100 connections you won't notice, but you should be aware that the 1-thread-per-connection model does not scale well and is not in line with the current state of the art. See what is written about the <a href=\"https://www.google.com/search?q=c10k+problem\" rel=\"nofollow\">c10k problem</a>.</p>\n\n<p>With a thread-per-connection approach you will have high memory overhead from each thread's stack, and you will spend a lot of time context switching.</p>\n\n<p>What scalable network code does these days is:</p>\n\n<ul>\n<li><p>On Unix: Use <code>epoll</code> (Linux), <code>kqueue</code> (*BSD) or equivalents with non-blocking sockets. The model here is that you ask the kernel to block until some file descriptor is ready for I/O. It informs you which fd is ready and you can issue the non-blocking read or write.</p></li>\n<li><p>On Windows: Issue your I/O with \"overlapped\" I/O, and use <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa365198(v=vs.85).aspx\" rel=\"nofollow\">I/O completion ports</a> or APC to be notified when the I/O is finished.</p></li>\n</ul>\n\n<p>In both of these models the ultimate goal is to not spend time waiting for synchronous I/O, such as a blocking read or write to the socket. This allows you to process multiple requests without needing multiple threads.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T18:24:13.757",
"Id": "15921",
"ParentId": "15901",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15902",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T07:49:17.350",
"Id": "15901",
"Score": "4",
"Tags": [
"c++",
"c",
"multithreading",
"tcp"
],
"Title": "Multithreaded Socket code to connect to 100 different machines"
}
|
15901
|
<p>I have a scenario wherein I have to filter a collection in a <code>PagedCollectionView</code>.
The filter criteria are <code>Name</code> and status which are checkboxes with Enabled and Disabled labels. If <code>Enabled</code> is checked it should filter out the list with all enabled rules and vice-versa. I have given it a try, but I believe this isn't the best way of doing it.</p>
<pre><code> private PagedCollectionView _autoDepRuleList;
public PagedCollectionView AutoDepRuleList
{
get
{
return this._autoDepRuleList;
}
set
{
this._autoDepRuleList = value;
RaisePropertyChanged("AutoDepRuleList");
}
}
private bool _isEnabled;
public bool IsEnabled
{
get
{
return this._isEnabled;
}
set
{
this._isEnabled = value;
RaisePropertyChanged("IsEnabled");
}
}
private bool _isDisabled;
public bool IsDisabled
{
get
{
return this._isDisabled;
}
set
{
this._isDisabled = value;
RaisePropertyChanged("IsDisabled");
}
}
private string _name;
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
RaisePropertyChanged("Name");
}
}
public void Search()
{
var tempList = new AutoDeploymentRuleList();
var filterList = new AutoDeploymentRuleList();
foreach (AutoDeploymentRule item in this.AutoDepRuleList)
{
tempList.Add(item);
}
if (IsEnabled && IsDisabled)
{
foreach (var item in tempList)
{
filterList.Add(item);
}
}
else if (IsEnabled)
{
foreach (var item in tempList.Where(r => r.Status.Equals("Enabled")))
{
filterList.Add(item);
}
}
else if (IsDisabled)
{
foreach (var item in tempList.Where(r => r.Status.Equals("Disabled")))
{
filterList.Add(item);
}
}
else
{
foreach (var item in tempList)
{
filterList.Add(item);
}
}
this.AutoDepRuleList = new PagedCollectionView(filterList.Where(r => r.Name.ToLower().Contains(this.Name.ToLower())));
</code></pre>
<p>Now the idea is to do away with the above block and go for the below logic. I did it for the <code>Name</code> property, but I'm not sure how I can do it for the <code>Status</code> property which can be anything either <code>Enabled</code> or <code>Disabled</code>.</p>
<pre><code> this.AutoDepRuleList.Filter = new System.Predicate<object>(o =>
{
AutoDeploymentRule rule = (AutoDeploymentRule)o;
if (rule.Name.ToLower().IndexOf(this.Name.Trim().ToLower()) >= 0)
{
return true;
}
else
{
return false;
}
});
}
</code></pre>
<p>How can I optimize it by removing those redundant where clauses and putting the entire thing under <code>Predicate<object></code>?</p>
|
[] |
[
{
"body": "<p>If performance is your concern, won't boxing and unboxing the variable unnecessarily add an overhead? Why would you want to do that?</p>\n\n<p>Wouldn't this be much easier?</p>\n\n<pre><code>this.AutoDepRuleList //if this is queryable/enumerable, or convert first\n.Where(r => (isDisabled && r.Status.Equals(\"Disabled\")) || \n (isEnabled && r.Status.Equals(\"Enabled\")) ||\n (!isDisabled && !isEnabled))\n//either ToList() if you just need to assign to another list, or ForEach if you want\n//to iterate over list and do something\n .ForEach(filterList.Add);\n</code></pre>\n\n<p>Update: had forgotten the condition where both isDisabled and isEnabled were false. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T17:05:33.970",
"Id": "25887",
"Score": "1",
"body": "you could also go var filterList = [Roopesh's linq].ToList()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T17:09:29.893",
"Id": "25888",
"Score": "0",
"body": "yup.. any idea which is more efficient? Anyways I put a foreach there so it'll work if the method has some additional logic as well instead of just .Add()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T06:34:59.247",
"Id": "25921",
"Score": "0",
"body": "hi @RoopeshShenoy, thanks for the post; as AutoDepRuleList is of type PagedCollectionView we can't apply linq methods to it directly,\n\n this.AutoDepRuleList.SourceCollection.OfType<AutoDeploymentRule>().Where(r => (IsDisabled && r.Status.Equals(\"Disabled\")) ||\n (IsEnabled && r.Status.Equals(\"Enabled\")) ||\n (!IsDisabled && !IsEnabled));"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T07:23:18.527",
"Id": "25925",
"Score": "0",
"body": "Great if it works for you!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T16:05:24.817",
"Id": "15916",
"ParentId": "15904",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T11:10:29.213",
"Id": "15904",
"Score": "2",
"Tags": [
"c#",
"performance",
"linq"
],
"Title": "Filter a collection in a PagedCollectionView"
}
|
15904
|
<p>I'm writing a simple automatic backup/versioning bash script.</p>
<p>It should basically mirror a directory structure somewhere, and then copy files over there when they've been altered. The ghost files should then be named <code>filename.YYYYMMDD-HHMMSS.ext</code> (the included date/time being the time of last modification).</p>
<p>This is what I came up with - it seems to work already, sort of. but since I've never written shell scripts before, I suspect I might be doing some things fundamentally wrong and inefficiΓ«nt.</p>
<p>How can I make this faster? The iterating over files seems to be really slow.
Is this robust? It seems to "lock up" without error messages sometimes, and I can't explain or understand why. What am I doing wrong?</p>
<p>I intend to run this as a cron job, every 30 minutes or so.</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/sh
# $1 : backup "root"
# $2 : from: directory to be backed up
# $3 : to: destination
rpath=$1
for f in $(find $2); do
r=$(./rel.sh $rpath $f)
if [ -f $f ]
then
basename=$(basename $f)
dir=$(dirname $r)
name=$(echo $basename | cut -d'.' -f1)
ext=$(echo $basename | cut -d'.' -f2)
mod=$(stat --format=%y $f | awk -F'.' '{printf $1}' | sed 's/[-:]//g' | sed 's/ /-/g')
if [ ! -f "$3/$dir/$name.$mod.$ext" ]
then
echo "+f $mod $r"
# cp $f "$3/$dir/$name.$mod.$ext"
fi
elif [ -d $f ]
then
if [ ! -d "$3/$r" ]
then
echo "+dir $r"
mkdir "$3/$r"
fi
fi
done
exit
</code></pre>
|
[] |
[
{
"body": "<p>Implementing solutions to problems like this is good for exercise purposes. It is good for learning.</p>\n\n<p>But it is almost never good to re-invent the wheel in production systems. Please have a look at well-established data synchronization software such as <a href=\"http://en.wikipedia.org/wiki/Rsync\">rsync</a> and perform some research around it and other data synchronization/backup/snapshot techniques.</p>\n\n<p>So, your question is good until \"<em>I intend to run this as a cron job, every 30 minutes or so.</em>\" :-) I am not that bash expert myself, to others might point out the potential weaknesses of your approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T20:27:07.080",
"Id": "25864",
"Score": "2",
"body": "Thank you for your feedback! It isn't really a production environment, and I'm definetly interested in learning."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T20:24:02.993",
"Id": "15906",
"ParentId": "15905",
"Score": "7"
}
},
{
"body": "<p>why not just tar up the entire folder:</p>\n\n<pre><code>tar -cvzf backup-`date +%Y-%m-%d`.tar.gz /path/to/backup\n</code></pre>\n\n<p>or use find to do it all</p>\n\n<pre><code># in script go to path\ncd /path/to/folder;\n# find all folders and make them in /tmp/backup-todays-date\nfind . -type d -exec mkdir /tmp/backup`date +%Y-%m-%d`/{} \\; \n# cp all files from current path to /tmp/backup-todays-date\nfind . -type f -exec cp {} /tmp/backup`date +%Y-%m-%d`/{} \\;\n</code></pre>\n\n<p>ls -l /tmp/backup2012-09-23/</p>\n\n<p>using top method produced 1 file for all content and then you could use logrotate to rotate tar files after 10 backups or something. so you don't have backup's filling up disk</p>\n\n<p>The 2nd method will continue on creating /tmp/backup-date folders no easy way of managing this unless you wrote another script to monitor them that did something like</p>\n\n<pre><code>find /tmp/backup* -mtime +10 -exec rm -rf {} \\;\n</code></pre>\n\n<p>the initial rsync suggestion is great for server to server copy and could be used for local copying too, the thing that stood out - is your script adding dates to files which means you wish to be able to look back on same file X amount days ago, doing rsync version control visit <a href=\"http://www.howtoforge.com/backing-up-with-rsync-and-managing-previous-versions-history\" rel=\"nofollow\">http://www.howtoforge.com/backing-up-with-rsync-and-managing-previous-versions-history</a></p>\n\n<p>The alternative if files are being backed up for version control purposes would be to use something like svn(subversion) or git to check in/out files this way there is an external process managing changes.</p>\n\n<p>and finally using tar to do same thing </p>\n\n<pre><code>mkdir /tmp/backup`date +%Y-%m-%d`; (cd /path/to/backup; tar -cvzf - .) | (cd /tmp/backup`date +%Y-%m-%d`; tar -xvzf -)\n</code></pre>\n\n<p>all the best</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T22:30:32.420",
"Id": "25865",
"Score": "0",
"body": "Thank you for your time and answer. My script isn't just creating periodic copies of the whole folder, and it's not what I'm intending to do. It's storing ghost copies of files only when they have been modified. I know and use svn and git and it's also definetly not what I want to be using here.\n\nI'd just like to *know* how to make something like this. The environment I'll be using it in is not professional or in production."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T08:38:15.213",
"Id": "25866",
"Score": "0",
"body": "cp -p preserves permissions and file dates, tar will also perserve this too. so either the final option of using tar or the outlined find but use -p. But if you are only interested in when files have been modified then rsync is your best bet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T19:50:41.217",
"Id": "25867",
"Score": "0",
"body": "how can i forget also if you were re-inventing the wheel a much easier way is to md5sum both files and if different then to copy."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T21:03:36.947",
"Id": "15907",
"ParentId": "15905",
"Score": "0"
}
},
{
"body": "<p>The previous answers addressed some alternative ways of accomplishing the backup and versioning goals; in this answer I'll comment on three or four possible improvements to your script.</p>\n\n<p>β’ For clarity, I prefer at the start of a script like this to copy all of the <code>$1, $2, $3</code> parameters to named variables, as you did for the first of them.<br>\nβ’ The <code>find $2</code> lists all the files and directories in $2 and below, but presumably the bulk of those files will have been treated already in previous runs. For example, to avoid processing files older than second-previous run, in each run write a time-marker file and use <code>-newer</code>:</p>\n\n<pre><code>mv Mark1 Mark0; mv Mark2 Mark1; touch Mark2\nfind -newer Mark0 ... \n</code></pre>\n\n<p>β’ Your script runs four new processes while setting <code>basename, dir, name</code>, and <code>ext</code>. To avoid all those separate processes, use various shell parameter expansions as below. (Eg, when f=/home/tx.7/xyz.axi.pan, these produce <code>xyz.axi.pan</code>, <code>/home/tx.7</code>, <code>xyz.axi</code>, and <code>pan</code>, respectively. Note, these expansions should work for all the files in your directories as listed by <code>find</code>, but if used in other scripts will stumble when given names like <code>.</code> or <code>/</code> or some other edge cases.)</p>\n\n<pre><code> basename=${f##*/}\n dir=${f%/*}\n name=${basename%.*}\n ext=${basename##*.}\n</code></pre>\n\n<p>β’ The <code>for f in $(find $2)</code> structure is likely to produce a large list of file names and then process it. That list need not be stored if you instead use (eg)</p>\n\n<pre><code>find $2 -exec filescript '{}' $3 \\;\n</code></pre>\n\n<p>where <code>filescript</code> represents a separate script that does the stuff found inside your current <code>for</code> loop. Of course you can also add <code>-newer Mark2</code> to the <code>find</code> command:</p>\n\n<pre><code>find $2-newer Mark2 -exec filescript '{}' $3 \\;\n</code></pre>\n\n<p>I would expect using <code>-exec</code> to be faster than using the shell <code>for</code> loop, but it might be worthwhile to run a timing test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T22:44:41.197",
"Id": "25868",
"Score": "0",
"body": "Thank you very much for your constructive feedback and suggestions. I'll definetly look into them and see how they affect the script. I'm really glad you took the time to correct this script, instead of offering alternative versioning tools. It allows me to learn and better understand shell scripting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T22:27:32.053",
"Id": "15908",
"ParentId": "15905",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15908",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-23T20:20:07.617",
"Id": "15905",
"Score": "8",
"Tags": [
"linux",
"bash",
"shell"
],
"Title": "Can I speed up this simple versioning/backup script?"
}
|
15905
|
<p>I'm currently studying Java by myself. The book I'm using (while very good)
lacks feedback (obviously). While trying to write this program, I found myself solving most of the problems I've encountered by trial and error and makeshift solutions, which I fear might have led to some haphazard code. A good example would be the initialization of several variables: <code>bestline</code> and <code>bestrow</code> in the <code>Testing</code> class, and <code>bestMove</code> in the <code>Board</code> class.</p>
<p>The code also feels very cumbersome. I would really appreciate it if you could review my code and comment on where I can improve, best practices I should adopt, etc...</p>
<pre><code>import java.util.Scanner;
public class Testing
{
public static void main(String[] args) {
int turn = 0; // turn is either 0 or 1 , changed with Math.abs(turn-1).
Board board = new Board ();
board.initializeBoard(board);
Scanner myScanner = new Scanner(System.in);
for( ; board.scoreBoard(board) == 1000 ; ){
if (turn == 0){ //X's turn
int line = myScanner.nextInt(); // get a line
int row = myScanner.nextInt(); // get a row
for ( ; board.Square[line][row] != 0 ;line = myScanner.nextInt() , row = myScanner.nextInt() ){ // run while the square at [line][row] is taken,print the line and pick another.
System.out.println("Square Taken , please pick another.");
}
board.Square[line][row] = 1; //make the move (1 means X)
board.printBoard(board);
}
if (turn == 1){ //O's turn
int lastboard = 100; // O's worst case scenario so it has somthing to compare in the first round. // this will keep the best score that player can get
int bestline=0; // no meaning because I had to initialize
int bestrow =0; // no meaning because I had to initialize
for(int line = 0 ; line <3 ; line++){ //
for(int row = 0 ; row < 3 ; row ++){ //go over the entire board
if(board.Square[line][row]==0){ //if (Square is empty)
board.Square[line][row] = 2; // place 2 (2 means O) , this "tries" a move.
int tmpboard = board.scoreBestMove(board, Math.abs(turn-1)); //"scores" the move just made, keeps it in a temporary int.
if(tmpboard<=lastboard){ // if the move just made is better than previous best move.
lastboard = tmpboard; // keep the new score as the best score.
System.out.println(line+" "+row+" this is " +board.scoreBestMove(board, Math.abs(turn-1))); // printing how it scores every move for debugging. // ignore.
bestline = line; // keeps the best moves line.
bestrow = row; // keeps the best moves row.
}
board.Square[line][row] = 0; // resets the square.
}
}
}
board.Square[bestline][bestrow] = 2; // once the loop is over , do the best move you found.
board.printBoard(board); // print the board.
}
turn = Math.abs(turn-1); // change the turn.
}
System.out.println(board.scoreBoard(board));
}
}
</code></pre>
<p><strong>Board:</strong></p>
<pre><code>import java.math.*;
public class Board {
int Square[][] = new int [3][3];
Board(){
int Square[][] = new int [3][3];
}
// constructor for a new board , makes an int array size 3/3.
public void initializeBoard (Board board){
for(int i=0 ; i<3 ; i++)
for(int j=0 ; j<3 ; j++)
Square[i][j] = 0;
}
public int scoreBoard (Board board){
if( (board.Square[0][0] == 1 & board.Square[0][1] == 1 & board.Square[0][2] == 1) || // 1'st line X
(board.Square[1][0] == 1 & board.Square[1][1] == 1 & board.Square[1][2] == 1) || // 2'nd line X
(board.Square[2][0] == 1 & board.Square[2][1] == 1 & board.Square[2][2] == 1) || // 3'rd line X
(board.Square[0][0] == 1 & board.Square[1][0] == 1 & board.Square[2][0] == 1) || // 1'st row X
(board.Square[0][1] == 1 & board.Square[1][1] == 1 & board.Square[2][1] == 1) || // 2'nd row X
(board.Square[0][2] == 1 & board.Square[1][2] == 1 & board.Square[2][2] == 1) || // 3'rd row X
(board.Square[0][0] == 1 & board.Square[1][1] == 1 & board.Square[2][2] == 1) || // 1'st diag X
(board.Square[0][2] == 1 & board.Square[1][1] == 1 & board.Square[2][0] == 1) ){ // 2'nd diag X
return 100; //X win
}
if( (board.Square[0][0] == 2 & board.Square[0][1] == 2 & board.Square[0][2] == 2) || // 1'st line X
(board.Square[1][0] == 2 & board.Square[1][1] == 2 & board.Square[1][2] == 2) || // 2'nd line X
(board.Square[2][0] == 2 & board.Square[2][1] == 2 & board.Square[2][2] == 2) || // 3'rd line X
(board.Square[0][0] == 2 & board.Square[1][0] == 2 & board.Square[2][0] == 2) || // 1'st row X
(board.Square[0][1] == 2 & board.Square[1][1] == 2 & board.Square[2][1] == 2) || // 2'nd row X
(board.Square[0][2] == 2 & board.Square[1][2] == 2 & board.Square[2][2] == 2) || // 3'rd row X
(board.Square[0][0] == 2 & board.Square[1][1] == 2 & board.Square[2][2] == 2) || // 1'st diag X
(board.Square[0][2] == 2 & board.Square[1][1] == 2 & board.Square[2][0] == 2) ){ // 2'nd diag X
return 0; // O win
}
if ( board.Square[0][0] == 0 || // this "if" gets called if no player won yet, this checks to see if the game is over , it returns 1000 if the game is not over.
board.Square[0][1] == 0 ||
board.Square[0][2] == 0 ||
board.Square[1][0] == 0 ||
board.Square[1][1] == 0 ||
board.Square[1][2] == 0 ||
board.Square[2][0] == 0 ||
board.Square[2][1] == 0 ||
board.Square[2][2] == 0){
return 1000; // game not over
}
return 50; // draw , gets to this "if" only if no other if is called.
}
// get a board: returns 100 if X won , 0 if O won , 50 if draw and 1000 if game not over.
public void printBoard (Board board){
for(int i=0 ; i<3 ; i++){
for(int j=0 ; j<3 ; j++){
System.out.print("|"+ Square[i][j]+ "|");
}
System.out.println();
}
}
public int scoreBestMove (Board board , int turn){
if(board.scoreBoard(board)!= 1000){ // if(game over)
return board.scoreBoard(board); // return the score
}
int bestmove=50; // no meaning because I had to initialize
int tmpbestmove; // temoprary int to store the value the recursion returns , so I dont have to call it twice.
switch (turn){
case 0: //X's turn
bestmove = 0; // makes the bestmove's score X's worst case scenario.
break;
case 1://O's turn
bestmove = 100;// makes the bestmove's score O's worst case scenario.
break;
}
for(int i = 0 ; i <3 ; i++){ //
for (int j = 0 ; j <3 ; j++){ //go over the entire board
if(board.Square[i][j]==0){ //if (Square is empty)
switch(turn){
case 0: // X's turn
board.Square[i][j] = 1; // place 1 (1 means X) , this "tries" a move.
tmpbestmove = board.scoreBestMove(board, Math.abs(turn-1)); // call itself with the board and the other player's turn to rate the move it just made.
if(tmpbestmove>bestmove){ //if the move scores better (for X) than any previous moves
bestmove = tmpbestmove; // keep that score in bestmove.
}
board.Square[i][j] = 0; // reset that Square to empty.
break;
case 1: // O's turn
board.Square[i][j] = 2; // place 2 (2 means O) , this "tries" a move.
tmpbestmove = board.scoreBestMove(board, Math.abs(turn-1));// call itself with the board and the other player's turn to rate the move it just made.
if(tmpbestmove<bestmove){ //if the move scores better(for O) than any previous moves
bestmove = tmpbestmove; // keep that score in bestmove.
}
board.Square[i][j] = 0; // reset that Square to empty.
break;
}
}
}
}
return bestmove; // return the score for the best option , NOTE : this does not return a move , but the score for the callers move.
}
// gets a board and a turn , returns the score for the move.
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T11:58:05.977",
"Id": "25934",
"Score": "0",
"body": "Hi , been getting some great answers though one part remains unreviewed the recursive scoreBestMove , I know beggars can't be choosers but I would really love for that function to get reviewed."
}
] |
[
{
"body": "<p>Here are some simple fixes you should make to the beginning of the <code>Board</code> class. I'll let someone else tackle another part.</p>\n\n<pre><code>public class Board {\n int Square[][] = new int [3][3];\n\n\n Board(){\n int Square[][] = new int [3][3];\n }\n// constructor for a new board , makes an int array size 3/3.\n\npublic void initializeBoard (Board board){\n for(int i=0 ; i<3 ; i++)\n for(int j=0 ; j<3 ; j++)\n Square[i][j] = 0;\n}\n</code></pre>\n\n<p>In the above code, do the following:</p>\n\n<ol>\n<li><p>Prefer lowercase variable names.</p></li>\n<li><p>Eliminate the array construction in the constructor that you don't use. Since you declare it there, it goes out of scope at the end of the constructor. It temporarily hides your instance variable of the same name, but it isn't referenced and isn't necessary.</p></li>\n<li><p>Don't pass board into <code>initializeBoard()</code> since you don't use it and is confusing.</p></li>\n<li><p>Consider moving the code of <code>initializeBoard</code> into <code>Board()</code>. Ask yourself: is there ever a time I would want an uninitialized board? If the answer is no, don't require the caller to initialize it.</p></li>\n<li><p>Consider eliminating the <code>initializeBoard</code> code. <a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html\" rel=\"nofollow\">As you can see here, primitive types in Java have default values.</a> For int, the value is 0. Therefore setting each element of the square array to 0 does nothing.</p></li>\n</ol>\n\n<p>The resulting code would look like this:</p>\n\n<pre><code>public class Board {\n int square[][] = new int[3][3];\n Board() {}\n}\n</code></pre>\n\n<p>Since I changed the name of your variable from \"Square\" to \"square\", you'll need to fix the references in the rest of your code.</p>\n\n<p>Also, consider introducing <code>enum</code>s for magic constants in your code and use them instead.</p>\n\n<pre><code>public enum SquareValue {\n Blank,\n X,\n O\n}\n\npublic enum BoardValue {\n X_Wins(100),\n O_Wins(0),\n Draw(50),\n GameNotOver(1000);\n\n public int value;\n\n BoardValue(int value) {\n this.value = value; \n }\n}\n</code></pre>\n\n<p>It will make it more readable. Of course we'll have to revisit the <code>Board</code> code I have above.</p>\n\n<pre><code>public class Board {\n SquareValue[][] square = new SquareValue[3][3];\n Board() {\n for (int i=0; i<3; i++) {\n for (int j=0; j<3; j++) {\n square[i][j] = SquareValue.Blank;\n }\n }\n }\n}\n</code></pre>\n\n<p>Then, since <code>scoreBoard</code> is an instance method, don't pass a board. Instead use the board of the current instance. I would also change it to <code>getScore()</code> to better reflect the purpose.</p>\n\n<pre><code>public int getScore() { ... }\n</code></pre>\n\n<p>Also, refactor some of your code into smaller pieces. For example, create the following functions on the <code>Board</code> class.</p>\n\n<pre><code>public boolean isWinningBoard(SquareValue value) { ... }\npublic boolean isFullBoard() { ... }\n</code></pre>\n\n<p>You could also break down <code>isWinningBoard</code> using additional functions. If you don't expect these to be called from outside this class, make them private or protected.</p>\n\n<pre><code>private boolean isWinningRow(int row, SquareValue value) { ... }\nprivate boolean isWinningColumn(int column, SquareValue value) { ... }\n</code></pre>\n\n<p>Using those functions, my <code>getScore()</code> function that replaces your <code>scoreBoard</code> function would look like this:</p>\n\n<pre><code>public BoardValue getScore() {\n if (isWinningBoard(SquareValue.X)) {\n return BoardValue.X_Wins;\n }\n else if (isWinningBoard(SquareValue.O)) {\n return BoardValue.O_Wins;\n }\n else if (isFullBoard()) {\n return BoardValue.Draw;\n }\n else {\n return BoardValue.GameNotOver;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T18:34:38.390",
"Id": "25890",
"Score": "0",
"body": "You would also need `isWinningDiagonal()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T18:49:07.213",
"Id": "25891",
"Score": "0",
"body": "Of course. This wasn't meant to be complete. I would probably name it hasWinningDiagonal(SquareValue value) since there are 2 diagonals to check. There are many ways to slice and dice that big scoreBoard method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:00:53.717",
"Id": "25894",
"Score": "0",
"body": "I'm glad you found it to be helpful. Have fun!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:05:55.960",
"Id": "25895",
"Score": "0",
"body": "WOW! thank you for the answer! this makes the code so much more readable , also it actually helped me understand some of the concepts I had not fully grasped. I did not expect such a detailed answer =).-edited for grammer"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T18:22:09.793",
"Id": "15920",
"ParentId": "15911",
"Score": "10"
}
},
{
"body": "<p>Welcome to CodeReview. Your concern for the quality of your code is warranted, but don't let that put you down: digging through that book on your own, writing your own code and even exposing it to the Internet's critical eyes are impressive first steps in the right direction.</p>\n<p>You seem interested in writing clean code. I can warmly recommend the book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0132350882\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Clean Code: A Handbook of Agile Software Craftsmanship</a> (Robert C. Martin). For me, it was a very thought-provoking book that helped me really understand why internal software quality matters (and how to achieve it).</p>\n<p>Now, let's get to the Review.</p>\n<p><strong>Pulazzo's suggestions are spot on.</strong> (As he pointed out, you may want to revisit the concept of object instances and the <code>this</code> keyword).</p>\n<p>In addition to the points already made, I'd like to explain some more abstract topics that really drive code quality.</p>\n<hr />\n<h1>Theoretical Background</h1>\n<h2>The fundamental problem</h2>\n<p>Programmers like to think of themselves as <em>smart.</em> We tend to solve a problem, marvel at our cleverness, and leave a mess behind without even realizing it. It's only when we revisit our code later (often in the process of trying to add a feature or fix a bug), we realize that <strong>reading and understanding code is a lot harder than writing it.</strong> There's often too much information to comfortably wrap our heads around.</p>\n<p>We then write comments (in your case, almost a comment per line) to help make sense of the whole thing, but in doing so, we add even more information, and this time there isn't even a guarantee for reliability or truthfullness: comments go off faster than milk left out of the fridge at 40Β°C, rendering the "information" they contain obsolete.</p>\n<p>Even worse, <strong>comments are often redundant.</strong> It's as if we are writing everything <em>twice!</em> A good programmer is a lazy programmer in that she <em>never</em> repeats herself.</p>\n<p><sub>(Comments <em>do</em> have their place, for instance in the documentation of public APIs and explaining particularly weird decisions we made.)</sub></p>\n<h2>The solution</h2>\n<p>In order to cope with complexity, we need to split it up and simplify it as far as possible. In other words: <strong>Divide and conquer.</strong> If our classes are small, we can easily spot the <em>responsibilities</em>. If our methods are small, we can easily discern the flow of control. If our lines are short, we can make sense of the statements they contain.</p>\n<p>Conciseness isn't the only thing that matters. It's even more important to <strong>choose proper names.</strong> Without proper names, we are constantly decoding and reconstructing the information that should be apparent from reading the code alone.</p>\n<hr />\n<h1>Applying it to your Tic Tac Toe</h1>\n<h2>The entry point</h2>\n<p>Look at your <code>main</code> method. It spans nearly 50 lines and contains <em>six levels of nesting.</em> I tried really hard, but my head nearly exploded trying to comprehend everything you were doing in there.</p>\n<p>What if that method were to look like this?</p>\n<pre><code>private static final Scanner in = new Scanner(System.in);\nprivate static final PrintStream out = System.out;\nprivate static final Game game = new Game();\n\npublic static void main(String args[]) {\n out.println("Welcome to TicTacToe.");\n out.println(game);\n while (game.isRunning()) {\n informPlayersOfNextTurn();\n makeNextMove();\n out.println(game);\n }\n out.println(game.getResult());\n}\n</code></pre>\n<p>A lot of effort went into transforming your original code into this <em>readable</em> and <em>expressive</em> form. But where, you ask, has all the code gone? Let's go step by step.</p>\n<p>Because I have split everything into separate methods that each <em>do one thing only,</em> I've promoted the local variables to <code>private static final</code> fields. There's your familiar Scanner, plus a reference to <code>System.out</code> so I can use the short form <code>out.println(...)</code> and drop the <code>System</code> (I find it more convenient, but go with what you feel most comfortable with).</p>\n<p>The methods that are called from <code>main</code> all look <em>pretty much how you expected them:</em></p>\n<pre><code>private static void informPlayersOfNextTurn() {\n String message = "Player %s, it's your turn. Make your move!\\n";\n out.printf(message, game.getCurrentPlayer());\n}\n</code></pre>\n<p>We simply ask the game for the current player and prompt them to make their move.</p>\n<p>Note the high level of these method calls... there's not much of an implementation visible here, just a high level view of how the program flows. We'll keep asking for a move until the user enters a valid one:</p>\n<pre><code>private static void makeNextMove() {\n Move move = askForMove();\n while (!game.isMoveAllowed(move)) {\n out.println("Illegal move, try again.");\n move = askForMove();\n }\n game.makeMove(move);\n}\n</code></pre>\n<p>Now, we delve a little deeper. Users aren't usually accustomed to the programming convention of counting from zero, so we'll allow them to enter their moves in familiar terms and subtract <code>1</code> to transform them to an appropriate format for use with Java.</p>\n<pre><code>private static Move askForMove() {\n int x = askForCoordinate("horizontal");\n int y = askForCoordinate("vertical");\n return new Move(x - 1, y - 1);\n}\n</code></pre>\n<p>Finally, we've arrived at the implementation level: We're using the Scanner to gather some valid input.</p>\n<pre><code>private static int askForCoordinate(String coordinate) {\n out.printf("Enter the %s coordinate of the cell [1-3]: ", coordinate);\n while (!in.hasNextInt()) {\n out.print("Invalid number, re-enter: ");\n in.next();\n }\n return in.nextInt();\n}\n</code></pre>\n<p>And that's it! This is all that goes in the <code>Testing</code> class. (I called it <code>Main</code> because that's my personal convention, but <code>Testing</code> is okay too).</p>\n<p>What happened to the rest of the code? In <code>Main</code>, we're really only interested in the rough flow of logic and handling the input, so the other responsibilities have been <em>delegated</em> to <code>Game</code>. One of the problems with your original code is that it only has two classes: <code>Testing</code> and <code>Board</code>. But those are too many responsibilities bundled into one.</p>\n<h2>Tracking game state</h2>\n<pre><code>public class Game {\n private final Board board = new Board();\n private Player currentPlayer = Player.X;\n</code></pre>\n<p>The game has a <code>Board</code> and tracks the current <code>Player</code> (X has the first move; <code>Player</code> is an enum).</p>\n<pre><code> public boolean isRunning() {\n return !currentPlayer.isWinner && !board.isFull();\n }\n</code></pre>\n<p>Scroll back up and look at our while loop in <code>main</code>. So now it's clear: the game is only running if there isn't a winner yet and the board is not yet full. Otherwise, it's ended.</p>\n<pre><code> public Player getCurrentPlayer() {\n return currentPlayer;\n }\n\n public boolean isMoveAllowed(Move move) {\n return isRunning() && board.isCellEmpty(move.X, move.Y);\n }\n</code></pre>\n<p>A move is allowed if the game is running and the cell we are trying to put an X or O in is empty.</p>\n<p>You can only make a move if the game is still running. If we don't have a winner after making the move, the next player's turn starts:</p>\n<pre><code> public void makeMove(Move move) {\n if (!isRunning()) {\n throw new IllegalStateException("Game has ended!");\n }\n board.setCell(move.X, move.Y, currentPlayer);\n if (!currentPlayer.isWinner) {\n currentPlayer = currentPlayer.getNextPlayer();\n }\n }\n</code></pre>\n<p>When the game has finished, we can check the result:</p>\n<pre><code> public GameResult getResult() {\n if (isRunning()) {\n throw new IllegalStateException("Game is still running!");\n }\n return new GameResult(currentPlayer);\n }\n</code></pre>\n<p>And to print the board to the console, <code>toString</code> is overridden (so <code>out.println(game);</code> will print the game board in its current state):</p>\n<pre><code> @Override\n public String toString() {\n return board.toString();\n }\n\n}\n</code></pre>\n<p>Now the only major thing to take a look at is <code>Board</code>.</p>\n<h2>The tic tac toe board</h2>\n<pre><code>public class Board {\n private final int LENGTH = 3;\n private final Player[][] cells = new Player[LENGTH][LENGTH];\n private int numberOfMoves = 0;\n</code></pre>\n<p>Instead of your "two-dimensional" array of <code>int</code>, I've used the <code>Player</code> enum to make the code more expressive (and to get rid of all the magic numbers such as 500, 1000 and 50 that are so prevalent in your original code). We keep count of the moves so far to easily tell if the board is full without counting the full cells later.</p>\n<p>In the constructor, we fill all the rows with cells:</p>\n<pre><code> public Board() {\n for (Player[] row : cells)\n Arrays.fill(row, Player.Blank);\n }\n</code></pre>\n<p>The following method is called when the player makes a move. It replaces your three enormous if statements where the conditions spanned multiple lines. Even in this refactored version, some complexity remains. Basically, the approach is:</p>\n<ul>\n<li>We can base our calculations on the current move,</li>\n<li>so we only need to examine the current column, row, diagonal and anti-diagonal.</li>\n<li>If any of those is long enough (<code>3</code>), we have a winner.</li>\n</ul>\n<p>If this makes no sense, draw the board on a piece of paper and go through it with a pencil.</p>\n<pre><code> public void setCell(int x, int y, Player player) {\n cells[x][y] = player;\n numberOfMoves++;\n int row = 0, column = 0, diagonal = 0, antiDiagonal = 0;\n for (int i = 0; i < LENGTH; i++) {\n if (cells[x][i] == player) column++;\n if (cells[i][y] == player) row++;\n if (cells[i][i] == player) diagonal++;\n if (cells[i][LENGTH - i - 1] == player) antiDiagonal++;\n }\n player.isWinner = isAnyLongEnough(row, column, diagonal, antiDiagonal);\n }\n\n private boolean isAnyLongEnough(int... combinationLengths) {\n Arrays.sort(combinationLengths);\n return Arrays.binarySearch(combinationLengths, LENGTH) >= 0;\n }\n</code></pre>\n<p>The simplest way I found to find if any of the values is as long as <code>LENGTH</code> is a binary search, which only works when lengths are sorted. You could use a loop just as well.</p>\n<p>In game, we sometimes have to check if a cell is empty, so we check if it's on the board and, if it is, whether it is also blank:</p>\n<pre><code> public boolean isCellEmpty(int x, int y) {\n boolean isInsideBoard = x < LENGTH && y < LENGTH && x >= 0 && y >= 0;\n return isInsideBoard && cells[x][y] == Player.Blank;\n }\n</code></pre>\n<p>After nine moves, the board is invariably full:</p>\n<pre><code> public boolean isFull() {\n return numberOfMoves == LENGTH * LENGTH;\n }\n</code></pre>\n<p>Finally, we again override <code>toString</code>, giving us the ability to output the game board. This is still a lot more complex than I would like. Ideally, this might be delegated to a separate <code>GameBoardFormatter</code> class.</p>\n<pre><code> @Override\n public String toString() {\n final String horizontalLine = "-+-+-\\n";\n StringBuilder builder = new StringBuilder();\n for (int row = 0; row < cells.length; row++) {\n for (int column = 0; column < cells[row].length; column++) {\n builder.append(cells[column][row]);\n if (column < cells[row].length - 1)\n builder.append('|');\n }\n if (row < cells.length - 1)\n builder.append('\\n').append(horizontalLine);\n }\n return builder.toString();\n }\n\n}\n</code></pre>\n<p>And that's it! Well, almost. You've probably got a pretty good idea what the enum <code>Player</code> and the helper class <code>Move</code> have to look like, but I'll show them for the sake of completeness.</p>\n<h2>Helper data structures</h2>\n<p>Some Java experts and professionals will tell you that every field should be protected by getters and setters. I disagree (and Robert C. Martin happens to be of the same opinion): Some classes really have no significant <em>state</em> to protect, so they should be classified as <em>data structures without behaviour</em> and may have public fields. Others will disagree, and using getter-setter methods is fine too.</p>\n<pre><code>public enum Player {\n X, O, Blank {\n @Override // to give us a blank space on the board\n public String toString() {\n return " ";\n }\n };\n\n public boolean isWinner = false;\n\n public Player getNextPlayer() {\n return this == Player.X ? Player.O : Player.X;\n }\n\n}\n</code></pre>\n<p>Pretty straightforward: <code>X</code> and <code>O</code> will show up on the game board correctly, so all we need to do is override <code>toString</code> of <code>Player.Blank</code> to give us an empty space. Also, there's a convenience method to give us the next player.</p>\n<h3>Formatting the game result</h3>\n<pre><code>public class GameResult {\n private final Player player;\n\n public GameResult(Player lastPlayer) {\n player = lastPlayer;\n }\n\n @Override\n public String toString() {\n String winner = player.isWinner ? player.toString() : "Nobody";\n return String.format("%s won. Thank you for playing.", winner);\n }\n}\n</code></pre>\n<h3>A data structure for Player moves</h3>\n<pre><code>public class Move {\n\n public final int X;\n public final int Y;\n \n public Move(int x, int y){\n X = x;\n Y = y;\n }\n}\n</code></pre>\n<hr />\n<p>I hope you find this review useful. I've tried to clearly mark the parts that are purely based on my opinion. Having spent a couple of hours on this, I'd appreciate some feedback in the form of votes and comments.</p>\n<p><sub>And sorry for not linking to the more advanced concepts I touched upon: you may need to Google a lot of things. I'll try to come back and put in some links some time.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T09:17:47.273",
"Id": "25928",
"Score": "0",
"body": "Thank you for the answer! I am really grateful for your time and effort, this is really taking it to another level. you sir ,deserve a medal. again , this is a much better review than I ever thought I would get , coherent and constructive. thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T20:40:52.293",
"Id": "25987",
"Score": "0",
"body": "@Thank you, Tom. One thing I neglected in my answer is the artificial intelligence in your implementation. I'm glad you found the review useful anyway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T00:41:30.777",
"Id": "15939",
"ParentId": "15911",
"Score": "20"
}
},
{
"body": "<p>Quick tip about your Board.scoreBoard(...) method: </p>\n\n<ol>\n<li>It was hard to read because of all the lines. </li>\n<li>There was a bunch of duplicate code. </li>\n<li>It looked like you were using & instead of && -- & is the bitshift operator. </li>\n</ol>\n\n<p>Hopefully I didn't misunderstand the code in that method, but here's another way to write it that (IMHO :) is clearer. The code here <em>is</em> slower than your code, but clearness is <em>always</em> more important than speed in Java, unless you're writing real time code (i.e. robotics) -- and actually, even then, it's still more important. </p>\n\n<pre><code>public int scoreBoard(Board board) {\n if( checkLines(board, 1) ) { \n return 100;\n }\n else if( checkLines(board, 2) ) { \n return 0;\n }\n\n for( int a = 0; a < 3; ++a ) { \n for( int b = 0; b < 3; ++b ) { \n if( board.Square[a][b] == 0 ) { \n return 1000;\n }\n }\n }\n\n return 50;\n}\n\nprivate boolean checkLines(Board board, int player ) { \n for( int x = 0, r = 0; r < 3; ++r, x = 0) {\n if( board.Square[r][x] == player && board.Square[r][++x] == player && board.Square[r][++x] == player ) { \n return true;\n }\n x = 0;\n if( board.Square[x][r] == player && board.Square[++x][r] == player && board.Square[++x][r] == player ) { \n return true;\n } \n }\n\n if( board.Square[0][0] == player && board.Square[1][1] == player && board.Square[2][2] == player ) { \n return true;\n }\n if( board.Square[0][2] == player && board.Square[1][1] == player && board.Square[2][0] == player ) { \n return true;\n }\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T09:24:22.173",
"Id": "25929",
"Score": "0",
"body": "thank you for the answer , seems like I failed to notice the &--&& issue, now I am confused as to why my program is still working even though its using \"&\" instead of \"&&\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T11:53:56.247",
"Id": "25933",
"Score": "1",
"body": "Wow, something new every day: [this](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html) confirms that & is a bitshift operator. *But* [this stackoverflow answer](http://stackoverflow.com/questions/1724205/effect-of-a-bitwise-operator-on-a-boolean-in-java) clarifies that bitshift operators **do** work with booleans, as specified in [this section](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2) of the JLS!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T11:59:56.803",
"Id": "25935",
"Score": "0",
"body": "BTW, the effect of using & was that the entire line is evaluated, instead of the expression 'short-cutting' when it determined that the first (boolean) expresion was false."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T06:06:07.170",
"Id": "15944",
"ParentId": "15911",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15939",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T14:07:05.083",
"Id": "15911",
"Score": "19",
"Tags": [
"java",
"beginner",
"game"
],
"Title": "TicTacToe logic in Java"
}
|
15911
|
<p>I'm a total newbie teaching myself via Zed Shaw's <em>Learn Python The Hard Way</em> and I've gotten bored over a week long memorization lesson, so I thought I would make a character generator for a pen and paper RPG I'm writing. I havent really read about <code>if</code> statements or things like that, so I am experimenting here. </p>
<pre><code>##########################################################
# Cyberpanky N.O.W Python Character Generator by Ray Weiss
#
# Created 9/24/2012
#
# Much thanks to Connor Daliposon
# Mho made a very readable D&D Character Generator
# That a Python newbie like me could understand
##########################################################
# Imports
import random
from pprint import pprint
# Hey there
print """
Hello world & welcome to the CYBERPANKY N.O.W. character generator.
Programmed by Ray Weiss.
To quit at anytime, press CNTRL-C.
"""
print "Lets figure out your stats first. Press enter to continue."
raw_input()
# Stat Roller
# Rolls 3D6 and adds the sum together and prints
def roll_stats():
a = random.randint(1, 6)
b = random.randint(1, 6)
c = random.randint(1, 6)
d = random.randint(1, 6)
list = [a, b, c, d]
list.sort()
add = sum(list[1:4])
return add
# Modifiers
def pow_mod():
a = "|+1 to hit on mele attack rolls| "
b = "|+1 damage on mele attack rolls|"
if pow >= 15 and pow < 17:
return a
if pow >= 17:
return a + b
else:
return " ~no modifiers~"
def iq_mod():
a = "|-500$ to invest in cyberspace| "
b = "|Reroll Street Doc abilities|"
if iq >= 15 and iq < 17:
return a
if iq >= 17:
return a + b
else:
return " ~no modifiers~"
def agi_mod():
a = "|+1 to hit with ranged weapons| "
b = "|-1 to hit with ranged weapons|"
if agi >= 12:
return a
if agi <= 9:
return b
else:
return " ~no modifiers~"
def con_mod():
a = "|+1 hit point per hit dice|"
b = "|-1 hit point per hit dice|"
if con >= 15:
return a
elif con <= 6:
return b
else:
return " ~no modifiers~"
def cyn_mod():
a = "|Add 10% to earned experience|"
b = "|Add 5% to earned experience|"
c = "|Subtract 10% from earned experience|"
d = "|Subtract 20% from earned experience|"
if cyn >= 15:
return a
elif cyn > 12 and cyn < 15:
return b
elif cyn > 6 and cyn < 9:
return c
elif cyn <= 6:
return d
else:
return " ~no modifiers~"
def cha_mod():
a = "|+1 to reaction rolls|"
b = "|-1 to reaction rolls|"
if cha >= 15:
return a
if cha <= 8:
return b
else:
return " ~no modifiers~"
# Prints stats + modifiers.
pow = roll_stats()
print "Power:", pow, pow_mod()
iq = roll_stats()
print "Intelligence:", iq, iq_mod()
agi = roll_stats()
print "Agility:", agi, agi_mod()
con = roll_stats()
print "Constitution:", con, con_mod()
cyn = roll_stats()
print "Cynicism:", cyn, cyn_mod()
cha = roll_stats()
print "Charisma:", cha, cha_mod()
print "\nIf you dont like your stats, tough shit. This is Cyberpanky N.O.W."
print "\nPress enter to continue."
raw_input()
# Choose Class
print """In Cyberpanky N.O.W. there are only 3 character classes.
1. Samurai: Badass mercenaries. Can make multiple attacks.
------------------------------------------------------------------------------
2. Street Docs: Hackers / Doctors. Can heal & hack.
------------------------------------------------------------------------------
3. Shaman: Magical prophets that follow spirit animals and cast miracles
------------------------------------------------------------------------------
"""
type = int(raw_input("Please type a 1, 2, or 3 > "))
if type == 1:
character_class = "Samurai"
class_power = """
* Attack multiple times for a -2 to hit penalty.
* Uses a D10 for Physical hit box.
* Has a + 1 to hit bonus that levels up to level 5.
"""
name = raw_input("\nAlright {}, tell me your name >".format(character_class))
elif type == 2:
character_class = "Street Doc"
class_power = """
* Roll IQ to mess with electronics
* Can heal party members after combat for 1D4 Hit Points
* Can perform cyberwear installation or surgery with proper tools.
"""
name = raw_input("\nAlright {}, tell me your name >".format(character_class))
elif type == 3:
character_class = "Shaman"
class_power = """
* Can cast Miracles.
* Can call for a saving grace if they are on their last Cool Hit Box
* Can do favors for their god for more miracles, or pay a tithe.
"""
name = raw_input("\nAlright {}, tell me your name >".format(character_class))
# Alignment
print"""\nAlright {}, pick an alignment, it's not that important;
1. Narcissist: Cocky bastard, you think you are the best.
------------------------------------------------------------------------------
2. Neutral: Pretty self explanatory dipshit.
------------------------------------------------------------------------------
3. Nihilist: You care about nothing Lebowski, You'll cut off their Johnson.
------------------------------------------------------------------------------
""".format(name)
x = int(raw_input("Please type a 1, 2, or 3 > "))
if x == 1:
alignment = "Narcissist"
elif x == 2:
alignment = "Neutral"
elif x == 3:
alignment = "Nihilist"
print "\nOk you chose {} for an alignment, press enter to continue.".format(
alignment)
print """
------------------------------------------------------------------------------
"""
raw_input()
# Functions for ID generation
def gen_id():
global gender_id
one = "1. Straight male"
two = "2. Gay male"
three = "3. Transgender male pre-op"
four = "4. Transgender male post-op"
five = "5. Bisexual male"
six = "6. Straight female"
seven = "7. Gay female"
eight = "8. Transgender female pre-op"
nine = "9. Transgender female post-op"
ten = "10. Bisexual female"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "\nPlease hit enter to roll 1D10"
raw_input()
gender_id = random.choice(list)
print "You rolled {}, press enter to continue.".format(gender_id)
raw_input()
# Ethnic Profile
def eth_pr():
global ethnic_pr
one = "1. Native American"
two = "2. West European"
three = "3. East European"
four = "4. North Asian"
five = "5. South Asian"
six = "6. Pacific"
seven = "7. North African"
eight = "8. South African"
nine = "9. Slavic / Caucuses"
ten = "10. Hispanic"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "\nPlease hit enter to roll 1D10"
raw_input()
ethnic_pr = random.choice(list)
print "You rolled {}, press enter to continue.".format(ethnic_pr)
raw_input()
# Family Class Distinction
def fam_cls():
global fcd
one = "1. Homeless"
two = "2. Impoverished"
three = "3. Lower Class"
four = "4. Lower Middle Class"
five = "5. Middle Class"
six = "6. Comfortable"
seven = "7. Upper Middle Class"
eight = "8. Upper Class"
nine = "9. Job Creators"
ten = "10. Warren Buffett"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "Please hit enter to roll 1D10"
raw_input()
fcd = random.choice(list)
print "You rolled {}, press enter to continue.".format(fcd)
raw_input()
# Whats Good With Your Folks
def wha_goo():
global wg, one_x, two_x
one_x = "1. Things Are Good With Your Folks; Go to Current Family Affairs"
two_x = "2. Your folks are fucked; go to Your Folks Got Fucked"
list = [one_x, two_x]
pprint(list)
print "Please hit enter to roll 1D2"
raw_input()
wg = random.choice(list)
print "You rolled {}, press enter to continue.".format(wg)
raw_input()
# Your Folks Got Fucked
def yo_fo():
global fogo_fuck
one = "1. Your parents were mugged and murdered, just like Batman"
two = "2. Your parents were both convicted of murder"
three = "3. Parents decapitated by a truck"
four = "4. Parents addicted to coke, put you in an orphanage"
five = "5. Parents were corporate spies and assinated in front of you"
six = "6. Parents abandonded you at a young age and joined a cult"
seven = "7. Your parents died from STDs contracted from aldultery"
eight = "8. Parents owed mob a bunch of money, sleeping with fishies"
nine = "9. Nuclear explosion incinerated parents, their shadow remains"
ten = "10. Parents shot themselves immediately after you were born."
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "Please hit enter to roll 1D10"
raw_input()
fogo_fuck = random.choice(list)
print "You rolled {}, press enter to continue.".format(fogo_fuck)
raw_input()
# Current Family Affairs
def cu_fa():
global cur_fam, one_y, two_y
one_y = "1. Things are ok with family, go to Nature Or Nurture"
two_y = "2. Your family is fucked, go to Your Family Is Fucked"
list = [one_y, two_y]
pprint(list)
print "Please hit enter to roll 1D2"
raw_input()
cur_fam = random.choice(list)
print "You rolled {}, press enter to continue.".format(cur_fam)
raw_input()
# Your Family Got Fucked
def fa_fu():
global fam_fuk
one = "1. Market tanked with president Paul, dead broke family."
two = "2. Home invaders raped and murded the women in your family"
three = "3. Racial Supremisicist drove your family from their home"
four = "4. Whole family was abducted by aliens, never seen again"
five = "5. Radiation leak hospitalized your whole family."
six = "6. Family was accidentally napalmed by the UN, all dead."
seven = "7. Family came down with malaria"
eight = "8. Family has some obvious dealings with Illuminati"
nine = "9. Family eaten alive by cannibals"
ten = "10. Make it up dipshit"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
raw_input()
fam_fuk = random.choice(list)
print "You rolled {}, press enter to continue.".format(fam_fuk)
raw_input()
# Nature Or Nurture
def na_nu():
global nat_nur
one = "1. Your childhood was very boring & average"
two = "2. Your childhood was spent moving from city to city"
three = "3. Your childhood was depraved; hungry and lonely"
four = "4. Your childhood was rewarding, social & fun."
five = "5. You were a sick child, spent a lot of time in bed"
six = "6. You were sent to a preppy boarding school as a kid"
seven = "7. You got addicted to drugs; it screwed you up."
eight = "8. You killed another kid, spent time in a hospital"
nine = "9. You were a child genius, but had few friends"
ten = "10. Make it up dipshit"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "Please hit enter to roll 1D10"
raw_input()
nat_nur = random.choice(list)
print "You rolled {}, press enter to continue.".format(nat_nur)
raw_input()
# General Disposition
def ge_di():
global gen_dis
one = "1. Friendly"
two = "2. Unfriendly"
three = "3. Shy"
four = "4. Outgoing"
five = "5. Unpretentious"
six = "6. Pretentious"
seven = "7. Hyperactive"
eight = "8. Depressed"
nine = "9. Wonderful Human Being"
ten = "10. Scumbag"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "Please hit enter to roll 1D10"
raw_input()
gen_dis = random.choice(list)
print "You rolled {}, press enter to continue.".format(gen_dis)
raw_input()
# Whats the most important thing in the world
def wh_wo():
global wha_wor
one = "1. Money"
two = "2. Kicking ass"
three = "3. Getting fucked up"
four = "4. Family & friends"
five = "5. Business"
six = "6. The internet"
seven = "7. Faith"
eight = "8. Style"
nine = "9. Anarchy"
ten = "10. Selfishness"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "Please hit enter to roll 1D10"
raw_input()
wha_wor = random.choice(list)
print "You rolled {}, press enter to continue.".format(wha_wor)
raw_input()
# Who is to blame for the worlds problems?
def wh_pr():
global who_pro
one = "1. Corporations"
two = "2. Leftists"
three = "3. Fate"
four = "4. Religion"
five = "5. The Illuminatus"
six = "6. The News Media"
seven = "7. The UN"
eight = "8. Your Neighbors"
nine = "9. Aliens"
ten = "10. President Ron Paul"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "Please hit enter to roll 1D10"
raw_input()
who_pro = random.choice(list)
print "You rolled {}, press enter to continue.".format(who_pro)
raw_input()
# How do you solve the worlds problems
def ho_pr():
global how_pro
one = "1. Kill them all"
two = "2. But them out"
three = "3. Intimidation"
four = "4. Diplomacy"
five = "5. Free trade"
six = "6. Seduction"
seven = "7. New-Age spirituality"
eight = "8. Religious fanaticism"
nine = "9. Federal power"
ten = "10. Who gives a shit"
list = [one, two, three, four, five, six, seven, eight, nine, ten]
pprint(list)
print "Please hit enter to roll 1D10"
raw_input()
how_pro = random.choice(list)
print "You rolled {}, press enter to continue.".format(how_pro)
raw_input()
# ID Generation
print ("Alright {}, now we need to figure out your personality & life story."
.format(name))
print "\n\t\t1. Ethnics, Genes, & Looks"
print "\nTo figure out your age, we add 15 to 1D10.\n"
age = random.randint(1, 10) + 15
print "Press enter to continue dipshit."
raw_input()
print "Age:", age
print "\t\tGender Identity\n"
gen_id()
print"""
------------------------------------------------------------------------------
"""
print "\t\tEthnic Profile\n"
eth_pr()
print"""
------------------------------------------------------------------------------
"""
print "\t\t2. Ballz Of Our Fathers"
print "\n"
print "\t\tFamily Class Distinction"
fam_cls()
print"""
------------------------------------------------------------------------------
"""
print "\t\tWhat's Good With Your Folks"
wha_goo()
print"""
------------------------------------------------------------------------------
"""
if wg == one_x:
fogo_fuck = "none"
print "\t\tCurrent Family Affairs"
cu_fa()
print"""
------------------------------------------------------------------------------
"""
if cur_fam == one_y:
fam_fuk = "none"
print "\t\tNature Or Nurture?"
na_nu()
print"""
------------------------------------------------------------------------------
"""
if cur_fam == two_y:
print "\t\t Your Family Is Fucked"
fa_fu()
print"""
------------------------------------------------------------------------------
"""
print "\t\tNature Or Nurture?"
na_nu()
print"""
------------------------------------------------------------------------------
"""
if wg == two_x:
print "\t\tYour Folks Got Fucked"
yo_fo()
print"""
------------------------------------------------------------------------------
"""
print "\t\tCurrent Family Affairs"
cu_fa()
print"""
------------------------------------------------------------------------------
"""
fam_fuck = "none"
print "\t\tNature Or Nurture?"
na_nu()
print"""
------------------------------------------------------------------------------
"""
if cur_fam == one_y:
fam_fuck = "none"
print "\t\tNature Or Nurture?"
na_nu()
print"""
------------------------------------------------------------------------------
"""
if cur_fam == two_y:
print "\t\t Your Family Is Fucked"
fa_fu()
print"""
------------------------------------------------------------------------------
"""
print "\t\t3. What Makes you tick"
print "\n"
print "\t\tGeneral Disposition"
ge_di()
print"""
------------------------------------------------------------------------------
"""
print "\t\tWhat's The Most Important Thing In The World?"
wh_wo()
print"""
------------------------------------------------------------------------------
"""
print "\t\tWho Is To Blame For The World's Problems?"
wh_pr()
print"""
------------------------------------------------------------------------------
"""
print "\t\tHow Do You Solve Your / The Worlds Problem"
ho_pr()
print"""
------------------------------------------------------------------------------
"""
#Starting Money
gold = roll_stats() * 100
print "Ok so lets sum that up, please hit enter to continue"
raw_input()
print"""
------------------------------------------------------------------------------
"""
# Print Character Sheet Function.
def char_shee():
print "Name:", name
print "Class:", character_class
print "Class Powers:", class_power
print "Alignment:", alignment
print "Power:", pow, pow_mod()
print "Intelligence:", iq, iq_mod()
print "Agility:", agi, agi_mod()
print "Constitution:", con, con_mod()
print "Cynicism:", cyn, cyn_mod()
print "Charisma:", cha, cha_mod()
print "Money:", gold
print "All Characters Start With 3 Hit Dice"
print"""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro)
char_shee()
print "Press enter to continue"
raw_input()
# Export to text file?
#character sheet function for writing
def character_sheet():
sheet = []
sheet.append("Name: " + name)
sheet.append("Class: " + character_class)
sheet.append("Class Powers :" + class_power)
sheet.append("Alignment: " + alignment)
sheet.append("Power: {0} {1}".format(pow, pow_mod()))
sheet.append("Intelligence: {0} {1}".format(iq, iq_mod()))
sheet.append("Agility: {0} {1}".format(agi, agi_mod()))
sheet.append("Constitution: {0} {1}".format(con, con_mod()))
sheet.append("Cynicism {0} {1}".format(cyn, cyn_mod()))
sheet.append("Charisma: {0} {1}".format(cha, cha_mod()))
sheet.append("Money: " + str(gold))
sheet.append("All Characters Start With 3 Hit Dice")
sheet.append("""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro))
# Return the string with newlines
return '\n'.join(sheet)
print """Just because I like you, let me know if you want this character
saved to a text file. Please remember if you save your character not to
name it after something important, or you might lose it.
"""
text_file = raw_input("Please type 'y' or 'n', if you want a .txt file > ")
if text_file == "y":
filename = raw_input("\nWhat are we calling your file, include .txt > ")
target = open(filename, 'w')
target.write(character_sheet())
target.close()
print "\nOk I created your file."
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
else:
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-23T16:34:10.923",
"Id": "166160",
"Score": "0",
"body": "Small tip, that top comment should be a docstring."
}
] |
[
{
"body": "<pre><code>def roll_stats():\n a = random.randint(1, 6)\n b = random.randint(1, 6) \n c = random.randint(1, 6)\n d = random.randint(1, 6)\n list = [a, b, c, d]\n</code></pre>\n\n<p>Call it <code>dice</code> or something more descriptive then <code>list</code>. You can also use <code>list = [random.randint(1,6) for x in xrange(4)]</code> rather then creating the variables separately.</p>\n\n<pre><code> list.sort()\n add = sum(list[1:4])\n</code></pre>\n\n<p>Instead of sorting it and slicing it use: <code>list.remove(min(list))</code></p>\n\n<pre><code> return add\n</code></pre>\n\n<p>Don't assign variables just to return them on the next line, use <code>return sum(list[1:4])</code></p>\n\n<pre><code>def pow_mod():\n a = \"|+1 to hit on mele attack rolls| \"\n b = \"|+1 damage on mele attack rolls|\"\n\n if pow >= 15 and pow < 17:\n</code></pre>\n\n<p>Don't take input to a function from global variables, pass it as a parameter</p>\n\n<pre><code> return a\n if pow >= 17:\n return a + b\n else: \n return \" ~no modifiers~\"\n</code></pre>\n\n<p>You return strings, but conceptually you are returning a list of modifiers. I suggest returning the list. You can then format the list anyway you like in the caller.</p>\n\n<p>You've got a number of functions very similiar to this, it suggests moving some of the details into data structures. I'd do it like this:</p>\n\n<pre><code>POW_MODIFIERS = [\n# specify minimum and maximum stat the modifier applies to\n (15, 9999, \"+1 to hit on mele attack rolls\"),\n (17, 9999, \"+1 damage on mele attack rolls\")\n]\n\ndef calc_modifiers(stat, modifiers):\n return [modifier for minimum, maximum, modifier in modifiers if minimum <= state <= maximum]\n\ndef format_modifiers(modifiers):\n if modifiers:\n return ' '.join('|%s|' % modifier for modifier in modifiers) \n else:\n return ' ~no modifiers~ '\n</code></pre>\n\n<p>By creating lists like POW_MODIFIERS for all your stats, you can reuse the functions for all the different stats. You should be able to apply similiar techniques to your other decisions. I'd also look at storing the data in a seperate file, perhaps using JSON. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T15:28:40.070",
"Id": "15914",
"ParentId": "15913",
"Score": "6"
}
},
{
"body": "<p>I would suggest moving all your top level code into a main() routine and collecting it all in one place rather than having top level code and routines interspersed. I like to structure my code like this:</p>\n\n<pre><code>import sys\n\ndef main():\n ... top level code ...\n routine1()\n ...\n routine2()\n ...\n all_done()\n\ndef routine1():\n ... do work here ...\n\ndef routine2():\n ... do work here ...\n\ndef all_done():\n ... finish up ...\n\nif __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n\n<p>By doing it this way, if my code is in a file named, say, 'code.py', I can play with in the python interpreter by doing, eg.</p>\n\n<pre><code>python\n>>> import code\n>>> code.all_done() # test routine all_done() by itself\n>>> ^D\n</code></pre>\n\n<p>With the top level code interspersed with the function definitions, when you try to import code, it all gets run. You can't run the pieces independently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T10:58:29.483",
"Id": "47342",
"ParentId": "15913",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15914",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T14:23:22.620",
"Id": "15913",
"Score": "7",
"Tags": [
"python",
"beginner",
"game",
"dice",
"role-playing-game"
],
"Title": "Character generator"
}
|
15913
|
<p>I'm new to Android and I wanted to create a class that would load an ad inside the current layout. All the layouts have a <code>RelativeLayout id=adLayout</code></p>
<p>From my main, I have:</p>
<pre><code>AdLoader al = new AdLoader();
al.GrabAd(this,"123");
</code></pre>
<p>Then on my AdLoader.java class I have:</p>
<pre><code>public class AdLoader {
private DfpAdView adView;
public void GrabAdFor(Activity act, String adId) {
adView = new DfpAdView(act, AdSize.BANNER, adId);
RelativeLayout rl = (RelativeLayout) act.findViewById(R.id.adLayout);
rl.addView(adView);
adView.loadAd(new AdRequest());
}
}
</code></pre>
<p>Is it incorrect to pass the Activity? Am I even passing the activity or the View/Context?</p>
|
[] |
[
{
"body": "<p>You could also make a baseactivity for all the other activity that are going to use the adView</p>\n\n<pre><code> public class BaseActivity extends Activity {\n\n private DfpAdView adView;\n RelativeLayout rl;\n //some other stuff\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.baseactivity_layout)\n rl = (RelativeLayout) findViewById(R.id.adLayout);\n adView = new DfpAdView(this, AdSize.BANNER, adId);\n rl.addView(adView);\n adView.loadAd(new AdRequest());\n }\n}\n</code></pre>\n\n<p>And and make your MainActivity (or all the other activities that are using the adview)</p>\n\n<pre><code>public class MainActivity extends BaseActivity {\n @Override\n public void onCreate(Bundle savedInstanceState){\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T15:49:50.527",
"Id": "16158",
"ParentId": "15915",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T15:36:57.343",
"Id": "15915",
"Score": "4",
"Tags": [
"java",
"beginner",
"android"
],
"Title": "findViewById - in separate class"
}
|
15915
|
<p>Here's a class I created to parse XML to create an IList.
It seems to me that this is something that will be done a lot in general by a lot of different programs. Is there a more standard way of doing this using .Net and C#</p>
<pre><code>/// <summary>
/// public class CListFromXml {}
/// Created By: Michael Fitzpatrick, 2012 Sept 25
/// Please attribute & send email: samplecode AT mikefitz dot us
/// Create an IList from XML data
/// XML Syntax -
/// <XmlNode Type="MyType" Enabled="(bool)" Iterations="(number)">
/// (data definition)
/// </XmlNode>
///
/// Type: System.Double by default
/// Type can be Enum using the following syntax:
/// Type="NameSpace.ClassParent.Class+EnumName, ClassParent"
/// See: http://stackoverflow.com/questions/2493215/create-list-of-variable-type
///
/// Enabled: true by default, If false: no list is created
///
/// Iterations: 1 by default, If 0: no list is created.
/// If LT 0 then Iterations = Int32.MaxValue
///
/// (data definition): As CSV list-
/// <CsvString> (item), (item), ... </CsvString>
/// where:
/// (item) is any value. For arrays item is bracketed using "{}"
/// just like C# uses for initializers. Example:
/// <MeasProp Type="System.Double[]">
/// {1960, 1970, 1980},
/// {2960, 2970, 2980},
/// {2960}
/// </MeasProp>
///
/// (data definition): As Center / StepDelta -
/// <LoopSpec>
/// <Center>(some value)</Center>
/// <StepDelta>(some value)</StepDelta> <!-- OPTIONAL -->
/// <StepsUp>(some integer)</StepsUp> <!-- OPTIONAL -->
/// <StepsDown>(some integer)</StepsDown> <!-- OPTIONAL -->
/// </LoopSpec>
/// </summary>
public class CListFromXml
{
public readonly IList Data = null;
public readonly string Name;
public readonly bool Enabled;
public readonly Type Type;
public readonly string TypeName;
public readonly Int32 Iterations;
private static bool ReadCsv(Type typ, string csvData, IList lst)
{
string[] astr = csvData
.Split(new[] { ",", "\r\n", "\n", " ", "\t", "}" }
, StringSplitOptions.RemoveEmptyEntries);
if (astr.Length == 0)
return false;
if (typ == typeof(bool))
foreach (string s in astr)
lst.Add(CUtils.BoolParse(s));
else if (typ.IsEnum)
foreach (string s in astr)
lst.Add(Enum.Parse(typ, s));
else
{
try
{
foreach (string s in astr)
{
object o = Convert.ChangeType(s, typ);
lst.Add(o);
}
}
catch
{
throw new NotSupportedException("CListFromXml: Type not supported:"
+ typ.ToString());
}
}
return true;
}
// ============================================================
/// <summary>
/// Create a list from XML data
/// </summary>
/// <param name="n"></param>
public CListFromXml(XmlNode n)
{
if (!(Enabled = CUtils.IsNodeEnabled(n)))
return;
if ((Iterations = CUtils.NodeIterations(n)) == 0)
return;
Name = n.Name;
TypeName = CUtils.AttribValue(n, "type");
if (TypeName != "")
{
Type = Type.GetType(TypeName);
if (Type == null)
throw new InvalidDataException("Invalid XML File: "
+ " the element " + Name
+ " has an invalid type attribute: " + TypeName);
}
else
Type = typeof(double);
Type lstType = typeof(List<>).MakeGenericType(Type);
Data = (IList)Activator.CreateInstance(lstType);
if (n.FirstChild.ChildNodes.Count == 0)
{
if (Type.IsArray)
{
// String format for Arrays is { <item>, <item>, ...} , { ...
string[] astr = n.InnerText.Trim()
.Split(new[] { "{"}
, StringSplitOptions.RemoveEmptyEntries);
if (astr.Length > 0)
{
IList lst;
Type aryType;
try
{
aryType = Type.GetElementType();
Type lstType1 = typeof(List<>).MakeGenericType(aryType);
lst = (IList)Activator.CreateInstance(lstType1);
}
catch (Exception e)
{
throw new NotSupportedException("CListFromXml: XML Node: "
+ Name + ", Type not supported:"
+ TypeName + "\r\n" + e.ToString());
}
//Type t1 = Data.GetType().GetGenericArguments()[0];
foreach (string s in astr)
{
if (!ReadCsv(aryType, s, lst ))
throw new InvalidDataException("Invalid XML File"
+ " the element " + Name
+ " has an invalid value: " + n.InnerText
+ "\nExpected comma delimited list of numbers.");
Array ary = (Array)Activator.CreateInstance(Type, new object[] { lst.Count });
lst.CopyTo(ary,0);
Data.Add(ary);
lst.Clear();
}
}
}
else
{
// Process as a csv list
if (!ReadCsv(Type, n.InnerText, Data))
throw new InvalidDataException("Invalid XML File"
+ " the element " + Name
+ " has an invalid value: " + n.InnerText
+ "\nExpected comma delimited list of numbers.");
}
}
else
{
if (!CUtils.IsTypeNumeric(Type))
throw new Exception("Error in XML file: '"
+ "', In element: " + Name
+ ", Only numeric types are supported for 'Center / Delta' lists");
ValueType center = CInvalid.Dbl, stepDelta = 0;
Int32 stepsUp = 0, stepsDown = 0;
foreach (XmlNode m in n.ChildNodes)
{
switch (m.Name.ToLower())
{
case "center":
center = (ValueType)Convert.ChangeType(
m.InnerText.Trim(), Type);
break;
case "stepdelta":
stepDelta = (ValueType)Convert.ChangeType(
m.InnerText.Trim(), Type);
break;
case "stepsup":
stepsUp = Int32.Parse(m.InnerText.Trim());
break;
case "stepsdown":
stepsDown = Int32.Parse(m.InnerText.Trim());
break;
case "#comment":
break;
default:
throw new Exception("Error in XML file: '"
+ "', In element: " + Name
+ ", invalid element: " + m.Name);
}
}
Data.Add(center);
if (!stepDelta.Equals(0) && ((stepsDown > 0) || (stepsUp > 0)))
{
double dC = (double)Convert.ChangeType(center, typeof(double));
double dD = (double)Convert.ChangeType(stepDelta, typeof(double));
for (Int32 i = 1; i <= stepsDown; i++)
{
double d = dC - (i * dD);
Data.Add(Convert.ChangeType(d, Type));
}
for (Int32 i = 1; i <= stepsUp; i++)
{
double d = dC + (i * dD);
Data.Add(Convert.ChangeType(d, Type));
}
}
}
} // CListFromXml(IList lst, XmlNode n)
} // CListFromXml{}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:11:15.007",
"Id": "25896",
"Score": "1",
"body": "I really don't think deserializing from a variant of CSV inside XML is something that is βdone a lotβ. Can't you use XML serialization?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:21:33.867",
"Id": "25897",
"Score": "0",
"body": "I had to make the XML as human readable as possible, thus the use of a CSV in the XML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T18:21:29.767",
"Id": "29811",
"Score": "0",
"body": "It was my understanding XML was was supposed to be designed for human readability. It certainly isn't designed for compactness"
}
] |
[
{
"body": "<p>Your code is definitely not a standard way of parsing XML in .NET. Usually there are 2 main cases where XML parsing is needed:</p>\n\n<ol>\n<li><p>You expect a predefined XML structure. In this case all the types of XML nodes are known upfront, so there is no need to specify them inside XML (as you do), and the easiest way to parse such XML is to create classes that correspond to the XML structure and use <code>XmlSerializer</code> to do the work. </p>\n\n<p>Also I usually create a corresponding XSD that specifies the structure of XML that I expect, and if I don't trust the source of XML I run XSD validation before deserializing the XML into objects. The XML structure that you described (where lists are stored enclosed in curly brackets) can't be validated correctly using XSD.</p>\n\n<p>There is a variation of this option when some .NET types are not known in advance, but the structure is still fixed, e.g. if you store the information about solution plugins (and the type of plugin is stored in XML). In that case I would either deserialize the XML into objects (leaving extension points as <code>XmlElement</code>'s) and then resolve .NET types for plugins, or create a custom <code>IXmlSerializable</code> implementation that loads appropriate types.</p></li>\n<li><p>You receive an unstructured XML and want to traverse it looking for familiar nodes, patterns, or anything else. In this case proper solution would be to use <code>XDocument</code> or <code>XmlDocument</code>, or even <code>XmlReader</code> if you need maximum performance or expect large documents.</p></li>\n</ol>\n\n<p>I wouldn't recommend using the code that you provided in production as it tries to use XML in its own unique way, which means you won't get support from existing frameworks, and other clients that may want to generate XML consumed by your service would have to design their own hacks. Also the code itself is quite unreadable due to nested conditions and large methods, consider refactoring it. And it's not recommended to expose class fields as public, even if they are readonly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T22:25:57.670",
"Id": "29881",
"Score": "0",
"body": "I have very little experience with XML, this is the first time I've ever worked with it. I'll consider your suggestions and look at `IXmlSerializable` as a better way to implement."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T12:28:25.693",
"Id": "18703",
"ParentId": "15922",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T18:48:01.913",
"Id": "15922",
"Score": "4",
"Tags": [
"c#",
"strings",
"xml"
],
"Title": "Parsing XML to create IList"
}
|
15922
|
<p>I am looking for some ideas on how this could be improved:</p>
<pre><code>switch ($periodValue) {
case "lastmonth":
$until = mktime(0, 0, 0, date('n'), 1, date('Y'));
$from = mktime(0, 0, 0, date('n', $until) - 1, 1, date('Y', $until));
break;
case "last3month":
$until = mktime(0, 0, 0, date('n'), 1, date('Y'));
$from = mktime(0, 0, 0, date('n', $until)-3, 1, date('Y', $until));
break;
case "last6month":
$until = mktime(0, 0, 0, date('n'), 1, date('Y'));
$from = mktime(0, 0, 0, date('n', $until)-6, 1, date('Y', $until));
break;
</code></pre>
<p>How could I make this "smarter", so that it works out if we are near the end of the month it will show the last 30 days instead of the previous month? </p>
|
[] |
[
{
"body": "<p>The date/time functions in PHP are a tricky thing. Last I looked into this there were known bugs with many of the date/time functions, especially around leap years, but no solutions. I don't know if that has changed, haven't had the need to look, so this answer might not be the best one, but have you tried <code>strtotime()</code>?</p>\n\n<pre><code>$period = 30;//90 for 3 months, 180 for 6 months\n\n$until = strtotime( 'now' );\n$from = strtotime( \"-$period days\" );\n//or\n$period = 'last month';//'last 3 months', or 'last 6 months'\n$from = strtotime( $period );\n</code></pre>\n\n<p>I've not tried any of the above, but I'm fairly confident the first half should work, but I'm not sure about the last half. However, <code>strtotime()</code> is a pretty smart function, so who knows. Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-31T09:55:30.860",
"Id": "376474",
"Score": "0",
"body": "90 days ago isn't actually 3 months ago. for example if now is 31/5/2018 which is the time of this comment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T20:19:43.660",
"Id": "15924",
"ParentId": "15923",
"Score": "0"
}
},
{
"body": "<p>Try the <a href=\"http://php.net/manual/en/class.datetime.php\" rel=\"nofollow\" title=\"DateTime\">DateTime</a> class. In combination with the <a href=\"http://php.net/manual/en/class.dateinterval.php\" rel=\"nofollow\">DateInterval</a> class you can do something like this:</p>\n\n<pre><code>$until = new DateTime();\n$interval = new DateInterval('P2M');//2 months\n$from = $until->sub($interval);\necho 'from' . $from->format('Y-m-d') . 'until' . $until->format('Y-m-d');\n</code></pre>\n\n<p>Also, you have to set the <code>$until</code> variable only once, <strong>before</strong> the switch statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T20:59:50.880",
"Id": "15925",
"ParentId": "15923",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "15925",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T18:50:43.873",
"Id": "15923",
"Score": "8",
"Tags": [
"php",
"datetime"
],
"Title": "Calculate last month, last 3 months, and last 6 months from today"
}
|
15923
|
<p>I have written a PDO wrapper and a class file like a model. It's looking good so far, but I'm just confuseed on where I should put the <code>try</code>/<code>catch</code> block. Would it be better to place it in the PDO wrapper (pdoDatabase.php), mobile.php (model) or test.php?</p>
<p><strong>pdoDatabase.php</strong></p>
<pre><code>class pdoDatabase {
public $db;
private $sth;
private static $instance;
private $error;
private function __construct() {
$dsn = "mysql:dbname=" . config::read("db.database") . ";host=localhost";
$username = config::read("db.username");
$password = config::read("db.password");
$this->db = new PDO($dsn, $username, $password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new static();
}
return self::$instance;
}
public function fetchData($sql, $params = array(), $fetchMode = 'all') {
// Should try...catch block be here?
try {
$this->sth = $this->db->prepare($sql);
if (count($params) > 0)
$this->setBind($params);
$this->sth->execute();
$fetch = ($fetchMode == 'single') ? "fetch" : "fetchAll";
return $this->sth->$fetch();
} catch (PDOException $e) {
$this->error = array(
'status' => 'error',
'message' => $e->getMessage()
);
return false;
}
}
public function setBind($params) {
if (is_object($this->sth)) {
foreach ($params as $key => $value) {
$this->sth->bindValue(":$key", $value);
}
}
}
public function error() {
return $this->error;
}
public function beginTransaction() { }
public function commit() { }
public function rollBack() { }
</code></pre>
<p><strong>mobile.php</strong></p>
<pre><code>class Mobile {
public $db;
public function __construct() {
$this->db = pdoDatabase::getInstance();
}
public function findPhoneAffiliate($phoneId = null, $affiliateId = null, $affiliatePhoneId = null) {
// or should try...catch block be here?
$bindAr = array();
if ($phoneId !== null)
$whereAr[] = "phone_id = " . $phoneId;
if ($affiliateId !== null)
$whereAr[] = 'affiliate_id = ' . $affiliateId;
if ($affiliatePhoneId !== null) {
$whereAr[] = 'affiliate_phone_id = :affiliate_phone_id';
$bindAr['affiliate_phone_id'] = $affiliatePhoneId;
}
$where = count($whereAr) > 0 ? 'WHERE ' . implode(' AND ', $whereAr) : '';
$sql = "SELECT * FROM phone_affiliate $where";
return $this->db->fetchData($sql, $bindAr, 'single');
}
}
</code></pre>
<p><strong>test.php</strong></p>
<pre><code>$mobileResult = $mobile->findPhoneAffiliate(null, 'f', "ASEF33");
if ($mobileResult) {
// Data Found!
print_r($mobileResult);
} else {
if ($mobile->db->error()) {
print_r($mobile->db->error());
exit();
}
if ($mobile->db->rowCount() == 0)
echo "Data Not Found";
}
</code></pre>
<p>As you can see, it will need to check if there any error or no data found in the <code>else</code> statement. Is this how it should be done? If now, what can be improved to reduce the code from the test.php sample?</p>
|
[] |
[
{
"body": "<p>I'll probably revisit this later, but for now:</p>\n\n<hr>\n\n<p>The exception catching should be done at either the model or model-using layer. I would probably let the exceptions bubble up through the model unless you want the model to be fairly high level.</p>\n\n<p>For the sake of abstracting the DB layer away from the model layer, I might consider wrapping the PDOException in some kind of model exception(s). Exception wrapping is typically an anti-pattern, but it would keep your consuming code from needing to know that the models are all dependent on PDO. (Thus allowing you to change PDO to something else if you ever wanted to -- basically it's a weird instance of separation of concerns and hiding implementation details.)</p>\n\n<p>I'm starting to ramble, but what I'm trying to convey is that your consuming code needs to know something went wrong. If you handle the exception in your DB class, you model has no (pleasant) way to know that something went wrong. If you handle the exception in your model, the level above the model has no (pleasant) way to know something went wrong. Basically your consuming code needs to know something happened, and for that to be the case, you need exceptions to come out of the model. (An alternative would of course be returning a Boolean or something along those lines. That tends to not fit the OO paradigm very well though, and PDO sometimes uses Boolean false when something isn't an error.)</p>\n\n<hr>\n\n<p>Your pdoDatabase class shouldn't be a <a href=\"https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons\">singleton</a>.</p>\n\n<hr>\n\n<p><code>$this->db = pdoDatabase::getInstance();</code> you pass the pdoDatabase instance as a parameter instead of coupling your code to this static method.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependency Injection</a></p>\n\n<hr>\n\n<p>There's a few other things that stuck out to me, but I'm out of time now ;(. Will come back later.</p>\n\n<hr>\n\n<p><strong>Exception Catching</strong></p>\n\n<p>It should be extremely rare for an exception to actually happen with your <code>Mobile</code>.</p>\n\n<p>Consider the sources of exceptions: connection drops, invalid syntax, unknown column/table/etc, so on. Basically there's different layers of exceptions. There's the connection oriented ones, and the SQL oriented ones. The SQL oriented ones should never happen. By the time your code goes into production, you should be certain that none of your queries have invalid syntax, reference non-existing entities, so on.</p>\n\n<p>This leaves connection problems as the only source of exceptions (or perhaps MySQL related hiccups, though those should be pretty rare).</p>\n\n<p>Because of this rarity, I would be tempted to basically ignore any exceptions.</p>\n\n<p>Even if you did handle the exceptions, what are you going to do with them?</p>\n\n<pre><code>try {\n $affs = $mobile->findPhoneAffiliate(5);\n} catch (SomeExceptionClass $ex) {\n //There's not really a good way to recover from this, so you might as well\n //show some kind of \"Oops, something broke.\" page.\n //You could then log the exception behind the scenes and make sure the end-user\n //sees nothing sensitive.\n}\n</code></pre>\n\n<p>What I would do in this situation is just let the exception bubble up to the very top. I would have a giant try/catch at the top layer though that intercepts any uncaught exceptions and renders some kind of error page.</p>\n\n<p>How you do this will highly depend on the structure of your website, but assuming you're doing something MVC-ish, it should be fairly simple. In the catch block, just kill the current dispatch, and instead dispatch a request for the exception page.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T09:17:24.803",
"Id": "25927",
"Score": "0",
"body": "Thanks Corbin and that was helpful. Looking forward for more details and also would be great if you include the code of `exception` how it should be done from my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T19:03:59.247",
"Id": "26411",
"Score": "0",
"body": "@I'll-Be-Back I've tried to elaborate a bit more on the exception situation. Let me know if that brings up any more questions :)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T01:31:18.087",
"Id": "15940",
"ParentId": "15927",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "15940",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T21:13:42.363",
"Id": "15927",
"Score": "5",
"Tags": [
"php",
"php5",
"exception-handling",
"pdo"
],
"Title": "Try/catch block in PDO wrapper"
}
|
15927
|
<p>Please suggest ways of cleaning up this code.</p>
<pre><code>Hashtable newValues = e.Values;
string NewPosition = null;
string NewFirst = null;
string NewLast = null;
string NewEmail = null;
int NewAppt = 0;
if (newValues["Position"] == null)
{
NewPosition = "";
}
else
{
NewPosition = newValues["Position"].ToString();
}
if (newValues["First Name"] == null)
{
NewFirst = "";
}
else
{
NewFirst = newValues["First Name"].ToString();
}
if (newValues["Last Name"] == null)
{
NewLast = "";
}
else
{
NewLast = newValues["Last Name"].ToString();
}
if (newValues["Email"] == null)
{
NewEmail = "";
}
else
{
NewEmail = newValues["Email"].ToString();
}
if (newValues["Appts"] == null)
{
NewAppt = 0;
}
else
{
NewAppt = 1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:23:05.090",
"Id": "25903",
"Score": "0",
"body": "I would suggest rewording the question to only have a representative snippet of that pattern, rather than repeating it 5 times"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T20:02:36.360",
"Id": "25904",
"Score": "0",
"body": "I didn't know that was an option. Thanks @DaveZych. I will keep that in mind for future postings like this one."
}
] |
[
{
"body": "<p>You can use the <em>null-coalescing operator</em> <a href=\"http://msdn.microsoft.com/en-us/library/ms173224.aspx\" rel=\"nofollow\"><code>??</code></a> like this:</p>\n\n<pre><code>NewPosition = (newValues[\"Position\"] ?? \"\").ToString();\n</code></pre>\n\n<p>The core of this approach is this expression:</p>\n\n<pre><code>newValues[\"Position\"] ?? \"\"\n</code></pre>\n\n<p>The <code>??</code> operator evaluates the left expression first (i.e. <code>newValues[\"Position\"]</code>), and uses it as the result if it's not <code>null</code>. If the first expression is <code>null</code>, the second expression is evaluated, and its result is returned as the overall result of the expression.</p>\n\n<p>For the last one, use <code>?</code>:</p>\n\n<pre><code>NewAppt = (newValues[\"Appts\"] != null) ? 1 : 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:24:05.347",
"Id": "25906",
"Score": "0",
"body": "Does this also assign the value if it is not null? Could you explain how this works just so I understand it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:25:58.420",
"Id": "25907",
"Score": "0",
"body": "And do I create the var first like string `NewPosition;` or Can I do a full assignment like string `NewPosition = (newValues[\"Position\"] ?? \"\").ToString();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:27:27.890",
"Id": "25908",
"Score": "0",
"body": "@JamesWilson Since the expression fits on a single line, you can combine the declaration with initialization, like this: `var NewPosition = (newValues[\"Position\"] ?? \"\").ToString();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:27:51.333",
"Id": "25909",
"Score": "0",
"body": "@JamesWilson Literally, ?? means \"unless it is null, in which case use\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T14:46:46.220",
"Id": "25938",
"Score": "4",
"body": "+1 Outstanding. Though I'd replace \"\" with `string.Empty` as a matter of habit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:18:10.180",
"Id": "52956",
"Score": "0",
"body": "-1, all this does is make it harder to maintain, reuse, and read the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:35:44.110",
"Id": "52961",
"Score": "1",
"body": "@AMissico It does make things harder to developers unfamiliar with the `??` operator. Developers who are familiar with their basic technology, on the other hand, tend to appreciate the beauty and the brevity of this approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T20:03:13.923",
"Id": "52966",
"Score": "0",
"body": "It makes it harder to change the code. If you use ?? you have have to change every statement. If you use a method that use ??, then you only have to change the method. Also, the method's implementation can change without affecting the statements. Our responsibility is to write code we can read, understand, and modify. Anyone can write crap."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T20:10:43.083",
"Id": "52967",
"Score": "1",
"body": "@AMissico Note that `??` can be replaced with `+` without changing the validity of your statement. Yet very few people in their right mind write `AddOne(length)` instead of `length+1`, and it does not make anyone's code any harder to \"maintain, reuse, and read\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:09:38.683",
"Id": "52973",
"Score": "0",
"body": "Change the `??` statement to support `DBNull`. Tell me how long it takes you to change each statement. Then tell me how long it takes you if a method was used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:12:01.043",
"Id": "52974",
"Score": "0",
"body": "After you are done with that exercise. Change the `??` statements to support more than just a `string`. In the long run, using a method is the only logical choice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:30:48.977",
"Id": "52980",
"Score": "0",
"body": "@AMissico `??` operator does not support `DBNull`; minus operator `-` does not support strings. It would be very silly of me, however, to keep in mind an unlikely possibility of supporting `string`s some day while crafting my `int`-based solutions that needs a minus operator."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:19:34.900",
"Id": "15929",
"ParentId": "15928",
"Score": "15"
}
},
{
"body": "<p>This is a pattern that will reduce the lines, and IMO, make it easier to read.</p>\n\n<p>Old:</p>\n\n<pre><code>if (newValues[\"Position\"] == null)\n{\n NewPosition = \"\";\n}\nelse\n{\n NewPosition = newValues[\"Position\"].ToString();\n}\n</code></pre>\n\n<p>New:</p>\n\n<pre><code>NewPosition = newValues[\"Position\"] == null ? string.Empty : newValues[\"Position\"].ToString();\n</code></pre>\n\n<p>As for the integer field:</p>\n\n<p><code>NewAppt = newValues[\"Appts\"] == null ? 0 : 1;</code></p>\n\n<p>Documentation: <a href=\"http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.100).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.100).aspx</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:20:34.773",
"Id": "15930",
"ParentId": "15928",
"Score": "2"
}
},
{
"body": "<p>My preferred option is using the ternary operator when you are doing operations such as that.</p>\n\n<p>Here is a brief example:</p>\n\n<pre><code>string NewPosition = newValues[\"Position\"] != null ? newValues[\"Position\"].ToString() : String.Empty;\n</code></pre>\n\n<p>The way it work is like this:</p>\n\n<p>variable = boolean expression ? value that gets assigned when true : value that gets assigned when false.</p>\n\n<p>You must be careful not to make your code difficult to read when using the ternary operator since it puts it in one line, however I find in most cases it makes it more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:22:47.167",
"Id": "15933",
"ParentId": "15928",
"Score": "3"
}
},
{
"body": "<p>While these are all good suggestions, I would wrap the code into a method.</p>\n\n<pre><code>NewPosition = GatherValue(\"Position\");\nNewFirst = GatherValue(\"First Name\");\n\n...\nstring GatherValue(string name) {\n return newValues[name] == null ? \"\" : newValues[name].ToString(); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:32:41.053",
"Id": "25911",
"Score": "0",
"body": "Does this offer any benefit over the other option, or is it just personal preference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T20:01:16.697",
"Id": "25912",
"Score": "0",
"body": "@James: Data container access method encapsulation/extraction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T20:04:31.897",
"Id": "25913",
"Score": "0",
"body": "I would need to make a seperate method for the int portion I am assuming? Or modify the GatherValue to return a different value if the one passed in is Appts right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T00:58:32.727",
"Id": "25954",
"Score": "0",
"body": "@James Wilson; Yes, create another method for the int."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T00:59:04.600",
"Id": "25955",
"Score": "0",
"body": "Personal preference based on a couple decades of experience. :O)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T01:05:03.847",
"Id": "25957",
"Score": "0",
"body": "The immediate benefit is reuse and maintainence. Later, the code can be easily converted to an extension method for dictionaries (IDictionary) that can handle all data types."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:26:22.000",
"Id": "15935",
"ParentId": "15928",
"Score": "8"
}
},
{
"body": "<p>This code could be refactored like this:</p>\n\n<pre><code>HashTable newValues = e.Values;\nstring NewPosition = string.Empty;\nstring NewFirst = string.Empty; \nstring NewLast = string.Empty;\nstring NewEmail = string.Empty;\nint NewAppt;\n\nNewPosition = (newValues[\"Position\"] ?? string.Empty).ToString();\nNewFirst = (newValues[\"First Name\"] ?? string.Empty).ToString();\nNewLast = (newValues[\"Last Name\"] ?? string.Empty).ToString();\nNewEmail = (newValues[\"Email\"] ?? string.Empty).ToString();\nNewAppt = newValues[\"Appts\"] == null ? 0 : 1\n</code></pre>\n\n<p>Things to note: </p>\n\n<ul>\n<li>you don't need to declare the int as 0 - it defaults to 0, NB: C# structs (like int) are not nullable.</li>\n<li>If you are using a recent version of c#, use the var keyword to improve the readability of your variable declarations.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:45:08.457",
"Id": "25914",
"Score": "0",
"body": "This will just result in null reference exceptions when the values are null"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:53:10.670",
"Id": "25916",
"Score": "0",
"body": "Now it's just like several other existing answers..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T20:00:05.527",
"Id": "25917",
"Score": "0",
"body": "@Servy: Doesn't deserve downvote though imo."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T14:48:58.137",
"Id": "25939",
"Score": "0",
"body": "Why initialize the local string variables when they are instantly replaced? Extra coding and loss of performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T15:10:02.370",
"Id": "25940",
"Score": "0",
"body": "Valid question. The only reason is because I hate initializing variables as null as the OP did. I know you can use string.IsNullOrEmpty() but a lazy programmer might not bother in the future when changing the code - leading to trouble. Eg: imagine if someone removed one of the lines that assign values to the strings, or changed it. Accessing the variable later on would cause an exception. So I guess I'm trying to make it foolproof."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T18:36:49.467",
"Id": "25978",
"Score": "1",
"body": "@Kryptonite Actually, as it seems these are all done as local variables in a method, they won't be `null` if you remove the initialization altogether. They'll be *undefined* until assigned, which the assignments immediately do."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:39:33.120",
"Id": "15936",
"ParentId": "15928",
"Score": "1"
}
},
{
"body": "<p>Other than null coalescing operator, you could also simply add empty string </p>\n\n<pre><code>NewFirst = newValues[\"First Name\"]+\"\";\n</code></pre>\n\n<p>For the following reason:</p>\n\n<blockquote>\n <p>7.8.4 Addition operator</p>\n \n <p>String concatenation:</p>\n \n <p>string operator +(string x, string y); string operator +(string x,\n object y); string operator +(object x, string y);</p>\n \n <p>These overloads of the binary + operator perform string concatenation.\n If an operand of string concatenation is null, an empty string is\n substituted. Otherwise, any non-string argument is converted to its\n string representation by invoking the virtual ToString method\n inherited from type object. If ToString returns null, an empty string\n is substituted.</p>\n</blockquote>\n\n<p>This will not work for integers/booleans/etc. Mostly just for strings or anything the .ToString() overload gives you that you actually want. For other cases i'd suggest null coalescing operator or some other approach like other answers provide here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T01:03:05.453",
"Id": "25956",
"Score": "0",
"body": "This is an old hack that relies on the storage variable to be a string. It is not an improvement. Over the years, this trick has caused by problems in two projects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T19:52:59.260",
"Id": "26128",
"Score": "0",
"body": "This makes is shorter at the expense of introducing a hack (relying on coincidence). Sometimes this is valid but in this case I would disagree. It is not needed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:45:32.577",
"Id": "15937",
"ParentId": "15928",
"Score": "2"
}
},
{
"body": "<p>In case of <code>Hashtable</code>:</p>\n\n<pre><code>string value = ht[\"key\"] as string ?? \"\";\n</code></pre>\n\n<p>But it's better to use generic thus type-safe <code>Dictionary<string, string></code>:</p>\n\n<pre><code>string value = dic[\"key\"] ?? \"\";\n</code></pre>\n\n<p>or <code>Dictionary<string, objects></code>:</p>\n\n<pre><code>string value = ((string)dic[\"key\"]) ?? \"\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:56:55.900",
"Id": "15938",
"ParentId": "15928",
"Score": "3"
}
},
{
"body": "<p>Given you're using c# 4 I'd suggest to create a static extension method for your values.</p>\n\n<pre><code>public static class MyExtensions\n{\n public static string ToValueOrStringEmpty(this object myString)\n {\n return string.IsNullOrEmpty((string)myString) \n ? string.Empty \n : (string)myString;\n }\n}\n</code></pre>\n\n<p>Your code now is:</p>\n\n<pre><code>NewPosition = newValues[\"Position\"].ToValueOrStringEmpty();\nNewFirst = newValues[\"First Name\"].ToValueOrStringEmpty();\nNewLast = newValues[\"Last Name\"].ToValueOrStringEmpty();\nNewEmail = newValues[\"Email\"].ToValueOrStringEmpty();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T10:19:27.850",
"Id": "16072",
"ParentId": "15928",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "15929",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T19:16:47.677",
"Id": "15928",
"Score": "10",
"Tags": [
"c#",
".net"
],
"Title": "Cleaning up conditional statements regarding new values"
}
|
15928
|
<p>How can I make this more readable?</p>
<pre><code>public class RssFeed
{
string url = "http://www.pwop.com/feed.aspx?show=dotnetrocks&filetype=master";
public string responseBody;
private string DATE_FORMAT = "ddd, dd MMM yyyy HH:mm:ss \\E\\D\\T";
public Story[] Getstories()
{
getContent();
var stories = Parse(responseBody);
return GetMostRecent5(stories, new StoryComparer());
}
public void getContent()
{
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
WebResponse response = req.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
responseBody = sr.ReadToEnd();
}
static Story[] Parse(string content)
{
var items = new List<string>();
int start = 0;
while (true)
{
var nextItemStart = content.IndexOf("<item>", start);
var nextItemEnd = content.IndexOf("</item>", nextItemStart);
if (nextItemStart < 0 || nextItemEnd < 0) break;
String nextItem = content.Substring(nextItemStart, nextItemEnd + 7 - nextItemStart);
items.Add(nextItem);
start = nextItemEnd;
}
var stories = new List<Story>();
for (byte i = 0; i < items.Count; i++)
{
stories.Add(new Story() {
title = Regex.Match(items[i], "(?<=<title>).*(?=</title>)").Value,
link = Regex.Match(items[i], "(?<=<link>).*(?=</link>)").Value,
date = Regex.Match(items[i], "(?<=<pubDate>).*(?=</pubdate>)").Value
});
}
return stories.ToArray();
}
private static T[] GetMostRecent5<T>(T[] stories, IComparer<T> comparer)
{
List<T> recentStories = stories.Take(5).ToList();
recentStories.Sort(comparer);
var recentStoriesArray = new T[5];
for (int i = 0; i <= 5; i++)
{
recentStoriesArray[i] = recentStories[i];
}
return recentStoriesArray;
}
public class Story
{
public string title;
public string link;
public string date;
public override bool Equals(object obj)
{
return this.Equals(obj as Story);
}
public bool Equals(Story story)
{
return this.link == story.link;
}
}
private class StoryComparer : IComparer<Story>
{
public int Compare(Story x, Story y)
{
if (x.Equals(y))
return 0;
//redundant else
else
return x.date.CompareTo(y.date);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Not that ugly. I've seen ugly code, and trust me, this is not ugly.</p>\n\n<p>However, this is kind of a \"God Class\" that has more than a single responsibility, hence it violates <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">SRP principle</a>.</p>\n\n<h1>How to improve</h1>\n\n<p>Separate the class to:</p>\n\n<p>ContentFetcher, which is responsible for fetching only</p>\n\n<p>StoryParser, which parses the content and creates instances of your object model (<code>Story[]</code>)</p>\n\n<p>Both of the above should implement the <code>Try..</code> pattern, so that the single method in the <code>ContentFetcher</code> has the following signature: </p>\n\n<pre><code>bool TryFetch(out string content){ /* code */ }\n</code></pre>\n\n<p>The same goes for <code>StoryParser</code>.</p>\n\n<h2>As for the fetcher itself</h2>\n\n<ol>\n<li><p>You can choose if the URL is either injected in the constructor, or is part of the method signature. Modern OOP coding is biased towards the constructor technique.</p></li>\n<li><p>The code should implement the <code>using (...) { ... }</code> pattern for classes that implement the <code>IDisposable</code> interface, and be wrapped in a try-catch what so ever.</p></li>\n</ol>\n\n<h2>As for the parser itself</h2>\n\n<ol>\n<li><p>since rss is a format on top of xml, I don't think it's a good idea to parse it using regular expressions. Let the framework do the parsing by using either <code>XmlDocument</code> or <code>XDocument</code>. Or use an external library to parse the string for you (hopefully it's implemented by the above techniques, and not by using <code>Regex</code>es).</p></li>\n<li><p>a try-catch might be needed here, too</p></li>\n</ol>\n\n<h2>Putting it all together</h2>\n\n<p>So finally, the class you have should use the above two classes (a fetcher and a parser), and then, getting the stories from the feed should look like this:</p>\n\n<pre><code>public Story[] Getstories()\n{\n string content;\n if (!this.fetcher.TryGetContent(out content)) return null;\n Story[] stories;\n if (!this.parser.TryParse(out stories)) return null; \n return GetMostRecent5(stories, new StoryComparer());\n}\n</code></pre>\n\n<p>As you can see, <code>null</code> is a special value for failure. You can change that to <code>TryGetStories</code> which returns a <code>boolean</code> and and <code>out</code> parameter if you want to avoid the special value of <code>null</code>.</p>\n\n<p>The actual instances of <code>fetcher</code> and <code>parser</code> can be created by the class itself (in the constructor) and/or be <em>injected</em> to the class by the constructor. Let's see the injection pattern:</p>\n\n<pre><code>public class RssFeed\n{ \n private readonly ContentFetcher fetcher;\n private readonly StoryParser parser;\n\n public RssFeed(ContentFetcher fetcher, StoryParser parser)\n {\n if (null == fetcher) throw new ArgumentNullException(\"fetcher\");\n if (null == parser) throw new ArgumentNullException(\"parser\");\n this.fetcher = fetcher;\n this.parser = parser;\n }\n}\n</code></pre>\n\n<p>As a final step of refactoring, you can extract the preparing code to its own method, moving the parsed stories to be part of the class' state:</p>\n\n<pre><code>private Story[] stories = null;\n\nprivate bool Prepare()\n{\n if (this.stories != null) return true;\n string content;\n if (!this.fetcher.TryGetContent(out content)) return false;\n Story[] temp;\n if (!this.parser.TryParse(out temp)) return false;\n this.stories = temp;\n return true;\n}\n\npublic Story[] Getstories()\n{\n if (!Prepare()) return null;\n return GetMostRecent5(this.stories, new StoryComparer());\n}\n</code></pre>\n\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T05:08:55.090",
"Id": "15943",
"ParentId": "15942",
"Score": "12"
}
},
{
"body": "<p>To add to what Ron Klein said (in no particular order):</p>\n\n<ol>\n<li>Use <code>WebClient</code> (or possibly <code>HttpClient</code>, if you're on .Net 4.5) instead of <code>WebRequest</code> and <code>StreamReader</code>, it will make your code simpler.</li>\n<li>Consider using <code>var</code> more in your code (although this is a question of style and not everybody would agree with that).</li>\n<li>If you know a method returns more specific type than its return type claims (such as <code>WebRequest.Create()</code> with HTTP URL), use cast instead of <code>as</code>. This way, if something goes wrong, you will immediately get a helpful <code>InvalidCastException</code>, instead of a confusing <code>NullReferenceException</code> later.</li>\n<li>Use consistent naming conventions, ideally <a href=\"http://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"nofollow\">the ones recommended by Microsoft</a>. (So, don't call one method <code>getContent</code> and another <code>GetStories</code>).</li>\n<li>Consider using interfaces like <code>IEnumerable<T></code> and <code>IList<T></code> (and <code>IReadOnlyList<T></code> if you're on .Net 4.5) instead of arrays. Arrays cannot change their length, but the items in them can change. Most of the time, this isn't what you want. You either want to allow mutating both the length and the individual items (in that case, use <code>IList<T></code>), or don't allow mutating either (in that case use <code>IEnumerable<T></code> or <code>IReadOnlyList<T></code>).</li>\n<li>A method like <code>GetMostRecent5()</code> is awfully specific, consider changing it to something like <code>GetMostRecent()</code> and passing the number as parameter.</li>\n<li>Don't use fields the way you use <code>responseBody</code>. Instead use return value of the method (or <code>out</code> parameter, as Ron suggested).</li>\n<li>Don't use regular expressions to parse XML, use an XML library, such as LINQ to XML. (Ron already mentioned this, but I think this is so important it bears repeating.)</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T06:43:59.730",
"Id": "15946",
"ParentId": "15942",
"Score": "8"
}
},
{
"body": "<p>A few additional things:</p>\n\n<ul>\n<li>Story should probably implement IEquatable<Story>, since you already\nhave the method implementation present on the class. </li>\n<li>Since you are overriding Equals on Story, you should also override GetHashCode. The compiler should actually be giving you warnings about this already.</li>\n<li>Consider changing Story to expose its values as properties rather than public fields. This gives you the flexibility to change their underlying behavior later without breaking anyone referencing the class.</li>\n<li>Re: the XML parsing - I would agree with the sentiment that you should avoid Regex for this. You may consider using <a href=\"http://msdn.microsoft.com/en-us/library/ms733127.aspx\" rel=\"nofollow\">Data Contracts</a>.</li>\n<li>If the date order is something you always want to use for stories, you may consider moving the comparison code to the Story class and mark it as implementing IComparable<Story>. Once you do that, your list.Sort will no longer require the comparer parameter, as it will identify Story as IComparable and use its CompareTo method.</li>\n<li>Alternatively, you may simply use a LINQ <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.orderby.aspx\" rel=\"nofollow\">IEnumerable<T>.OrderBy</a> statement instead of List<T>.Sort.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T17:59:52.280",
"Id": "15959",
"ParentId": "15942",
"Score": "3"
}
},
{
"body": "<ol>\n<li><p>I want to emphasize how important it is to override <code>GetHashCode()</code> is when you override <code>Equals</code>. If you don't, all hashtable based collections/algorithms will sometimes fail in unexpected ways. This includes <code>HashSet<T></code>, <code>Dictionary<K,V></code> and LINQ functions like <code>Distinct</code> or <code>GroupBy</code>.</p></li>\n<li><p><code>GetMostRecent5</code> can be simplified:</p>\n\n<ul>\n<li><p>You can use <code>ToArray</code> to create an array from a list instead of writing a loop</p>\n\n<pre><code>private static T[] GetMostRecent5<T>(T[] stories, IComparer<T> comparer)\n{\n List<T> recentStories = stories.Take(5).ToList();\n recentStories.Sort(comparer);\n var recentStoriesArray = recentStories.ToArray();\n return recentStoriesArray;\n}\n</code></pre></li>\n<li><p>You can use <code>Array.Sort</code> so you don't need to copy from a list.</p>\n\n<pre><code>private static T[] GetMostRecent5<T>(T[] stories, IComparer<T> comparer)\n{\n T[] recentStories = stories.Take(5).ToArray();\n Array.Sort(recentStories, comparer);\n return recentStories;\n}\n</code></pre></li>\n<li><p>You can use LINQ for sorting, so you don't need a temporary array.</p>\n\n<pre><code>private static T[] GetMostRecent5b<T>(T[] stories, IComparer<T> comparer)\n{\n return stories.Take(5).OrderBy(story => story, comparer).ToArray();\n}\n</code></pre></li>\n<li><p>You don't need a custom comparer. LINQ's <code>OrderBy</code> takes a projection as first parameter. You can simply project to <code>story.Date</code>.</p>\n\n<pre><code>private static T[] GetMostRecent5b<T>(T[] stories)\n{\n return stories.Take(5).OrderBy(story => story.Date).ToArray();\n}\n</code></pre></li>\n</ul>\n\n<p>At this point it's so short that it might not even deserve its own method anymore.</p></li>\n<li><p>Since you call <code>Take(5)</code> before sorting you're relying on the items being sorted by the <code>Date</code> in descending order. If that assumption is correct you don't actually need to sort again, you can simply reverse the order to ascending.</p>\n\n<pre><code>stories.Take(5).Reverse().ToArray();\n</code></pre>\n\n<p>If that assumption is not always true you need to sort before calling <code>Take(5)</code>, else you won't get the most recent items.</p>\n\n<pre><code>stories.OrderBy(story => story.Date).Take(5).Reverse().ToArray();\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T21:14:02.650",
"Id": "33886",
"ParentId": "15942",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "15943",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T03:16:07.440",
"Id": "15942",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"parsing",
"rss"
],
"Title": "RSS feed class in C#"
}
|
15942
|
<p>I have a data stream of bytes and I'd like to get a little endian encoded int32 from four bytes. Is there a better way than to do this like the following code?</p>
<pre><code>package main
func read_int32(data []byte) int32 {
return int32(uint32(data[0]) + uint32(data[1])<<8 + uint32(data[2])<<16 + uint32(data[3])<<24)
}
func main() {
println(read_int32([]byte{0xFE,0xFF,0xFF,0xFF})) // -2
println(read_int32([]byte{0xFF,0x00,0x00,0x00})) // 255
}
</code></pre>
<p>The code above seems to work fine, but perhaps there is a built-in function in Go that I've missed or there is a super cool hack that does that in one instruction?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T07:10:39.247",
"Id": "25924",
"Score": "0",
"body": "This page should help. http://golang.org/pkg/encoding/binary/#ReadVarint"
}
] |
[
{
"body": "<p><code>encoding/binary</code> package may have what you need. Check this: <a href=\"http://golang.org/pkg/encoding/binary/#example_Read\">http://golang.org/pkg/encoding/binary/#example_Read</a></p>\n\n<p>Your code with modified <code>read_int32</code> function could be:</p>\n\n<pre><code>package main\nimport (\n \"bytes\"\n \"encoding/binary\"\n \"fmt\"\n)\n\nfunc read_int32(data []byte) (ret int32) {\n buf := bytes.NewBuffer(data)\n binary.Read(buf, binary.LittleEndian, &ret)\n return\n}\n\nfunc main() {\n fmt.Println(read_int32([]byte{0xFE, 0xFF, 0xFF, 0xFF})) // -2\n fmt.Println(read_int32([]byte{0xFF, 0x00, 0x00, 0x00})) // 255\n}\n</code></pre>\n\n<p>Also you can interpret big endian by replacing <code>binary.LittleEndian</code> with <code>binary.BigEndian</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T07:29:36.387",
"Id": "28991",
"Score": "0",
"body": "That looks fine, I'll try it out and report back. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T02:04:21.197",
"Id": "18169",
"ParentId": "15945",
"Score": "12"
}
},
{
"body": "<p>This is a really late answer, however there are 2 different ways to do it.</p>\n\n<pre><code>func readInt32(b []byte) int32 {\n // equivalnt of return int32(binary.LittleEndian.Uint32(b))\n return int32(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)\n}\n\n// this is much faster and more efficient, however it won't work on appengine \n// since it doesn't have the unsafe package.\n// Also this would blow up silently if len(b) < 4.\nfunc ReadInt32Unsafe(b []byte) int32 {\n return *(*int32)(unsafe.Pointer(&b[0]))\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-08T14:36:43.080",
"Id": "155519",
"Score": "0",
"body": "How to modify func readInt32 to return float32 value?\nI'd tried to just change `return int32(...)` to `retrun float32(...)` and get wrong data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-03T19:29:12.613",
"Id": "214904",
"Score": "1",
"body": "@ΠΠΎΡΠΈΡ, replace `int32` with `math.Float32frombits`. See [here](https://play.golang.org/p/aG8GRNPRh3). Internally, it uses the `unsafe` cast, but is safe because it operates on a `uint32` instead of a slice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-30T04:48:16.350",
"Id": "534263",
"Score": "0",
"body": "how do you convert an `int` into `[]byte` ?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-15T17:10:18.047",
"Id": "60161",
"ParentId": "15945",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T06:13:21.330",
"Id": "15945",
"Score": "9",
"Tags": [
"go",
"integer",
"serialization"
],
"Title": "Effectively convert little endian byte slice to int32"
}
|
15945
|
<p>I have some <code>ViewModel</code>s that have a lot of parameters like this one:</p>
<pre><code>public class ProductsMainViewModel : NotificationObject, IActiveAware, ...
{
public ProductsMainViewModel(IProductRepository productRepository, IWarehouseRepository warehouseRepository, IUnitOfMeasureRepository unitOfMeasureRepository,
IProductCategoryRepository productCategoryRepository, IProductPriceRepository productPriceRepository, IPriceLevelRepository priceLevelRepository,
ICodingRepository codingRepository, ICategoryRepository categoryRepository, IDialogService dialogService, Logging.ILoggerFacade logger, IRegionManager regionManager,
IJsonSerializer jsonSerializer, ICodeService codeService, IEventAggregator eventAggregator)
{
// ...
}
}
</code></pre>
<p>(All repositories have the same instance of <code>IUnitOfWork</code>)
Instantiating this is done by <code>IUnityContainer</code>, But there are some dialogs that get called in this ViewModel:</p>
<pre><code> var viewModel = new ProductViewModel(_warehouseRepository, _unitOfMeasureRepository,
_productCategoryRepository, _priceLevelRepository, _productPriceRepository, _codingRepository, _dialogService, _codeService, _jsonSerializer);
var result = _dialogService.ShowDialog("ProductWindow", viewModel);
if (result == true)
{
// ...
}
</code></pre>
<p>that their repositories must have the same <code>IUnitOfWork</code> of the current <code>ViewModel</code>. So I decided to pass parameters manually. I found it a good idea to "not reference any IoC container" in my <code>ViewModel</code> in <a href="http://unity.codeplex.com/discussions/391225" rel="nofollow">here</a>.</p>
<blockquote>
<p>The benefit of this approach is that the ViewModel doesn't have any
knowledge of the (Unity) container. Also, in terms of understanding
the application design the dependencies of the ViewModel are easy to
see since they are in the constructor.</p>
</blockquote>
<p>Well, any ideas on how to reduce the number of parameters? Any particular design pattern?</p>
<p>Is it a good idea to create a 'IFooRepositoriesContext' and put related repositories in it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T15:41:03.023",
"Id": "26028",
"Score": "2",
"body": "*\"Is it a good idea to create a 'IFooRepositoriesContext' and put related repositories in it?\"* This is the route I'd go."
}
] |
[
{
"body": "<p>why don't you write an <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow\">abstract factory</a> containing all the references you need?\nYou can then implement a factory method for your ViewModel creating an instance based on some configuration parameters.\nYour client code now doesn't need to know the constructor sintax but just the configuration needed for the right instance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T16:45:24.107",
"Id": "26034",
"Score": "1",
"body": "Thank you for answer, but I choose what @Jesse said before :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T15:01:41.763",
"Id": "16012",
"ParentId": "15947",
"Score": "4"
}
},
{
"body": "<p>I agree with what Jesse said in that a grouping of your repositories into one related is one approach and may be the one best suited in your case. However I'd like to offer another approach and that would be use composition in your ViewModel and have it contain lots of smaller ViewModels.</p>\n\n<blockquote>\n <p>Also, in terms of understanding the application design the\n dependencies of the ViewModel are easy to see since they are in the\n constructor</p>\n</blockquote>\n\n<p>I don't think that splitting the ViewModels up into smaller ones will break this statement . However I also don't necessarily agree with it either. <em>Why should the ViewModel depend on anything</em>? </p>\n\n<p>However what I do think splitting your ViewModels up (where possible of course) is allow you to potentially re-use any Viewmodel while also making each view model specific to a particular part of the design/functional requirement.</p>\n\n<p>So if I was to continue on with the IFooRepositoriesContext approach I might consider something like this:</p>\n\n<pre><code>public ProductViewModel {\n public string ProductOnlyDetail { get; set; }\n public ProductDescriptionViewModel Description { get; set; }\n public ProductPriceViewModel Price { get; set; }\n}\n</code></pre>\n\n<p>or if you wanted to make it explict that the ProductViewModel always needs parameters then create the constructor to take the <em>IFooRepositoriesContext</em>:</p>\n\n<pre><code>public ProductViewModel(IFooRepositoriesContext context) {\n // and build your viewModel there\n}\n</code></pre>\n\n<p>Your sub viewmodels themselves might look like (examples only of course):</p>\n\n<pre><code>public ProductDescriptionViewModel {\n\n public ProductDescriptionViewModel(IProductRepository productRepository, IWarehouseRepository warehouseRepository, IUnitOfMeasureRepository unitOfMeasureRepository,\n IProductCategoryRepository productCategoryRepository)\n {\n\n }\n\n public string Name { get; set; }\n // etc\n}\n\npublic ProductPriceViewModel {\n public decimal Price { get; set; }\n public string Currency { get; set; } \n // etc\n\n public ProductPriceViewModel (IProductPriceRepository productPriceRepository, IPriceLevelRepository priceLevelRepository)\n {\n\n }\n}\n</code></pre>\n\n<p>Then your code might be sonething like:</p>\n\n<pre><code>var viewModel = new ProductViewModel\n{\n Description = new ProductDescriptionViewModel(productRepository, warehouseRepository, unitOfMeasureRepository,\n productCategoryRepository),\n Price = new ProductPriceViewModel(productPriceRepository, priceLevelRepository)\n\n ProductOnlyDetail = \"Hello\" \n}\n\nvar result = _dialogService.ShowDialog(\"ProductWindow\", viewModel);\nif (result == true)\n{\n // ...\n}\n</code></pre>\n\n<blockquote>\n <p>But there are some dialogs that get called in this ViewModel</p>\n</blockquote>\n\n<p>I assume this was a grammatical error and you don't actually call dialogs from within the viewModel itself? If so I seriously think you should reconsider your approach to using the ViewModels.</p>\n\n<p><strong>ViewModelBuilder or someother approach.</strong></p>\n\n<p>Aside from this I would consider having another object that was responsible for building up your viewmodels. Of course it depends on the design and requirements of the system but I would be asking. </p>\n\n<blockquote>\n <p>Will the viewmodel always get the data from x? Is there any reason\n why it couldn't get it from y?</p>\n</blockquote>\n\n<p>If yes then having the viewModel build itself is really limiting it to the knowledge of where and what data to obtain, even if the where of that data is abstracted out view interfaces. There are existing mapping frameworks out there already that may offer assistance if you were worried about the class explosion this might cause?</p>\n\n<p>Hope this helps give a different perspective or some more food for thought :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T11:26:04.293",
"Id": "26143",
"Score": "0",
"body": "When I call `_dialogService.ShowDialog(\"ProductWindow\", viewModel);` a dialog window pops up. What's wrong with that? You can mock or test it simply!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T20:07:31.763",
"Id": "26161",
"Score": "0",
"body": "@Jalalx That's different to what you said. You said some dialogs get called \"in\" this viewModel. Not the viewModel is passed to some dialog service log and is \"used\". Probably just english semantics but does help to clarify your question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T19:31:45.780",
"Id": "16013",
"ParentId": "15947",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "16013",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T06:54:22.453",
"Id": "15947",
"Score": "8",
"Tags": [
"c#",
"mvvm"
],
"Title": "ViewModel constructor with many parameters"
}
|
15947
|
<p>I have learned to make a carousel image slideshow script with JavaScript. I think it's better to learn it from the basic than just from the framework (instant script), but I'm a newbie. I wrote this script using my technique, but I think it's terrible.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var runCarousel, runTimer;
firstval = 0;
secondval = 0;
function Carousel(){
firstval += 10;
document.getElementById('abc-container').style.left = "-" + firstval + "px";
document.getElementById('asas').innerHTML = "-" + firstval;
if(firstval == 400)
{
StopRun();
StartTimer()
return;
}
if(firstval == 800)
{
StopRun();
StartTimer()
return;
}
runCarousel = setTimeout(Carousel, 10);
}
function StartTimer(){
secondval += 1;
document.getElementById('asass').innerHTML = "-" + secondval;
if(secondval == 10)
{
StopTimer();
Carousel();
return;
}
if(secondval == 20)
{
StopTimer();
Carousel();
return;
}
runTimer = setTimeout(StartTimer, 1000);
}
function StopRun(){
window.clearTimeout(runCarousel);
}
function StopTimer(){
window.clearTimeout(runTimer);
}
function firstStart(){
setTimeout("Carousel()", 10000);
}
firstStart();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
width:400px;
height:140px;
position:absolute;
left:50%;
top:50%;
margin: -70px 0 0 -200px;
background: #383838;
overflow: hidden;
}
#abc-container {
position: absolute;
width:1200px;
height:140px;
}
#a {
width:400px;
height:140px;
background: #FF0000;
float: left;
}
#b {
width:400px;
height:140px;
background: #FFFF00;
float: left;
}
#c {
width:400px;
height:130px;
background: #00FFFF;
float: left;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<div id="abc-container">
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
</div>
</div>
<div id="asas"></div>
<div id="asass"></div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Great start for far but you need to work on your overall design.</p>\n\n<p>Here are some tips.</p>\n\n<h2>1) Separate the css, html and javascript into their own files.</h2>\n\n<p>If you were place all your css into a file called \"style.css\" and javascript in a file called \"main.js\", then you could import the files from your html like so.</p>\n\n<pre><code>... more code\n<head>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />\n</head>\n... more code\n<script src=\"main.js\"></script>\n</code></pre>\n\n<h2>2) For your css, try using a creating a class for the box to share common properties.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>#a {\n width:400px;\n height:140px;\n background: #FF0000;\n float: left;\n}\n\n#b {\n width:400px;\n height:140px;\n background: #FFFF00;\n float: left;\n}\n\n#c {\n width:400px;\n height:130px;\n background: #00FFFF;\n float: left; \n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>#a {\n background: #FF0000;\n}\n#b {\n background: #FFFF00;\n}\n#c {\n background: #00FFFF;\n}\n.box{\n width:400px;\n height:140px;\n float: left; \n}\n</code></pre>\n\n<p>Remember to add the classes.</p>\n\n<pre><code><div id=\"abc-container\">\n <div id=\"a\" class=\"box\"></div>\n <div id=\"b\" class=\"box\"></div>\n <div id=\"c\" class=\"box\"></div>\n</div>\n</code></pre>\n\n<h2>3) Don't repeat yourself.</h2>\n\n<p>The if conditions for firstval and secondval can be combined by using or, <code>||</code>.</p>\n\n<p>Old Code:</p>\n\n<pre><code>if(firstval == 400){\n StopRun();\n StartTimer()\n return;\n}\nif(firstval == 800){\n StopRun();\n StartTimer()\n return;\n}\nrunCarousel = setTimeout(Carousel, 10);\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>if(firstval == 400 || firstval == 800){\n StopRun();\n StartTimer()\n}else{\n runCarousel = setTimeout(Carousel, 10);\n}\n</code></pre>\n\n<h2>4) Declare all variables are the top of a function.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>var runCarousel, runTimer;\nfirstval = 0;\nsecondval = 0;\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var runCarousel, runTimer, firstval = 0, secondval = 0;\n</code></pre>\n\n<h2>5) Pass the function name instead of string to <code>setTimeout()</code></h2>\n\n<p>Also it's better to use multiplication when setting the timeout delay.</p>\n\n<p>Old Code:</p>\n\n<pre><code>setTimeout(\"Carousel()\", 10000); \n</code></pre>\n\n<p>New Code: </p>\n\n<pre><code>setTimeout( Carousel, 10 * 1000); \n</code></pre>\n\n<h2>6) Attach all the global variables to a object literal.</h2>\n\n<h2>7) Name variables and functions based on their operations.</h2>\n\n<ul>\n<li>Rename <code>Carousel()</code> to <code>moveToNextSlide()</code></li>\n</ul>\n\n<h2>8) Cache elements for faster lookup.</h2>\n\n<p>Code:</p>\n\n<pre><code>var infoEl = document.getElementById('asas'), \ncontainer = document.getElementById('abc-container');\n</code></pre>\n\n<h2>9) There needs to be a limit for <code>firstval</code> inside <code>Carousel()</code></h2>\n\n<p>Add this:</p>\n\n<pre><code>var abc_container = 1200;\nfirstval += 10;\nif( abc_container < firstval ){\n firstval = 0;\n}\n</code></pre>\n\n<h2>10) Use variables in place of numeric constants.</h2>\n\n<p>It's hard to understand the meaning of <code>400</code>. \nIt seems that <code>400</code> is the width of each box.</p>\n\n<h2>11) secondval isn't needed. Just place everything inside <code>setTimeout()</code> for 10 seconds.</h2>\n\n<p>Better yet <code>seconds</code> as a parameter.</p>\n\n<p>Old Code:</p>\n\n<pre><code>function StartTimer() {\n secondval += 1;\n el.innerHTML = \"-\" + secondval;\n if (secondval == 10 || secondval == 20 ) {\n runTimer = window.setTimeout(StartTimer, 1000);\n }else{\n ...\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>function StartTimer( seconds ) {\n setTimeout(function(){\n window.clearTimeout(runTimer);\n moveToNextSlide();\n }, seconds * 1000);\n}\n</code></pre>\n\n<h2>12) Read the source code from other image slideshow to find out better techniques.</h2>\n\n<p>Here's a place to start. <a href=\"http://www.tripwiremagazine.com/2012/08/jquery-image-slider.html\" rel=\"noreferrer\">http://www.tripwiremagazine.com/2012/08/jquery-image-slider.html</a></p>\n\n<h2>Final Code:</h2>\n\n<p>HTML:</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n <head>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />\n </head>\n <body>\n <div id=\"wrapper\">\n <div id=\"abc-container\">\n <div id=\"a\" class=\"box\"></div>\n <div id=\"b\" class=\"box\"></div>\n <div id=\"c\" class=\"box\"></div>\n </div>\n </div>\n <div id=\"asas\"></div>\n <!-- !!! Use script tag to import \"main.js\" -->\n </body>\n</html>\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>var carouselTimer, runTimer, firstval = 0, \n boxWidth = 400, abc_container = 1200,\n infoEl = document.getElementById('asas'), \n container = document.getElementById('abc-container');\n\nfunction moveToNextSlide() {\n firstval += 10;\n if( abc_container < firstval ){\n firstval = 0;\n return;\n }\n container.style.left = \"-\" + firstval + \"px\";\n infoEl.innerHTML = \"container.style.left.px = \" + firstval;\n if (firstval % boxWidth) {\n carouselTimer = setTimeout(moveToNextSlide, 10);\n }else{\n window.clearTimeout(carouselTimer);\n StartTimer( 2 );\n }\n}\nfunction StartTimer( seconds ) {\n setTimeout(function(){\n window.clearTimeout(runTimer);\n moveToNextSlide();\n }, seconds * 1000);\n}\nStartTimer( 2 );\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#wrapper {\n width:400px;\n height:140px;\n position:absolute;\n left:50%;\n top:50%;\n margin: -70px 0 0 -200px;\n background: #383838;\n overflow: hidden;\n}\n#abc-container {\n position: absolute;\n width:1200px;\n height:140px;\n}\n#a {\n background: #FF0000;\n}\n#b {\n background: #FFFF00;\n}\n#c {\n background: #00FFFF;\n}\n.box{\n width:400px;\n height:140px;\n float: left; \n}\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/vSWmx/2\" rel=\"noreferrer\">http://jsfiddle.net/vSWmx/2</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T15:50:30.573",
"Id": "25973",
"Score": "0",
"body": "Hi Thanks for you help Larry, It's very very very great, I love it!! Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T09:03:44.997",
"Id": "26141",
"Score": "0",
"body": "do you have an idea to make it looping?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T15:22:37.897",
"Id": "26148",
"Score": "0",
"body": "@user1697962 It's looping becuase of this condition. `if( abc_container < firstval ){ firstval = 0; }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T15:37:34.010",
"Id": "26149",
"Score": "0",
"body": "@user1697962 I updated the animation so it only cycles once. Another call to `moveToNextSlide()` will start the cycle again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T02:43:55.260",
"Id": "26169",
"Score": "0",
"body": "I would have add \"do not use IDs for CSS\""
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T20:07:06.290",
"Id": "15963",
"ParentId": "15948",
"Score": "6"
}
},
{
"body": "<p>I agree with everything in <a href=\"https://codereview.stackexchange.com/a/15963/120114\">Larry's answer</a> and there is one other big point, which may be implied in the <strong>Final Code</strong>: indentation is crucial for readability. </p>\n\n<p>There isn't an official \"<em>correct</em>\" indentation amount but general conventions call for two or four spaces when starting a block. For example, the <a href=\"https://google.github.io/styleguide/jsguide.html\" rel=\"nofollow noreferrer\">Google JavaScript Style Guide</a> calls for 2 spaces:</p>\n\n<blockquote>\n <p>Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block.<sup><a href=\"https://google.github.io/styleguide/jsguide.html#formatting-block-indentation\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p>Meanwhile, Doug Crockford's <a href=\"https://crockford.com/javascript/code.html\" rel=\"nofollow noreferrer\"><em>Code Conventions for the JavaScript Programming Language</em></a> recommends 4 spaces.</p>\n\n<blockquote>\n <p>Every statement should begin aligned with the current indentation. The outermost level is at the left margin. The indentation increases by 4 spaces when the last token on the previous line is <code>{</code><em><code>left brace</code></em>, <code>[</code><em><code>left bracket</code></em>, <code>(</code><em><code>left paren</code></em>. The matching closing token will be the first token on a line, restoring the previous indentation.<sup><a href=\"https://crockford.com/javascript/code.html#whitespace\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n\n<p>The <a href=\"https://codereview.stackexchange.com/revisions/15948/1\">first version of your code</a> appears to have various levels of indentation:</p>\n\n<blockquote>\n<pre><code>var runCarousel, runTimer;\n firstval = 0;\n secondval = 0;\n\n function Carousel(){\n firstval += 10;\n document.getElementById('abc-container').style.left = \"-\" + firstval + \"px\";\n document.getElementById('asas').innerHTML = \"-\" + firstval;\n if(firstval == 400)\n {\n StopRun();\n StartTimer()\n return;\n }\n //...\n</code></pre>\n</blockquote>\n\n<p>To format this consistently, use a consistent indentation:</p>\n\n<pre><code>var runCarousel, runTimer;\nfirstval = 0;\nsecondval = 0;\n\nfunction Carousel(){\n firstval += 10;\n document.getElementById('abc-container').style.left = \"-\" + firstval + \"px\";\n document.getElementById('asas').innerHTML = \"-\" + firstval;\n if(firstval == 400)\n {\n StopRun();\n StartTimer()\n return;\n }\n</code></pre>\n\n<p>And the same also applies to the CSS.</p>\n\n<p><sup>1</sup><sub><a href=\"https://google.github.io/styleguide/jsguide.html#formatting-block-indentation\" rel=\"nofollow noreferrer\">https://google.github.io/styleguide/jsguide.html#formatting-block-indentation</a></sub>\n<sup>2</sup><sub><a href=\"https://crockford.com/javascript/code.html#whitespace\" rel=\"nofollow noreferrer\">https://crockford.com/javascript/code.html#whitespace</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-05T22:02:10.470",
"Id": "203211",
"ParentId": "15948",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-09-26T07:31:00.780",
"Id": "15948",
"Score": "6",
"Tags": [
"javascript",
"html",
"css",
"timer"
],
"Title": "Carousel image slideshow script"
}
|
15948
|
<p>Task: per host concurrency limits for web crawler (<code>map[string]Semaphore</code>).</p>
<p>I considered <code>chan struct{} (chan bool)</code> approach, but essentially it would not make code a lot easier because the main hurdle is to delete unused keys from map. And then semaphore takes constant memory - good property - as opposed to chan which grows with each "acquired limit".</p>
<p>I started with Semaphore using sync. Cond Wait/Signal (desired behavior of semaphore is well described in comments). Then I created <code>map[string]*Semaphore</code> with Mutex around all map operations and after semaphore is on hands, Acquire/Release it - that would block caller if needed but not block other access to map.</p>
<p>To remove unused semaphores from map I use separate counter that is stored in semaphore struct and modified only inside map lock. Its value sometimes differs from <code>semaphore.value</code>. When this counter goes to zero I know there are no goroutines that have pointer to semaphore from map except maybe one that is going to do final <code>Release()</code> now, so it's safe to delete key from map to preserve memory.</p>
<p>Essentially it works, test passes, but I would really appreciate any feedback on this approach.</p>
<p>Code link: <a href="https://gist.github.com/4130335" rel="noreferrer">https://gist.github.com/4130335</a></p>
<pre><code>// Package limitmap provides map of semaphores to limit concurrency against some string keys.
//
// Usage:
// limits := NewLimitMap()
// func process(url *url.URL, rch chan *http.Response) {
// // At most 2 concurrent requests to each host.
// limits.Acquire(url.Host, 2)
// defer limits.Release(url.Host)
// r, err := http.Get(url.String())
// rch <- r
// }
// for url := range urlChan {
// go process(url, rch)
// }
package limitmap
import (
"sync"
)
// Internal structure, may be changed.
// Requirements for this data structure:
// * Acquire() will not block until internal counter reaches set maximum number
// * Release() will decrement internal counter and wake up one goroutine blocked on Acquire().
// Calling Release() when internal counter is zero is programming error, panic.
type Semaphore struct {
// Number of Acquires - Releases. When this goes to zero, this structure is removed from map.
// Only updated inside LimitMap.lk lock.
refs int
max uint
value uint
wait sync.Cond
}
func NewSemaphore(max uint) *Semaphore {
return &Semaphore{
max: max,
wait: sync.Cond{L: new(sync.Mutex)},
}
}
func (s *Semaphore) Acquire() uint {
s.wait.L.Lock()
defer s.wait.L.Unlock()
for i := 0; ; i++ {
if uint(s.value)+1 <= s.max {
s.value++
return s.value
}
s.wait.Wait()
}
panic("Unexpected branch")
}
func (s *Semaphore) Release() (result uint) {
s.wait.L.Lock()
defer s.wait.L.Unlock()
s.value--
if s.value < 0 {
panic("Semaphore Release without Acquire")
}
s.wait.Signal()
return
}
type LimitMap struct {
lk sync.Mutex
limits map[string]*Semaphore
wg sync.WaitGroup
}
func NewLimitMap() *LimitMap {
return &LimitMap{
limits: make(map[string]*Semaphore),
}
}
func (m *LimitMap) Acquire(key string, max uint) {
m.lk.Lock()
l, ok := m.limits[key]
if !ok {
l = NewSemaphore(max)
m.limits[key] = l
}
l.refs++
m.lk.Unlock()
m.wg.Add(1)
if x := l.Acquire(); x < 0 || x > l.max {
panic("oia")
}
}
func (m *LimitMap) Release(key string) {
m.lk.Lock()
l, ok := m.limits[key]
if !ok {
panic("LimitMap: key not in map. Possible reason: Release without Acquire.")
}
l.refs--
if l.refs < 0 {
panic("LimitMap internal error: refs < 0.")
}
if l.refs == 0 {
delete(m.limits, key)
}
m.lk.Unlock()
if x := l.Release(); x < 0 || x > l.max {
panic("oir")
}
m.wg.Done()
}
// Wait until all released.
func (m *LimitMap) Wait() {
m.wg.Wait()
}
func (m *LimitMap) Size() (keys int, total int) {
m.lk.Lock()
keys = len(m.limits)
for _, l := range m.limits {
total += int(l.value)
}
m.lk.Unlock()
return
}
</code></pre>
|
[] |
[
{
"body": "<p>For my initial implementation, I would personally apply the common semaphore pattern using buffered channels for controlling the number of running goroutines. The simplest application of which looks like the code below (also available in this <a href=\"https://gist.github.com/theckman/283e6fde3ba6be0e9f6b965ca8f43623\" rel=\"nofollow noreferrer\">gist</a>):</p>\n\n<pre><code>func doWork(s string, ch <-chan struct{}, wg *sync.WaitGroup) { \n defer func() { \n <-ch // free up space in the semaphore \n wg.Done() // tell the WaitGroup we're finished \n }() \n\n fmt.Println(s) \n} \n\nfunc execute(work []string) { \n wg := &sync.WaitGroup{} \n sema := make(chan struct{}, 10) // concurrency limit of 10 \n\n for _, url := range work { \n // if there are 10 items in flight, channel is full / will block \n // unblocks when a worker finishes \n sema <- struct{}{} \n\n wg.Add(1) \n go doWork(url, sema) \n } \n\n // close the channel as nothing else should write \n close(sema) \n\n // wait for all goroutines to finish \n wg.Wait() \n} \n</code></pre>\n\n<p>If you enhanced this example a bit to use one channel per map key, where you then pass the channel in to the worker function to be read from, I think it'll work for you.</p>\n\n<p>If you're curious why I decided to use a <code>struct{}</code> type for the channel, Dave Cheney has a good post explaining it <a href=\"https://dave.cheney.net/2014/03/25/the-empty-struct\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-17T15:44:07.827",
"Id": "192302",
"ParentId": "15954",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T11:05:54.077",
"Id": "15954",
"Score": "15",
"Tags": [
"multithreading",
"locking",
"synchronization",
"go"
],
"Title": "Concurrency limit map in Go"
}
|
15954
|
<p><a href="http://jsfiddle.net/hrishikeshp19/VyDsu/21/" rel="nofollow">http://jsfiddle.net/hrishikeshp19/VyDsu/21/</a></p>
<p>Following is my HTML body:</p>
<pre><code><div id="header">
<div id="logo">
</div>
<div id="headercontent1">
</div>
<div id="headercontent2">
</div>
</div>
<div id="buttons-container">
</div>
<div id="panels-container">
<div id="panel1"></div>
<div id="panel2"></div>
<div id="panel3"></div>
</div>
<div id="table-container">
<table id="my-table">
<thead id="my-table-head">
<tr>
<th>
My Table
</th>
<th>
Column 1
</th>
<th>
Column 2
</th>
</tr>
</thead>
<tbody id="my-table-body">
<tr class="tr-odd">
<td>Row 1</td>
<td>Row 1 Column 1</td>
<td>Row 1 Column 2</td>
</tr>
<tr>
<td>Row 2</td>
<td>Row 2 Column 1</td>
<td>Row 2 Column 2</td>
</tr>
<tr class="tr-odd">
<td>Row 3</td>
<td>Row 3 Column 1</td>
<td>Row 3 Column 2</td>
</tr>
</tbody>
</table>
</div>
<div id="gallery">
</div>
β
</code></pre>
<p>following is my css:</p>
<pre><code>body{
position: relative;
}
#header{
height: 160px;
background-color:black;
width: 960px;
position: relative;
}#logo{
position: absolute;
width:300px;
height:140px;
left:40px;
background-color: grey;
top: 10px;
}
#headercontent2, #headercontent1{
position: absolute;
width:140px;
height:140px;
right:40px;
background-color: grey;
top: 10px;
}
#headercontent1{right:200px;}
#buttons-container{
position:absolute;
top:180px;
left:0px;
height:60px;
width:960px;
background-color:black;
}
#panels-container{
position:absolute;
top:260px;
left:0px;
}
#panel1,#panel2,#panel3{
position:absolute;
left:0px;
height:300px;
width:300px;
background-color:cyan;
}
#panel2{
left:320px;
}
#panel3{
left:640px;
}
#table-container{
position:absolute;
top:580px;
left:0px;
width:960px;
background-color:white;
}
#my-table{
width:960px;
border-color: black;
border-width: 1px;
border-style: solid;
}
#my-table-head th{
background-color: grey;
height:50px;
text-align:center;
width: 320px;
}
#my-table-body tr{
text-align:center;
background-color:grey;
height: 50px;
}
#my-table-body td{
text-align:center;
border-color: black;
border-width: 1px;
border-style: solid;
width: 320px;
}
#my-table .tr-odd{
background-color:white;
}
#gallery{
position:absolute;
top:800px;
left:0px;
width: 960px;
height:400px;
background-color:blue;
overflow:hidden;
}
β
</code></pre>
<p>and the javascript:</p>
<pre><code>var url = "http://numberonelarge.com/tapjoy/jsonp.php?callback=yourcallbackfunction";
var images_ready = function(images){
//sort the images, sorting based on height of images, this is called as greedy strategy
for(var i=0,len=images.length;i<len;i++){
for(var j=i+1;j<len;j++){
if(images[i].height<images[j].height){
var temp = images[j];
images[j]=images[i];
images[i]=temp;
}
}
}
images.reverse();//arrange in ascending order
//assumption 1: all images of constant width
var img_width = 160;
var row_limit = $("#gallery").width()/img_width;
for(var i=0,len=images.length;i<len;i++){
$(images[i]).css({"left":img_width*(i % row_limit)});
if(i-row_limit>=0){
$(images[i]).css({"top":images[i-row_limit].height+parseInt($(images[i-row_limit]).css("top"))});
}
else{
$(images[i]).css({"top":0});
}
$("#gallery").append(images[i]);
}
}
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
var images = [ ];
for (var i=0,len=json.length;i<len;i++){
var img = $('<img />').attr({ 'id':'img_'+i, 'src': json[i]}).css({"position":"absolute"}).load(function(){
images.push(this);
if(images.length == len){
images_ready(images);
}
});
}
},
error: function(e) {
console.log(e.message);
}
});
</code></pre>
<p>Above is the fiddle I want to make cleaner.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T15:57:33.527",
"Id": "25941",
"Score": "1",
"body": "We ask that you post your code in your question. This makes it easier to look at, and links like you have posted sometimes expire, so if somebody is looking at this in the future they code might not be there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T15:57:51.173",
"Id": "25942",
"Score": "1",
"body": "At least one user that has understood of this site works ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T10:59:27.080",
"Id": "25966",
"Score": "0",
"body": "Cleaner in what way? Better to read? Or using better techniques? My first suggestion would be to use less absolute positioning and fixed pixel sizes."
}
] |
[
{
"body": "<p>The code you posted doesn't have must meaning to me and it's hard to follow.</p>\n<p>Here are a few guidelines to follow to improve your code quality.</p>\n<h2>1) Format your code.</h2>\n<p>Formatting makes your code easier to read and maintain.</p>\n<h2>2) Add some comments</h2>\n<p>It looks like you posted a basic template.\nIt would be nice if you added a comment about the overall purpose of each section.</p>\n<h2>3) Try out a css framework.</h2>\n<p>Creating a layout that is consistent among various browsers is challenging. CSS frameworks were created to solve just that problem.\nHere's a popular framework called <a href=\"http://www.blueprintcss.org/\" rel=\"nofollow noreferrer\">blueprint</a>.</p>\n<h2>4) Learn how to create meaningful names.</h2>\n<p>What's the purpose of this table?</p>\n<pre><code><table id="my-table">\n</code></pre>\n<p>Can you guess what this table is for?</p>\n<pre><code><table id="yearlySalesTable">\n</code></pre>\n<p>You should read this question over at stackoverflow.com called "<a href=\"https://stackoverflow.com/questions/203618/how-to-name-variables\">How to name variables</a>"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T04:46:58.747",
"Id": "15968",
"ParentId": "15957",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15968",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T15:42:45.520",
"Id": "15957",
"Score": "2",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "make the fiddle cleaner"
}
|
15957
|
<p>I want to generate a random alphanumeric string in ruby, as succinctly and efficiently as possible. The following solution works, but is obviously not very efficient. </p>
<p>Please review the following code, bearing in mind that I am trying to keep it as succinct and readable as possible while improving efficiency. <em>Be sure to include a detailed explanation in your answer.</em></p>
<pre><code>([nil]*8).map { ((48..57).to_a+(65..90).to_a+(97..122).to_a).sample.chr }.join
</code></pre>
|
[] |
[
{
"body": "<p>I think this is both declarative and concise:</p>\n\n<pre><code>8.times.map { [*'0'..'9', *'a'..'z', *'A'..'Z'].sample }.join\n</code></pre>\n\n<p>It works because:</p>\n\n<ol>\n<li>You can call <code>map</code> on <code>times</code> since >= 1.8.7 made it return an enumerator when called without block (a lot of methods do this now: <code>each</code>, <code>each_cons</code>, <code>each_slice</code>, ...). </li>\n<li>You can build a range with objects of any class as long as they support <code><=></code> and <code>succ</code>. </li>\n<li>You can explode any enumerable. If you don't like the exploding syntax, use <code>['0'..'9', 'a'..'z', 'A'..'Z'].flat_map(&:to_a)</code>.</li>\n</ol>\n\n<p>The only problem with this being a one-liner (as requested), it's that the array is re-created on every iteration. It would be better to assign it once to a variable outside the block:</p>\n\n<pre><code>cs = [*'0'..'9', *'a'..'z', *'A'..'Z']\n8.times.map { cs.sample }.join\n</code></pre>\n\n<p>Alternatevely, you can write:</p>\n\n<pre><code>cs = [*'0'..'9', *'a'..'z', *'A'..'Z']\nArray.new(8) { cs.sample }.join\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T23:40:02.197",
"Id": "25952",
"Score": "0",
"body": "ah, didn't know you could call `map` on `times` or do ranges of characters, or explode ranges! nice one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-01T02:50:40.950",
"Id": "97836",
"Score": "0",
"body": "I don't think anyone should use `n.times.map{` -- use `Array.new(n){` instead."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T21:43:17.700",
"Id": "15965",
"ParentId": "15958",
"Score": "7"
}
},
{
"body": "<p>You could use</p>\n<pre><code>Array.new(8){[*'0'..'9', *'a'..'z', *'A'..'Z'].sample}.join\n</code></pre>\n<p>From the documentation for Array:</p>\n<blockquote>\n<p>new(size=0, obj=nil) new(array) <strong>new(size) {|index| block }</strong></p>\n<p>Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). <strong>In the last form, an array of the given size is created. Each element in this array is calculated by passing the elementβs index to the given block and storing the return value.</strong></p>\n</blockquote>\n<p>Perhaps it is better to create the array with the valid characters once in advance:</p>\n<pre><code>range = [*'0'..'9', *'a'..'z', *'A'..'Z']\nArray.new(8){range.sample}.join\n</code></pre>\n<hr />\n<p>I made a Benchmark for the solutions.</p>\n<pre><code>require 'benchmark'\nN = 10_000 #Number of Test loops\n\nBenchmark.bmbm(10) {|b|\n \n b.report('Nat' ) { N.times { ([nil]*8).map { ((48..57).to_a+(65..90).to_a+(97..122).to_a).sample.chr }.join } }\n b.report('tokland') { N.times { 8.times.map { [*'0'..'9', *'a'..'z', *'A'..'Z'].sample }.join } }\n b.report('knut' ) { N.times { Array.new(8){[*'0'..'9', *'a'..'z', *'A'..'Z'].sample}.join } }\n b.report('Natinit') { \n range = ((48..57).to_a+(65..90).to_a+(97..122).to_a)\n N.times { ([nil]*8).map { range.sample.chr }.join }\n }\n b.report('knutinit') { \n range = ((48..57).to_a+(65..90).to_a+(97..122).to_a)\n N.times { Array.new(8){range.sample}.join }\n }\n\n} #Benchmark\n</code></pre>\n<p>The result:</p>\n<pre><code>Rehearsal ---------------------------------------------\nNat 0.765000 0.000000 0.765000 ( 0.765625)\ntokland 2.172000 0.000000 2.172000 ( 2.171875)\nknut 1.953000 0.000000 1.953000 ( 1.984375)\nNatinit 0.063000 0.000000 0.063000 ( 0.062500)\nknutinit 0.078000 0.000000 0.078000 ( 0.078125)\n------------------------------------ total: 5.031000sec\n\n user system total real\nNat 0.781000 0.000000 0.781000 ( 0.781250)\ntokland 1.953000 0.000000 1.953000 ( 1.968750)\nknut 1.922000 0.000000 1.922000 ( 1.921875)\nNatinit 0.063000 0.000000 0.063000 ( 0.062500)\nknutinit 0.078000 0.000000 0.078000 ( 0.078125)\n</code></pre>\n<p>@Nat: Gratulation, your version is the fastest ;)</p>\n<p>To analyze the fastest way to build the <code>range</code> I used the following benchmark:</p>\n<pre><code>Benchmark.bmbm(10) {|b|\n \n b.report('Natinit') { \n N.times { ((48..57).to_a+(65..90).to_a+(97..122).to_a) }\n }\n b.report('knutinit') { \n N.times { [*'0'..'9', *'a'..'z', *'A'..'Z'] }\n }\n} #Benchmark\n</code></pre>\n<p>Result:</p>\n<pre><code>Rehearsal ---------------------------------------------\nNatinit 0.093000 0.000000 0.093000 ( 0.093750)\nknutinit 0.250000 0.000000 0.250000 ( 0.250000)\n------------------------------------ total: 0.343000sec\n\n user system total real\nNatinit 0.094000 0.000000 0.094000 ( 0.093750)\nknutinit 0.219000 0.000000 0.219000 ( 0.218750)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T10:35:23.033",
"Id": "26010",
"Score": "0",
"body": "That's not what I was expecting.\n\nCombining our code into `range = ('0'..'9').to_a+('a'..'z').to_a+('A'..'Z').to_a; N.times { Array.new(8){ range.sample }.join }` makes for even better performance.\n\nI guess the main difference is that concatenation is more efficiency that exploding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T11:58:31.767",
"Id": "26014",
"Score": "1",
"body": "it's always interesting to see benchmarks, but in this case, unless you need to generate millions and millions of strings, I don't see the point. Go for the most clear solution to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T09:59:44.240",
"Id": "525389",
"Score": "0",
"body": "Using `pack` to create the final string from code points is 30% faster converting each code point to a character first and joining that. `range = ((48..57).to_a+(65..90).to_a+(97..122).to_a); Array.new(8) { range.sample }.pack(\"U*\")`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T20:47:05.087",
"Id": "15997",
"ParentId": "15958",
"Score": "10"
}
},
{
"body": "<p>I've reviewed many means of random string generation of many, but this form is always the one I come back to:</p>\n\n<pre><code>rand(36**7...36**8).to_s(36)\n</code></pre>\n\n<p>It's a bit rougher to the more pleasing alternative <code>rand(36**8).to_s(36)</code>, but it's also more accurate.</p>\n\n<p>I also don't really care for Ruby's benchmarking class (read: I haven't bothered to learn how to utilize it), so I instead just timed how long using your original method takes to generate 100000 iterations versus the code above:</p>\n\n<pre><code>time echo \"100000.times {puts ([nil]*8).map { ((48..57).to_a+(65..90).to_a+(97..122).to_a).sample.chr }.join}\" | ruby\n# ruby 8.37s user 0.55s system 99% cpu 8.926 total\n\ntime echo \"100000.times {puts rand(36**7..(36**8)-1).to_s(36)}\" | ruby\n# ruby 0.59s user 0.34s system 97% cpu 0.949 total\n</code></pre>\n\n<p>In other words, while your original method occurs at a rate of 11,203 iterations per second. The code above occurs at a rate of 105,400 iterations per second. I'm sure this will vary from computer to computer, OS to OS, but anyone is certainly free to try this themselves.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T13:02:07.253",
"Id": "26196",
"Score": "0",
"body": "ooh, thats clever, took me a minute to get how it works though. Can it be made to include capital letters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T22:22:37.170",
"Id": "26231",
"Score": "1",
"body": "nice! If you use the \"...\" vs. the \"..\" in the range can you remove the -1? :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:40:45.110",
"Id": "26259",
"Score": "0",
"body": "@engineerDave Good call! Updated the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:47:37.413",
"Id": "26260",
"Score": "0",
"body": "@Nat I don't believe capital letters can be used, unfortunately."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T22:27:29.037",
"Id": "16089",
"ParentId": "15958",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15997",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T16:52:28.520",
"Id": "15958",
"Score": "10",
"Tags": [
"optimization",
"ruby",
"random"
],
"Title": "Generating a random alphanumeric string succinctly and efficiently"
}
|
15958
|
<p>In my never-ending quest to improve my coding skills I am requesting peer input on the following code logic. I am asking because I'm -NOT- an expert, but would like to be one day. Source material and recommended read is greatly welcome (no, do NOT point me to the PHP manual) especially for code formatting, unit testing, etc.</p>
<p>Notes:</p>
<ol>
<li><p>Layer separation is not important; i.e.: presentation and database connection logic was not abstracted to different classes. This is an admin usage only script. Sporadic usage, saw once a month.</p></li>
<li><p>I have just learned about dependence injection; was attempting to use it properly.</p></li>
<li><p>PHP version is 5.3.3. so fancy stuff like <code>mysqli::query_all(ASSOC)</code> is not an option.</p></li>
</ol>
<p>Please let me know, in a constructive way please, how I could improve my skill at this trade.</p>
<pre><code><?php
//script settings. Prevents timeouts
set_time_limit(0);
ignore_user_abort(1);
//constants
const DEBUG = false;
const EXECU = true;
/**
*@Comment: Create all the reused and repeated methods.
*/
class DependencyContainer
{
/**
* @Param: $location string [required], $user string [required], $password string [optional], $database strong [required]
* @Return: $mysqliConn object
*/
public static function dbConn( $location = null, $user = null, $password = null, $database = null )
{
//Inbound var check
if($location == null || $user == null || $database == null)
{
//public function status($title = null, $response = null, $die = 0)
$this->status("createDBObject missing params", "ERROR", 1);
}
//Connect me to the SugarCRM database
$mysqliConn = null;
try
{
$mysqliConn = new mysqli($location, $user, $password, $database);
} catch (Exception $e) {
$this->status('Could not create DB object', $e, 1);
}
//if connection fails
if ( $mysqliConn->connect_error )
{
DependencyContainer::status( 'Could not connect to host', $mysqliConn->connect_error, 1 );
}else{
return $mysqliConn;
}
}
/**
* @Comment: Debug function call./
* @Param: title string, response string, die int
*/
public static function status( $title = null, $response = null, $die = 0 )
{
//no debug for you!
if( DEBUG == false )
return;
$isBrwsr = true;
//determine if we are in a browser or CLI
//spefcial thanks to: http://www.codediesel.com/php/quick-way-to-determine-if-php-is-running-at-the-command-line/
if(php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
$isBrwsr = false;
}
//easy full stop AND if debug is off and an error occures.
if($title == null)
$this->dieRequest("An error has occured. Please contact your administrator.", 1);
if($isBrwsr)
echo("<pre><div color='black'>");
echo "\n" . $title.": ";
/**
* @Comment: should make this check for true or 1 as well to be a positive response.
*/
if ($response != null && is_numeric($response) == false)
{
if($isBrwsr)
echo("<div style='color:red;font-weight:bolder;display:inline;'>");
print_r($response);
if($isBrwsr)
echo("</div>");
}
elseif ($response == null)
{
if($isBrwsr)
echo("<div style='color:green;display:inline;'>");
print_r("GOOD or null");
if($isBrwsr)
echo("</div>");
}
elseif (is_numeric($response) == true)
{
if($isBrwsr)
echo("<div style='color:green;display:inline;'>");
print_r($response);
if($isBrwsr)
echo("</div>");
}
if($isBrwsr)
echo("</div></pre>");
if($die != 0)
{
self::dieRequest();
}
}
/**
* @Comment: Le-killer functions! No srsly, its a killer!
* @Param: callReferance, showDie int
*/
public static function dieRequest( $callReferance = null, $showDie = 0 )
{
if($showDie != 0)
echo("Die requested by: " . $callReferance);
die;
}
/**
* @Commentr UUIDv3 generator
*/
public static function UUIDmaker()
{
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
// 16 bits for "time_mid"
mt_rand( 0, 0xffff ),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand( 0, 0x0fff ) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand( 0, 0x3fff ) | 0x8000,
// 48 bits for "node"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
}
class Accounts
{
//class properties
private $mysqliConn;
/**
*@Comment: create the object. All aparams are as an array
*@Param $dbDependency object [required]
*/
function __construct($dbDependency = null)
{
if( $dbDependency != null )
{
$this->mysqliConn = $dbDependency;
}
}
/**
*@Comment Get all Accounts id, phone_office, phone_alternate
*@Param n/a
*@Return $dataArray
*/
public function getAccountsData( $columns = null, $limit = null )
{
if( $columns == null )
{
//for now all we check against is the phone_office data
//$columns = "`phone_office`, `phone_alternate`";
$columns = "`phone_office`";
}
//create SQL query
$stmt = "
SELECT ". $columns ."
FROM `accounts`
WHERE 1
". $limit . ";"
;
//exec query
$query = $this->mysqliConn->query($stmt);
//coallate results
$getAccountsData = array();
while ($row = $query->fetch_assoc())
{
foreach( $row as $rowKey=>$rowValue )
{
if( stristr( $rowKey, "phone" ) && $rowValue != "" )
{
$getAccountsData[] = $rowValue;
}
}
}
//DependencyContainer::status('$getAccountsData', $getAccountsData);
return $getAccountsData;
}
}
class Leads
{
//class properties
private $mysqliConn;
/**
*@Comment: create the object. All aparams are as an array
*@Param $dbDependency object [required]
*/
function __construct( $dbDependency = null )
{
if( $dbDependency != null )
{
$this->mysqliConn = $dbDependency;
}
}
/**
*@Comment Get all Accounts id, phone_office, phone_alternate
*@Param n/a
*@Return $dataArray
*/
public function getLeadsData( $columns = null, $limit = null )
{
if( $columns == null )
{
$columns = "`phone_home`, `phone_mobile`, `phone_work`, `phone_other`, `phone_fax`, `assistant_phone`";
}
//create SQL query
$stmt = "
SELECT ". $columns."
FROM `leads`
WHERE 1
". $limit . ";"
;
//exec query
$query = $this->mysqliConn->query($stmt);
//coallate results
$getLeadsData = array();
while ($row = $query->fetch_assoc())
{
foreach( $row as $rowKey=>$rowValue )
{
if( stristr( $rowKey, "phone" ) && $rowValue != "" )
{
$getLeadsData[] = $rowValue;
}
}
}
//DependencyContainer::status('$getLeadsData', $getLeadsData);
return $getLeadsData;
}
/**
*@Comment Create a lead based on an array of phone numbers
*@Param $data array [required]
*/
//this is terribad, but works for now
public function createLead( $data = null )
{
DependencyContainer::status('Accounts to create leads for', count( $data ) );
$insertStmt = "";
$stmt = "";
$counter = 1;
foreach( $data as $dataKey=>$dataValue )
{
DependencyContainer::status('$counter', $counter);
//SELECT from Accounts
//Get account associated with the phone_office number
$stmt = "SELECT `id`, `phone_office`, `name`, `assigned_user_id` FROM `accounts` WHERE `phone_office` = '". $dataValue . "';";
//exec query
$row = $this->mysqliConn->query($stmt);
$relatedAccountData = $row->fetch_assoc();
//INSERT into LEAD
//query statment
$insertStmt .= "INSERT
INTO `leads`
(`id`, `assigned_user_id`, `phone_work`, `status`, `account_name`)
VALUES
('". DependencyContainer::UUIDmaker() ."', '". $relatedAccountData['assigned_user_id'] ."', '". $relatedAccountData['phone_office'] ."', 'Converted', '". $relatedAccountData['name'] ."');
";
$relatedAccountData = "";
//abrstract to method
//error catching
try
{
DependencyContainer::status('$insertStmt', $insertStmt);
//testing
if( EXECU == true && $this->mysqliConn->query($insertStmt) )
{
DependencyContainer::status('SQL INSERT executed');
}elseif( EXECU == false ){
DependencyContainer::status('-TEST- SQL INSERT executed.');
}else{
DependencyContainer::status('SQL INSERT DID NOT execute.', $this->mysqliConn->error);
}
//caught
} catch (Exception $e) {
//if things go south
DependencyContainer::status('Exception', $e, 1);
}
$insertStmt = "";
$counter++;
}
return true;
}
}
class Comparison
{
public static function comparData( $arrayFrom = null, $arrayAgainst = null)
{
//Logic from merlyn dot tgz at gmail dot com 15-Mar-2012 10:08 @ http://php.net/manual/en/function.array-diff.php
foreach( $arrayFrom as $key => $value )
{
//check for number matches
if( is_numeric( $value ) )
{
if( in_array( $value, $arrayAgainst ) )
{
unset( $arrayFrom[$key] );
}
//remove non-numeric keys and values
}else{
unset( $arrayFrom[$key] );
}
}
//From array minus Against array
//exp: 9169286000
DependencyContainer::status('$arrayFrom after removals', $arrayFrom, 1);
return $arrayFrom;
}
}
//auto password :)
$pw = "";
if( isset($_SERVER['HTTP_HOST'] ) && $_SERVER['HTTP_HOST'] == "localhost" )
{
$pw = "";
}else{
$pw = "***passwordHere***";
}
$dbDependency = DependencyContainer::dbConn("localhost", "root", $pw, "sugarcrm");
$accountsClass = new Accounts($dbDependency);
$accountNumbers = $accountsClass->getAccountsData();
$leadsClass = new Leads($dbDependency);
$leadNumbers = $leadsClass->getLeadsData();
$results = Comparison::comparData( $accountNumbers, $leadNumbers );
$leadsClass->createLead( $results );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T16:13:11.993",
"Id": "25974",
"Score": "2",
"body": "Its not, but its also unnecessary. All this does is bring it back to the top of the general list. It is already at the top of the PHP list. Just be patient. This community is a bit slower than the other SE communities. That being said, sorry I didn't get around to my review sooner, my Raspberry Pi arrived last night and I was really excited to start playing with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T16:56:43.777",
"Id": "25977",
"Score": "0",
"body": "General Review and First DI Attempt would be a good one"
}
] |
[
{
"body": "<p>Well, first suggestion, don't use <code>set_time_limit()</code>. Try and refactor your code so that it is unnecessary, unless this is a CRON job or something and is running in the background. If you access it via a webpage then even if you are expecting it to take a while, it could be confusing. For instance, if you call this script via AJAX, then you will not see that it is loading, it will just sit there appearing to be doing nothing. I ran into a similar problem with a couple of my AJAX scripts recently and had to figure out how to separate the results so it didn't take as long. Additionally, be careful with that <code>ignore_user_abort()</code> function as it will require you to have to restart your server should you ever accidentally trigger an infinite loop.</p>\n\n<p>You got your constants confused. <code>define()</code> is used to create a constant outside of a class. <code>const</code> is used to define a constant inside of a class.</p>\n\n<p>No need to explicitly declare <code>@Comment</code>, just start typing. Your IDE should know that its a doccomment and act accordingly. <code>@Comment</code> isn't even a PHPDoc tag. See <a href=\"http://www.phpdoc.org/docs/latest/index.html\" rel=\"nofollow noreferrer\">this link</a> for a list of available tags and their uses. Its also important to note that if you give everything a decently descriptive name, doccomments like this are unnecessary. They should really only be used to point out the caveats and anything you think wont be obvious just by looking at the code.</p>\n\n<p>When using <code>@param</code> you should only give one parameter. Declare new <code>@param</code>s for each new parameter, otherwise you won't get the proper highlighting. Also, you have your parameter type and name switched.</p>\n\n<pre><code>/**\n * @param String $location etc...\n * @param String $user etc...\n etc...\n */\n</code></pre>\n\n<p>What is the point of all of these static methods? This completely defies the point of even having a class. You mentioned suggested reading, here's a <a href=\"http://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">wikipedia entry for OOP</a>. I would suggest reading the whole thing, but that first paragraph is the important one here. In it it points out the key concepts of OOP. I would also suggest following the links to each of those concepts for a better understanding. Once you have done this, come back and look at your code and ask yourself if you are following most of these concepts. You don't have to follow every one of them, but if you aren't at least following most, then you have not justified OOP. In short, you probably wont need static very much at all. I've been doing this for quite a while and everything I have started to do with static I ended up scraping or turning into a helper function. Speaking of which, don't be shy about using helper functions either. If it doesn't fit in a class don't try and force it, helper functions are still useful, even in an OOP context.</p>\n\n<p>You already have doccomments, why the inner comments? If you really need to document something about the method, do so in the doccomments at the beginning. That's what they are there for. Leave the inside of your methods comment free so that they don't get cluttered. Believe it or not, this really helps when trying to read the code, you wouldn't believe the difference it would make, especially if you auto-collapse doccomments in your IDE.</p>\n\n<p>You should either use absolute equality <code>===</code> comparisons when checking for NULL, or the <code>is_null()</code> function. Personally, I prefer the later approach, but there is no real difference between the two, <a href=\"https://stackoverflow.com/questions/4662588/whats-the-difference-between-is-nullvar-and-var-null\">see this post for more</a>. Unless, of course, you are not just checking for NULL, but for any FALSE value, in which case you can just do the following.</p>\n\n<pre><code>if( ! $location || ! $user || ! $database ) {\n</code></pre>\n\n<p>I'm actually kind of surprised this works at all... <code>$this</code> is not static and therefore can not be called in a static context. Use <code>self::</code> instead. See <a href=\"http://www.brainbell.com/tutorials/php/Static_Methods.html\" rel=\"nofollow noreferrer\">this tutorial</a> for details. I see you did this, or something very similar towards the end of the method, but the non-static implementation is still prevalent in the rest of your code and is wrong. Of course, removing the static keyword would be ideal and would make this unnecessary.</p>\n\n<p>First, before going on, let me just say that I am seeing quite a few inconsistencies in this code: spaces between parenthesis, no spaces; switching back and forth between single and double quotes; <code>$this-></code> vs. <code>DependencyContainer::</code> or <code>self::</code>, as I mentioned above. This leads me to believe you either copy-pasted this together, have multiple people working on it, or have changed your style and not retroactively gone back to change everything. If one of the last two, strive to at least make each file consistent. If its too much work to go back and change everything, adjust your current style to fit. Or if you are working in a group, have a meeting and discuss code style and make everyone adhere to it. If its the first one, don't ever do that. Always type out any code you borrow. Doing so may help you to better understand it, or at the very least will ensure that its not obvious you stole it :)</p>\n\n<p>But, the most heinous of all, IMO, are these braceless statements, especially when you use braced single statements as well. PHP inherently requires braces, otherwise you wouldn't have to add them after extending a statement past the first line. As such, I don't think braceless statements should be allowed at all. If they ever change the code so that those braces are entirely optional, then I will retract this statement, but in the meantime, I think this is the wrong way and I am going to stand by that. But either way, again, be consistent.</p>\n\n<pre><code>if( DEBUG == false )\n return;\n//OR\nif( DEBUG == FALSE ) {\n return;\n}\n</code></pre>\n\n<p>I mentioned this before, but it was in another context, so I'll repeat it here for clarity. If you are not using an absolute equality comparison, then you don't have to explicitly compare the variable to a boolean. Just treat it as a boolean, it does the same thing.</p>\n\n<pre><code>if( ! DEBUG ) {\n</code></pre>\n\n<p>Here's another inconsistency. Your echo statements do not have to have parenthesis, but you should pick one method and stick with it. I also mentioned something about quotes above. To elaborate, use single quotes when the string you are writing does not have any escape sequences, or if you need to use double quotes. Use double quotes for the opposite. And you can use your preference if the type isn't important, though I will say that single quotes are very slightly faster because PHP knows it doesn't need to escape anything. Additionally, you should use double quotes for your HTML attributes, so for those HTML strings I would use single quotes. If this string were to be loaded into DOM or treated as XML, then this would throw some errors. And finally, I mentioned using double quotes for escape sequences above, this also includes variables. The following echo statements are a little better, though the last one could be argued. Some don't like using variables in string sequences and instead concatenate it, up to you, I just find this cleaner.</p>\n\n<pre><code>echo '<pre><div color=\"black\">';\necho \"\\n$title: \";\n</code></pre>\n\n<p>The following is just begging to be refactored. First, it violates \"Don't Repeat Yourself\" (DRY) Principle, second, you don't want to have to check the same statement more than once. You can combine these by checking <code>$isBrwsr</code> at the very beginning and setting two variables, initially empty strings, maybe <code>$header</code> and <code>$footer</code> with a generic opening and closing div tags respectively. Then, wrapping these variables, whether empty or not, around the context variable will accomplish the same thing. If you do it right, you can use a placeholder in the <code>$header</code> so that you can then use the context, set up by your if/else statements, to set the div's class or id with a <code>sprintf()</code> function or <code>substr_replace()</code>. Then, using a stylesheet, you can save those individual styles and only call the one you need via class or id. Additionally, <code>print_r()</code>, unless using an array or object here, is unnecessary. <code>echo</code> is just fine, and <code>var_dump()</code> is more informative if just being used for debugging. I would show you how to do this, but I believe the above explanation should be adequate. If you need help, show me what you have tried and I'll take a look.</p>\n\n<pre><code>if($isBrwsr)\n echo(\"<div style='color:red;font-weight:bolder;display:inline;'>\");\n\nprint_r($response);\n\nif($isBrwsr)\n echo(\"</div>\");\n</code></pre>\n\n<p>I'm not going to dissect that <code>UUIDmaker()</code>, because I'm not sure exactly what you are doing here or why, but I'm fairly certain this could be refactored somehow.</p>\n\n<p>I kind of started skimming here. A lot of the issues I was finding were repeats, and there is a lot to look over. So take what I said above, and apply it to the rest. Something I didn't go over in the above review was Single Responsibility Principle, but you could stand to look into that as well. Here's a <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">good starting place</a>, and don't be shy about reading the related material either. One of those should be related to DRY, which I mentioned above.</p>\n\n<p>I'm not going to go too in depth for the Dependency Injection as there is already quite a bit here and this would only add a considerable bit more, but here are a few things to keep in mind. Dependency Injection is typically not optional if being implemented, so if it is null it either creates a new instance or fails. Dependency Injection requires objects of a specific type, so declaring that type by type-hinting your parameters will help quite a bit. And most importantly of all, Dependency Injection should only be done in a class constructor. Dependencies should not be passed in at any other point.</p>\n\n<pre><code>public function __construct( DependencyContainer $dbDependency ) {\n</code></pre>\n\n<p>Additionally, as shown above, always declare your method's or property's access type. By default it is public, but I have heard rumors of this being deprecated in the future. Don't rely on the language defaults to save you. Besides being specific about this kind of thing is important. Being in the habit of neglecting this could lead to mistakes, such as forgetting to make a method or property private, for example, a password.</p>\n\n<p>As I said, I'm skimming at this point, but this is the last thing that jumped out at me. If you are not going to use the key, you do not need to define it in your foreach statements.</p>\n\n<pre><code>foreach( $data as $dataKey=>$dataValue ) {\n//remove the key\nforeach( $data as $dataValue ) {\n</code></pre>\n\n<p>I'm sure there are a few things I missed, but this should definitely help you get started.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T16:11:36.490",
"Id": "15985",
"ParentId": "15960",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15985",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T19:08:38.373",
"Id": "15960",
"Score": "4",
"Tags": [
"php",
"performance",
"php5"
],
"Title": "Comparing multiple fields from two tables, looking for matches, updating 2nd table"
}
|
15960
|
<h2>Context</h2>
<p>As an exercise for myself (I'm learning clojure). I wanted to implement the <code>Depth-first search</code> algorithm.</p>
<h2>How I did it</h2>
<p>Using recursion</p>
<pre class="lang-lisp prettyprint-override"><code>(def graph
{:s {:a 3 :d 4}
:a {:s 3 :d 5 :b 4}
:b {:a 4 :e 5 :c 4}
:c {:b 4}
:d {:s 4 :a 5 :e 2}
:e {:d 2 :b 5 :f 4}
:f {:e 4 :g 1}})
(def stack [[:s]])
(def goal :g)
(defn cost [Graph start goal]
(goal (start Graph)))
(defn hasloop? [path]
(not (= (count path) (count (set path)))))
(defn atgoal? [path]
(= goal (last path)))
(defn solved? [stack]
(some true? (map atgoal? stack)))
(defn addtopath [path node]
(conj path node))
(defn pop* [stack]
(last stack))
(defn findpath [stack]
(if (not (solved? stack))
(let [first* (pop* stack) l (last first*) ]
(findpath (drop-last
(remove hasloop? (lazy-cat
(map #(addtopath first* %)
(keys (l graph))) stack)))))
[(first stack)]))
</code></pre>
<p>How to use</p>
<pre class="lang-lisp prettyprint-override"><code>(findpath stack)
</code></pre>
<h2>Question</h2>
<p>I'm really really interested in how this code can be improved. Both in readability, efficiency and performance.</p>
|
[] |
[
{
"body": "<p>I wrote the modified version of your <code>findpath</code> function using recursion:</p>\n\n<pre><code>(defn- dfs\n [graph goal]\n (fn search\n [path visited]\n (let [current (peek path)]\n (if (= goal current)\n [path]\n (->> current graph keys\n (remove visited)\n (mapcat #(search (conj path %) (conj visited %))))))))\n\n(defn findpath\n \"Returns a lazy sequence of all directed paths from start to goal\n within graph.\"\n [graph start goal]\n ((dfs graph goal) [start] #{start}))\n</code></pre>\n\n<p>Instead of using your <code>hasloop?</code> function,\nmy <code>search</code> function keeps track of visited nodes\nin order to avoid visiting the same node twice. \nIt seems to work for your settings:</p>\n\n<pre><code>user> (def graph \n {:s {:a 3 :d 4}\n :a {:s 3 :d 5 :b 4}\n :b {:a 4 :e 5 :c 4} \n :c {:b 4} \n :d {:s 4 :a 5 :e 2} \n :e {:d 2 :b 5 :f 4} \n :f {:e 4 :g 1}})\nuser> (findpath graph :s :g)\n([:s :a :b :e :f :g] [:s :a :d :e :f :g] [:s :d :a :b :e :f :g] [:s :d :e :f :g])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T14:11:34.020",
"Id": "16010",
"ParentId": "15961",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "16010",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T19:20:00.183",
"Id": "15961",
"Score": "7",
"Tags": [
"optimization",
"algorithm",
"performance",
"clojure"
],
"Title": "Depth-first search algorithm in clojure"
}
|
15961
|
<p>The <code>createReport</code> method takes around 30 seconds to execute and I was wondering how I could optimize it. I'm using the <code>Interop.Excel</code> class and the workbook I'm importing to is very formula intensive. </p>
<pre class="lang-vb prettyprint-override"><code>Dim UserDate As New Data_Entry_Form.UserDate
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim xlSourceRange, xlDestRange As Excel.Range
Dim path As String = Application.StartupPath
Dim dt As New DataTable
Public Sub New()
End Sub
Sub createReport(dt As DataTable) ' this procedure determines the flow of the excel manipulation'
openfile("2012 Master.xlsx")
debugging(False)
putfilesIntoYTD(dt)
save("test.xlsx")
closexl()
cleanup()
MsgBox("fin")
End Sub
Sub closexl()
xlWorkBook.Close()
xlApp.Quit()
End Sub
Sub cleanup() ' Releases all of the com objects to object not have excel running as a process after this method finishes'
GC.Collect()
GC.WaitForPendingFinalizers()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSourceRange)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
End Sub
Sub debugging(mode As Boolean) 'Determines if we want to display anything during the dubugging process'
If mode = True Then
xlApp.DisplayAlerts = True
xlApp.Visible = True
Else
xlApp.DisplayAlerts = False
xlApp.Visible = False
End If
End Sub
Sub putfilesIntoYTD(dt As DataTable)
'dt = CType(dbTools.getYTD(startDate, endDate), DataTable)'
Dim fileNum() As String = convertColumntoArray(dt, 0)
Dim dateRecorded() As String = convertColumntoArray(dt, 1)
Dim closerAndTypeCode() As String = convertColumntoArray(dt, 2)
xlSourceRange = xlWorkSheet.Range("N2:N" & fileNum.Length)
xlSourceRange.Value = fileNum
xlSourceRange = xlWorkSheet.Range("O2:O" & dateRecorded.Length)
xlSourceRange.Value = dateRecorded
xlSourceRange = xlWorkSheet.Range("P2:P" & closerAndTypeCode.Length)
xlSourceRange.Value = closerAndTypeCode
End Sub
Function convertColumntoArray(dt As DataTable, columnIndex As Integer) As String() ' Converts a single column of an datatable into an array of strings'
Dim array(dt.Rows.Count) As String
If columnIndex = 1 Then
For i As Integer = 0 To dt.Rows.Count - 1
array(i) = CDate(dt.Rows(i)(columnIndex).ToString()).Date
Next
Else
For i As Integer = 0 To dt.Rows.Count - 1
array(i) = dt.Rows(i)(columnIndex).ToString()
Next
End If
Return array
End Function
Sub save(filename As String) ' Saves the sheet under a specfic name'
xlWorkSheet.SaveAs(path & "/" & filename)
End Sub
Sub openfile(filename As String) ' opens the excel file under a specfic type'
xlApp = New Excel.Application()
xlWorkBook = xlApp.Workbooks.Open(path & "/" & filename)
xlWorkSheet = CType(xlWorkBook.Sheets("1"), Excel.Worksheet)
'xlWorkSheet.Activate()
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T09:04:55.577",
"Id": "25965",
"Score": "0",
"body": "30 seconds for how many records? Anyway, seens like a lot of opportunities for an improvement. Can you detail your benchmarks? Like which lines of code are slowing down everything and if that .xlsx behaves ok with interactive copy-paste."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T15:22:52.653",
"Id": "25972",
"Score": "0",
"body": "Ok I found what's causing my issue. Its specially the save statement which takes 20 seconds!!! I never would of thought that one line of code would be the issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T01:10:07.400",
"Id": "25995",
"Score": "0",
"body": "Do you have any empty cells that are taking up space? If you find the last row/column of your document, check to see if it is *really* the end of the document. Often, Excel will read in numerous blank cells which increase the file size, and thus the file save time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T03:56:09.957",
"Id": "25998",
"Score": "0",
"body": "Hmm... 20 seconds to save is quite a lot. How much data is there? I'd open the resulting document interactively and try to re-save it, both as-is and with deleting everything after the data to make sure tere is no non-empty \"empty\" cells, as per Gaffi's. Does it behave any different?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T04:39:17.700",
"Id": "26135",
"Score": "0",
"body": "I dunno I'll have to check when I get to work on Monday. Pardon my ignorance but when you say interactively do you mean just opening the excel file normally and timing the save outside of visual basic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T18:20:14.973",
"Id": "26299",
"Score": "0",
"body": "OK so I opened the excel document interactivley and timed the saves as operation it seems to take just as long(22-26 seconds). The Excel document is also 756kb if that has anything to do with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T02:40:00.087",
"Id": "143385",
"Score": "0",
"body": "OK I found what's causing my issue. Sadly is has little to do with my code. The excel sheet i have been given to work with is heavily filled with formulas and timing the save on the sheet standalone in excel is clocked around 20 seconds."
}
] |
[
{
"body": "<p>The first step in attempting to optimize a function like this is to narrow down the problem. Determine how long each of the function calls, and then specific lines of code, take to execute. This will tell you where you need to focus your efforts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-16T17:26:31.390",
"Id": "28032",
"Score": "1",
"body": "Most of the execution time occurs with the xlWorkSheet.SaveAs(path & \"/\" & filename)\n I did a \"Save As\" interactively and it took about the same amount of time 30-40 seconds. So I think my problems is due to the sheet i'am working with and not the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-16T15:23:30.240",
"Id": "17614",
"ParentId": "15966",
"Score": "1"
}
},
{
"body": "<p>There is definetely a way to improve that even though the excel sheet has a lot of formulas.\nIn VBA there is an:</p>\n\n<pre><code>Application.Calculation = xlManualCalculation\n</code></pre>\n\n<p>That can be used to help dramatically improve the time it takes, when the problem is many formulas in a sheet. And then in the end you should turn it back to automatic. </p>\n\n<p>As you are using VB with a connection to the Excel Workbook through a COM, the way to do it is very similar. It is:</p>\n\n<pre><code>ExcelApp.Calculation = XlCalculation.xlCalculationManual\n</code></pre>\n\n<p>Where ExcelApp is the excel application object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-03T06:10:45.020",
"Id": "64625",
"ParentId": "15966",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T23:01:21.207",
"Id": "15966",
"Score": "7",
"Tags": [
"optimization",
"vb.net",
"excel"
],
"Title": "Optimizing this Excel automation"
}
|
15966
|
<p>I am writing a networked audio application that sends the audio in 320 byte chunks, later I need to provide the player a bigger amount of bytes to play so I try to merge 2 or more chunks into one buffer and return it, well the code works but I hear some small audio artifacts, any ideas if the code is correct?</p>
<pre><code>-(NSData*) getRawBufferWithSize:(int) requestedBufferSize
{
if(audio.isBuffering && audio.bufferTimer>[[NSDate date] timeIntervalSince1970] && !AUDIO_BYPASS_NET)
{
return nil;
}
audio.isBuffering = NO;
int readyBufferSize = 0;
int bytesPending = requestedBufferSize;
if(returnBufferSize<requestedBufferSize)
{
returnBuffer = (char*)realloc(returnBuffer, requestedBufferSize);
returnBufferSize = requestedBufferSize;
}
while (readyBufferSize<requestedBufferSize)
{
NSData* newBuffer;
@synchronized(playbackRawBuffer)
{
if([playbackRawBuffer count] != 0)
{
newBuffer = [[playbackRawBuffer objectAtIndex:0] retain];
[playbackRawBuffer removeObjectAtIndex:0];
}
else
{
break;
}
}
char* bytes = (char*)[newBuffer bytes];
int readableBytes = newBuffer.length;
int amountOfBytesToRead = bytesPending;
int amountOfBytesToSaveForLater = 0;
if(readableBytes<amountOfBytesToRead)//if we can read less than we want
{
amountOfBytesToRead = readableBytes;
}
else if(readableBytes>amountOfBytesToRead)//if we can read more bytes than we want (we save the remaining bytes)
{
amountOfBytesToSaveForLater = readableBytes - amountOfBytesToRead;
}
bytesPending -= amountOfBytesToRead;
memcpy((char*)returnBuffer+readyBufferSize, bytes, amountOfBytesToRead);
[newBuffer release];
readyBufferSize+=amountOfBytesToRead;
if(amountOfBytesToSaveForLater>0)
{//save these bytes back in the buffers array
if(tBufSize<amountOfBytesToSaveForLater)
{
tBuf = (char*)realloc(tBuf, amountOfBytesToSaveForLater);
tBufSize = amountOfBytesToSaveForLater;
}
memcpy(tBuf, &(bytes[amountOfBytesToRead]), amountOfBytesToSaveForLater);
@synchronized(playbackRawBuffer)
{
[playbackRawBuffer insertObject:[NSData dataWithBytes:tBuf length:amountOfBytesToSaveForLater] atIndex:0];
}
break;
}
}
if(readyBufferSize>0)
{
return [NSData dataWithBytes:returnBuffer length:readyBufferSize];
}
else
{
audio.isBuffering = YES;
audio.bufferTimer = [[NSDate date] timeIntervalSince1970]+0.1;
return nil;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This is the wrong way to sue realloc:</p>\n\n<pre><code>returnBuffer = (char*)realloc(returnBuffer, requestedBufferSize);\n</code></pre>\n\n<p>If it fails you have just leaked the old returnBuffer.<br>\nThe way realloc should be used is:</p>\n\n<pre><code>char* tmp = (char*)realloc(returnBuffer, requestedBufferSize);\nif (tmp != NULL)\n{\n returnBuffer = tmp;\n}\nelse { /* Deal with realloc() failure */ }\n</code></pre>\n\n<p>But why are you dealing with this. I would use a <code>std::vector<char></code> it deals with all the memory management issues for you (and your post id tagged C++).</p>\n\n<p>TO be honest I have trouble following the rest of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T07:12:29.703",
"Id": "26000",
"Score": "0",
"body": "Well in this case the requested buffer size is from 600 to 700 bytes of data, if realloc cannot manage to extend it to this size then I think I have more serious problems than a memory leak :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T19:04:56.337",
"Id": "26038",
"Score": "0",
"body": "@AntonBanchev: That's not really the point. You are writing code that is known bad pattern. I reject people from an interview for making such obvious mistakes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T23:00:05.597",
"Id": "45574",
"Score": "0",
"body": "+1 for βuse `std::vector`β, although maybe for this particular problem, `std::deque` would work even better."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T17:25:53.747",
"Id": "15991",
"ParentId": "15969",
"Score": "1"
}
},
{
"body": "<p>I'm not sure what your sample rate is, but two 320-byte blocks put together is likely to be such a short time interval that merging them into 640 <em>entirely wrong</em> bytes would just sound like a quick \"artifact.\"</p>\n\n<p>What evidence do you have that this merge works correctly at all? It's hard to interpret on it's own, and if all you've got to go on currently is an audible artifact, there's a possibility that it is just 640 bytes of junknoise.</p>\n\n<p>Suggestion: run the method on it's own with known input, expected output, and validate that it does merge at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T20:36:52.007",
"Id": "23089",
"ParentId": "15969",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T08:04:34.100",
"Id": "15969",
"Score": "6",
"Tags": [
"objective-c",
"ios"
],
"Title": "Am I reconstructing the buffers correctly"
}
|
15969
|
<p>For experimental and learning purposes. I was trying to create a sorting algorithm from a hash function that gives a value biased on alphabetical sequence of the string, it then would ideally place it in the right place from that hash.</p>
<p>The reasoning is that theoretically if done right this algorithm can achieve O(n) speeds or nearly so. </p>
<p>So here is what I have worked out in python so far:</p>
<pre><code>letters = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,
'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,
's':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25,
'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,
'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,
'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25}
def sortlist(listToSort):
listLen = len(listToSort)
newlist = []
for i in listToSort:
k = letters[i[0]]
for j in i[1:]:
k = (k*26) + letters[j]
norm = k/pow(26,len(i)) # get a float hash that is normalized(i think thats what it is called)
# 2nd part
idx = int(norm*len(newlist)) # get a general of where it should go
if newlist: #find the right place from idx
if norm < newlist[idx][1]:
while norm < newlist[idx][1] and idx > 0: idx -= 1
if norm > newlist[idx][1]: idx += 1
else:
while norm > newlist[idx][1] and idx < (len(newlist)-1): idx += 1
if norm > newlist[idx][1]: idx += 1
newlist.insert(idx,[i,norm])# put it in the right place with the "norm" to ref later when sorting
return newlist
</code></pre>
<p>I think that the 1st part is good, but the 2nd part needs help. so the Qs would be what would be the best way to do something like this or is it even possible to get O(n) time (or near that) out of this?</p>
<p>The testing I did with an 88,000 word list took prob about 5 min, 10,000 took about 30 sec it got a lot worse as the list count went up.</p>
<p>If this idea actually works out then I would recode it in C to get some real speed and optimizations. </p>
<p>Thank for any advice that you could give.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T07:03:18.827",
"Id": "25962",
"Score": "0",
"body": "It will not be O(n), it will be O(n^2). For each of the `n` entries, the inner `while` loop will iterate some number of times that scales with `n`. So the algortihm has an O(n) loop inside an O(n) loop, making it O(n^2). You need to heavily optimize the number of compares you do in the inner loop. Why are you skipping by only 1 every time? (Also, make sure you use a data structure whose `insert` operation is O(1) or that will be a problem too.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T07:13:15.780",
"Id": "25963",
"Score": "0",
"body": "yes that is true, however that is what i am trying to solve, the 2nd part is there only because it works - even if slow, and i cant think of a better way to do it for the life of me, i would like to replace it with something that would not have to do the other loops if at all possible. any ideas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T08:08:49.337",
"Id": "25964",
"Score": "0",
"body": "Have you read http://en.wikipedia.org/wiki/Sorting_algorithm ?"
}
] |
[
{
"body": "<p>You have reinvented a form of <a href=\"http://en.wikipedia.org/wiki/Radix_sort\" rel=\"nofollow\">radix sort</a>.\nSee that page for how to get rid of the two nested O(n) loops.</p>\n\n<p>It is possible to get O(n) if the maximum length of the words to be sorted is assumed to be a constant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T08:46:58.697",
"Id": "15972",
"ParentId": "15971",
"Score": "1"
}
},
{
"body": "<pre><code>letters = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,\n'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,\n's':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25,\n'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,\n'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,\n'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25} \n</code></pre>\n\n<p>Python convention says that constants should be named in ALL_CAPS. I'd also suggest writing code to build this dict from <code>string.ascii_lowercase</code></p>\n\n<pre><code>def sortlist(listToSort):\n</code></pre>\n\n<p>Use <code>_</code> to seperate words in function/parameter names, this line should be: <code>def sort_list(list_to_sort):</code> to follow python guidelines.</p>\n\n<pre><code> listLen = len(listToSort)\n</code></pre>\n\n<p>I don't see that you ever use this</p>\n\n<pre><code> newlist = []\n for i in listToSort:\n k = letters[i[0]]\n for j in i[1:]:\n k = (k*26) + letters[j]\n</code></pre>\n\n<p>Set <code>k=0</code> before the loop, and then you won't need to slice the string.</p>\n\n<pre><code> norm = k/pow(26,len(i)) # get a float hash that is normalized(i think thats what it is called)\n</code></pre>\n\n<p>a <code>norm</code> has a specific meaning, instead, I'd call this <code>normalized</code>.</p>\n\n<pre><code> # 2nd part\n idx = int(norm*len(newlist)) # get a general of where it should go\n</code></pre>\n\n<p>The problem is that this assumes you'll have a pretty even distribution of all possible strings. That's never going to happen, since some letters are used far less then others. This simple isn't going to be a good heuristic. </p>\n\n<pre><code> if newlist: #find the right place from idx\n if norm < newlist[idx][1]:\n while norm < newlist[idx][1] and idx > 0: idx -= 1\n if norm > newlist[idx][1]: idx += 1\n else:\n while norm > newlist[idx][1] and idx < (len(newlist)-1): idx += 1\n if norm > newlist[idx][1]: idx += 1\n</code></pre>\n\n<p>This is going to rather slowly move to the correct position. Finding the correct position would be much better done by using binary search. The <code>bisect</code> module has functions to do it.</p>\n\n<pre><code> newlist.insert(idx,[i,norm])# put it in the right place with the \"norm\" to ref later when sorting\n</code></pre>\n\n<p>This line will kill your performance. The insert is going to have to move items around constantly. That'll make your algorithm <code>O(n^2)</code>.</p>\n\n<pre><code> return newlist\n</code></pre>\n\n<p>See the radix or bucket sort, they are getting at the same ideas you are. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T14:55:39.387",
"Id": "15981",
"ParentId": "15971",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T06:56:40.847",
"Id": "15971",
"Score": "3",
"Tags": [
"python",
"sorting",
"c",
"algorithm"
],
"Title": "creating a hash based sorting algorithm"
}
|
15971
|
<p>This is my first complete program written in F# (I was from C# and occasionally do interop) and I believe there are quite a few places I didn't tackle well in terms of coding practice.</p>
<p>Unblock Me / Rush Hour:</p>
<pre><code> 5 b b k j
4 c c c k j
3 a a k i l
2 d g g i l
1 d f h h l
0 e e f
0 1 2 3 4 5
</code></pre>
<p>A player can move horizontal bricks horizontally, vertical bricks vertically. The aim is to move the brick denoted by <code>aa</code> to the rightmost.</p>
<p>I used depth limited search to solve this problem, and the full running code is attached. It is slow (depth 7 takes 2 sec), and I know there are better algorithms for the problem.</p>
<p>However, my objective is to learn F# well, so could someone please shed some light on me how to improve the code without making to much tweaks on the algorithm itself?</p>
<pre><code>module Unblock
open System
open System.Collections.Generic
open System.IO
open System.Diagnostics
type Position = int * int // (RowID, ColumnID)
type Brick = char * int // (Name, Length)
type State = Position[]
type BrickInfo = Brick[]
type Direction =
| Up
| Down
| Left
| Right
override this.ToString() =
match this with
| Up -> "Up"
| Down -> "Down"
| Left -> "Left"
| Right -> "Right"
type Move = int * Direction
//module myFunction =
let checkBoth target length current =
if current > target || current + length - 1 < target then true else false
let test (initialState: State) (brickInfo: Brick[]) (horizontalBricks: int[][], verticalBricks: int[][]) (rowNum, columnNum) =
//let sw = new StreamWriter("output.csv");
let (redRowNum, _) = initialState.[0]
let (_, redLength) = brickInfo.[0]
let mySet = new HashSet<_>(HashIdentity.Structural)
let horizontalBricksAll = horizontalBricks |> Array.concat
let verticalBricksAll = verticalBricks |> Array.concat
let rec solveDFS (currentState: State) (lastBrick, lastDirection) depth =
let generateState i (newPosition: Position) =
let nextState = currentState |> Array.copy
nextState.[i] <- newPosition
nextState
let isDuplicated (set: HashSet<_>) =
if set.Contains (currentState) then true
else
//let f = currentState |> Array.map (fun elem -> sw.Write("{0},{1} ", fst elem, snd elem))
//sw.WriteLine()
ignore (set.Add currentState)
false
let checkVacancy (rowID, columnID) =
let checkHorizontal i =
let (_, length) = brickInfo.[i]
let (_, startColumn) = currentState.[i]
checkBoth columnID length startColumn
let checkVertical i =
let (_, length) = brickInfo.[i]
let (startRow, _) = currentState.[i]
checkBoth rowID length startRow
(horizontalBricks.[rowID] |> Array.forall checkHorizontal) && (verticalBricks.[columnID] |> Array.forall checkVertical)
let generateRight i =
let (_, length) = brickInfo.[i]
let (rowID, columnID) = currentState.[i]
if columnID + length >= columnNum then None
else Some ((rowID, columnID + length), (rowID, columnID + 1))
let generateLeft i =
let (_, length) = brickInfo.[i]
let (rowID, columnID) = currentState.[i]
if columnID = 0 then None
else Some ((rowID, columnID - 1), (rowID, columnID - 1))
let generateUp i =
let (_, length) = brickInfo.[i]
let (rowID, columnID) = currentState.[i]
if rowID + length >= rowNum then None
else Some ((rowID + length, columnID), (rowID + 1, columnID))
let generateDown i =
let (_, length) = brickInfo.[i]
let (rowID, columnID) = currentState.[i]
if rowID = 0 then None
else Some ((rowID - 1, columnID), (rowID - 1, columnID))
if depth < 7
&& not (isDuplicated mySet)
&&
(
let (_, columnLeft) = currentState.[0]
[|columnLeft + redLength .. columnNum - 1|] |> Array.forall (fun columnID -> checkVacancy (redRowNum, columnID))
||
horizontalBricksAll |> Seq.tryFind (fun elem ->
(match generateRight elem with
| Some (a,b) when checkVacancy a -> solveDFS (generateState elem b) (elem, Right) (depth + 1)
| _ -> false)
||
(match generateLeft elem with
| Some (a,b) when checkVacancy a -> solveDFS (generateState elem b) (elem, Left) (depth + 1)
| _ -> false)
)
|> Option.isSome
||
verticalBricksAll |> Seq.tryFind (fun elem ->
(match generateUp elem with
| Some (a,b) when checkVacancy a -> solveDFS (generateState elem b) (elem, Up) (depth + 1)
| _ -> false)
||
(match generateDown elem with
| Some (a,b) when checkVacancy a -> solveDFS (generateState elem b) (elem, Down) (depth + 1)
| _ -> false)
)
|> Option.isSome
)
then
Console.WriteLine("Brick Name {0} Direction {1}", fst brickInfo.[lastBrick], lastDirection)
true
else
ignore (mySet.Remove(currentState))
false
Console.WriteLine (solveDFS initialState (0, Right) 0) // the output would have an additional line of useless information (0, Right)
let x0 = ('a',2)
let x1 = ('b',2)
let x2 = ('c',3)
let x3 = ('d',2)
let x4 = ('e',2)
let x5 = ('f',1)
let x6 = ('g',2)
let x7 = ('h',2)
let x8 = ('i',2)
let x9 = ('j',2)
let x10 = ('k',3)
let x11 = ('l',3)
let brickInfo = [|x0;x1;x2;x3;x4;x5;x6;x7;x8;x9;x10;x11|]
let horizontalBricks = [|[|4|];[|7|];[|6|];[|0|];[|2|];[|1|]|]
let verticalBricks = [|[|3|];[||];[|5|];[|10|];[|8;9|];[|11|]|]
let rowNum = 6
let columnNum = 6
let p0 = (3,0)
let p1 = (5,0)
let p2 = (4,0)
let p3 = (1,0)
let p4 = (0,0)
let p5 = (0,2)
let p6 = (2,2)
let p7 = (1,3)
let p8 = (2,4)
let p9 = (4,4)
let p10 = (3,3)
let p11 = (1,5)
let initialState =[|p0;p1;p2;p3;p4;p5;p6;p7;p8;p9;p10;p11|]
[<EntryPoint>]
let main argv =
printfn "%A" argv
let sw = new Stopwatch()
sw.Start()
ignore (test (initialState) (brickInfo) (horizontalBricks, verticalBricks) (rowNum, columnNum))
sw.Stop()
Console.WriteLine(sw.Elapsed)
0 // return an integer exit code
</code></pre>
|
[] |
[
{
"body": "<p>There are some places you could tweak the code to squeeze out more performance and/or adhere to better F# style.</p>\n\n<hr>\n\n<p>If you're not going to use a function in curried form -- i.e., you're always going to pass all of the arguments at once -- it's better to define the function as such. Doing so allows the F# compiler to compile the function into a single .NET method, rather than a bunch of closures.</p>\n\n<p>For example, change this:</p>\n\n<pre><code>let rec solveDFS (currentState: State) (lastBrick, lastDirection) depth =\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>let rec solveDFS (currentState : State, lastBrick, lastDirection, depth) =\n</code></pre>\n\n<p>I don't think this'll make much of a difference for your code, but it will make a difference for larger codebases.</p>\n\n<hr>\n\n<p><code>inline</code> the <code>generateRight</code>, etc. functions -- they're fairly small and only used once so it'd be better to avoid the overhead of a function call.</p>\n\n<hr>\n\n<p>When your input is an array, it's better to use functions in the <code>Array</code> module instead of the <code>Seq</code> module, because the <code>Array</code> functions are optimized for arrays. So, change the <code>Seq.tryFind</code> calls to <code>Array.tryFind</code>.</p>\n\n<hr>\n\n<p>If you can, it'd be better to use 2d arrays (<code>[,]</code>) instead of jagged arrays (<code>[][]</code>). The reason is that a 2d array is stored as a contiguous block of memory and only requires a few more arithmetic operations to access than a 1d array, whereas a jagged array is stored in non-contiguous chunks so you have an additional indirection and poor memory locality (i.e., doesn't work as well with the CPU cache).</p>\n\n<p>I didn't make this change to the code I posted below, but this could provide a noticeable improvement in your code since you're frequently accessing the arrays.</p>\n\n<p>Note that there is an <code>Array2D</code> module for working with 2d arrays.</p>\n\n<hr>\n\n<p>Here's your code with the changes I described, other than the modification for 2d arrays:</p>\n\n<pre><code>module Unblock\nopen System\nopen System.Collections.Generic\nopen System.IO\nopen System.Diagnostics\n\n\ntype Position = int * int // (RowID, ColumnID)\n\ntype Brick = char * int // (Name, Length)\n\ntype State = Position[]\ntype BrickInfo = Brick[]\n\ntype Direction = \n | Up\n | Down\n | Left\n | Right\n\n override this.ToString() =\n match this with\n | Up -> \"Up\"\n | Down -> \"Down\"\n | Left -> \"Left\"\n | Right -> \"Right\"\n\ntype Move = int * Direction\n\n//module myFunction =\n\nlet inline checkBoth target length current =\n if current > target || current + length - 1 < target then true else false\n\n\n\nlet test (initialState: State, brickInfo: Brick[], horizontalBricks: int[][], verticalBricks: int[][], rowNum, columnNum) =\n //let sw = new StreamWriter(\"output.csv\");\n let (redRowNum, _) = initialState.[0]\n let (_, redLength) = brickInfo.[0]\n let mySet = HashSet<_> (HashIdentity.Structural)\n\n let horizontalBricksAll = Array.concat horizontalBricks\n let verticalBricksAll = Array.concat verticalBricks\n\n let rec solveDFS (currentState: State, lastBrick, lastDirection, depth) =\n\n let generateState i (newPosition: Position) =\n let nextState = Array.copy currentState\n nextState.[i] <- newPosition\n nextState\n\n let inline isDuplicated (set: HashSet<_>) =\n if set.Contains (currentState) then true\n else\n //let f = currentState |> Array.map (fun elem -> sw.Write(\"{0},{1} \", fst elem, snd elem))\n //sw.WriteLine()\n ignore (set.Add currentState)\n false\n\n let checkVacancy (rowID, columnID) =\n horizontalBricks.[rowID]\n |> Array.forall (fun i ->\n let length = snd brickInfo.[i]\n let startColumn = snd currentState.[i]\n checkBoth columnID length startColumn)\n\n && verticalBricks.[columnID]\n |> Array.forall (fun i ->\n let length = snd brickInfo.[i]\n let startRow = fst currentState.[i]\n checkBoth rowID length startRow)\n\n let inline generateRight i =\n let length = snd brickInfo.[i]\n let (rowID, columnID) = currentState.[i]\n if columnID + length >= columnNum then None\n else Some ((rowID, columnID + length), (rowID, columnID + 1))\n let inline generateLeft i =\n let length = snd brickInfo.[i]\n let (rowID, columnID) = currentState.[i]\n if columnID = 0 then None\n else Some ((rowID, columnID - 1), (rowID, columnID - 1))\n let inline generateUp i =\n let length = snd brickInfo.[i]\n let (rowID, columnID) = currentState.[i]\n if rowID + length >= rowNum then None\n else Some ((rowID + length, columnID), (rowID + 1, columnID))\n let inline generateDown i =\n let length = snd brickInfo.[i]\n let (rowID, columnID) = currentState.[i]\n if rowID = 0 then None\n else Some ((rowID - 1, columnID), (rowID - 1, columnID))\n\n // This was refactored from inside the condition of the 'if' statement below.\n // It's marked as 'inline', so it should compile to the exact same IL, but it's\n // much easier to read this way.\n let inline check () =\n let columnLeft = snd currentState.[0]\n [|columnLeft + redLength .. columnNum - 1|]\n |> Array.forall (fun columnID ->\n checkVacancy (redRowNum, columnID))\n ||\n horizontalBricksAll\n |> Array.tryFind (fun elem ->\n (match generateRight elem with\n | Some (a, b) when checkVacancy a ->\n solveDFS (generateState elem b, elem, Right, depth + 1)\n | _ -> false)\n ||\n (match generateLeft elem with\n | Some (a, b) when checkVacancy a ->\n solveDFS (generateState elem b, elem, Left, depth + 1)\n | _ -> false))\n |> Option.isSome\n ||\n verticalBricksAll\n |> Array.tryFind (fun elem ->\n (match generateUp elem with\n | Some (a, b) when checkVacancy a ->\n solveDFS (generateState elem b, elem, Up, depth + 1)\n | _ -> false)\n ||\n (match generateDown elem with\n | Some (a, b) when checkVacancy a ->\n solveDFS (generateState elem b, elem, Down, depth + 1)\n | _ -> false))\n |> Option.isSome\n\n if depth < 7 && not (isDuplicated mySet) && check () then\n printfn \"Brick Name %c Direction %A\" (fst brickInfo.[lastBrick]) lastDirection\n true\n else\n mySet.Remove currentState\n |> ignore\n false\n\n // the output would have an additional line of useless information (0, Right)\n Console.WriteLine (solveDFS (initialState, 0, Right, 0))\n\n\n\nlet x0 = ('a',2)\nlet x1 = ('b',2)\nlet x2 = ('c',3)\nlet x3 = ('d',2)\nlet x4 = ('e',2)\nlet x5 = ('f',1)\nlet x6 = ('g',2)\nlet x7 = ('h',2)\nlet x8 = ('i',2)\nlet x9 = ('j',2)\nlet x10 = ('k',3)\nlet x11 = ('l',3)\n\nlet brickInfo = [|x0;x1;x2;x3;x4;x5;x6;x7;x8;x9;x10;x11|]\nlet horizontalBricks = [|[|4|];[|7|];[|6|];[|0|];[|2|];[|1|]|]\nlet verticalBricks = [|[|3|];[||];[|5|];[|10|];[|8;9|];[|11|]|]\nlet [<Literal>] rowNum = 6\nlet [<Literal>] columnNum = 6\n\nlet p0 = (3,0)\nlet p1 = (5,0)\nlet p2 = (4,0)\nlet p3 = (1,0)\nlet p4 = (0,0)\nlet p5 = (0,2)\nlet p6 = (2,2)\nlet p7 = (1,3)\nlet p8 = (2,4)\nlet p9 = (4,4)\nlet p10 = (3,3)\nlet p11 = (1,5)\n\n\nlet initialState = [|p0;p1;p2;p3;p4;p5;p6;p7;p8;p9;p10;p11|]\n\n[<EntryPoint>]\nlet main argv = \n printfn \"%A\" argv\n\n let sw = Stopwatch.StartNew ()\n\n test (initialState, brickInfo, horizontalBricks, verticalBricks, rowNum, columnNum)\n |> ignore\n\n sw.Stop()\n\n Console.WriteLine sw.Elapsed\n 0 // return an integer exit code\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T14:17:38.263",
"Id": "26018",
"Score": "1",
"body": "A few more small tweaks: `checkBoth` could be shortened to `current > target || current + length - 1 < target` and `isDuplicated` to `not (set.Add(currentState))`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T14:58:33.860",
"Id": "26024",
"Score": "0",
"body": "Is there any way to simplify `generateUp generateLeft ...` as they take the majority of coding space"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T16:41:19.440",
"Id": "26032",
"Score": "0",
"body": "@colinfang as for points #1 and #4 in your comments -- can you name some specific books? I'm 99.9% certain I'm correct there, so I'm curious to know where you read that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T16:43:34.960",
"Id": "26033",
"Score": "0",
"body": "No, there's not much you could do with them."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T14:12:08.047",
"Id": "16011",
"ParentId": "15973",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T09:51:51.180",
"Id": "15973",
"Score": "4",
"Tags": [
"algorithm",
"f#"
],
"Title": "Unblock Me / Rush Hour solver"
}
|
15973
|
<p>I'm trying to learn some Scala and decided to try to tackle some Project Euler problems. </p>
<p>For <a href="http://projecteuler.net/problem=48" rel="nofollow">problem #48</a>, coming from a Python background, my solution is the following one-liner:</p>
<pre><code>print ( (1 to 1000).map(i => BigInt(i).pow(i)).sum % BigInt(10).pow(10) )
</code></pre>
<p>Is this idiomatic? Is there a simpler/more readable solution?</p>
|
[] |
[
{
"body": "<p>Your solution is totally valid. Instead of <code>xs.map(f).sum</code> it is possible to use <code>xs.foldLeft(init)(f)</code>:</p>\n\n<pre><code>(1 to 1000).foldLeft(BigInt(0)) {\n (sum, n) => sum+BigInt(n).pow(n)\n}\n// or with /: synonym for foldLeft\n(BigInt(0) /: (1 to 1000)) {\n (sum, n) => sum+BigInt(n).pow(n)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:05:50.853",
"Id": "26045",
"Score": "0",
"body": "Thanks for you answer! Would using foldLeft be more efficient or is it just a matter of taste?\nAlso, I didn't know at all the /: syntax for foldLeft. Seems a bit cryptic TBH..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:27:40.037",
"Id": "26046",
"Score": "1",
"body": "`foldLeft` should be more efficient because it does both operations (map+sum) in a single step. Thus, there is no unnecessary creation of an intermediate collection (from map), which can be allayed with lazy collections (like `.iterator` of `.view`). But, `foldLeft` should be more efficient, even with lazy collections."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T14:25:36.460",
"Id": "15980",
"ParentId": "15974",
"Score": "2"
}
},
{
"body": "<p>Your solution is clean but doesn't <strong>scale</strong> well. A well known optimization for <code>a^k mod m</code> is to perform all computations modulus <code>m</code>. If <code>m</code> is sufficiently small, we furthermore can switch to native types (this is not the case here !).</p>\n\n<pre><code>val n = 1000\nval m = BigInt(10).pow(10)\n(for (i <- 1 to n) yield BigInt(i).modPow(i,m)).sum % m\n</code></pre>\n\n<p>Rounded avarage timing results (Scala 2.9.1 with <code>-optimize</code>) :</p>\n\n<pre><code>n 1000 | 10000\nInitial solution 4.8 ms | 6700 ms\nFold left 4.8 ms | 6700 ms\nMy humble version 0.5 ms | 5 ms\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T22:58:00.033",
"Id": "20967",
"ParentId": "15974",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20967",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T10:44:05.413",
"Id": "15974",
"Score": "6",
"Tags": [
"scala",
"project-euler"
],
"Title": "Solving Project Euler problem #48 in Scala"
}
|
15974
|
<p>There are three servers. I want to assign a job to a server which has least <code>NotStarted</code> jobs. I have achieved this, but my code is very lengthy. I don't know how to minimize my code without changing my concept. Here is my code:</p>
<pre><code>public List<int> GetPaServer()
{
List<int> PaServers = new List<int>();
using (PaEntities pa = new PaEntities())
{
var PaServer = from server in pa.AppPM_Pa_Server
where server.IsActive == true
select server.ServerId;
foreach (var paServer in PaServer)
{
PaServers.Add(paServer);
}
}
return PaServers;
}
//Method to get the serverid for each request.
public int GetPaQueue()
{
using (PaEntities server = new PaEntities())
{
List<int> Paserver = new List<int>();
Paserver = GetPaServer();
string server1 = string.Empty;
string server2 = string.Empty;
string server3 = string.Empty;
foreach (int paserver in Paserver)
{
if (paserver == 1)
{
server1 = "active";
}
else if (paserver == 2)
{
server2 = "active";
}
else if (paserver == 3)
{
server3 = "active";
}
}
int retVal = 0;
// Get the Server NotStarted details here
var NotStarted1 = (from serverID in server.AppPM_Pat
where serverID.Status == "NotStarted" && serverID.ServerId == 1
select serverID.ServerId).Count();
var NotStarted2 = (from serverID in server.AppPM_Pat
where serverID.Status == "NotStarted" && serverID.ServerId == 2
select serverID.ServerId).Count();
var NotStarted3 = (from serverID in server.AppPM_Pat
where serverID.Status == "NotStarted" && serverID.ServerId == 3
select serverID.ServerId).Count();
// Get the Server Started details here
var server_Started1 = (from serverID in server.AppPM_Pat
where serverID.Status == "Started" && serverID.ServerId == 1
select serverID.ServerId).Count();
var server_Started2 = (from serverID in server.AppPM_Pat
where serverID.Status == "Started" && serverID.ServerId == 2
select serverID.ServerId).Count();
var server_Started3 = (from serverID in server.AppPM_Pat
where serverID.Status == "Started" && serverID.ServerId == 3
select serverID.ServerId).Count();
//Get the server number for each request
//control comes here only when the server is active
if (server1 == "active" && server2 == "active" && server3 == "active")
{
if (NotStarted1 == 0 && NotStarted2 == 0 && NotStarted3 == 0)
{
if ((server_Started1 > server_Started2) && (server_Started1 > server_Started3))
{
retVal = 2;
}
else if (server_Started1 == 0 && server_Started2 == 0 && server_Started3 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
retVal = 1;
}
else if ((server_Started2 > server_Started1) && (server_Started2 > server_Started3))
{
retVal = 1;
}
else if ((server_Started3 > server_Started1) && (server_Started3 > server_Started2))
{
retVal = 1;
}
else if (server_Started1 == server_Started2 && server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started1 == server_Started3 && server_Started2 == 0)
{
retVal = 2;
}
else if (server_Started2 == server_Started3 && server_Started1 == 0)
{
retVal = 1;
}
}
//control comes here only when the third server is active after some time
else if (NotStarted1 == NotStarted2 && NotStarted3 == 0)
{
if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 3;
}
}
else if ((NotStarted1 > NotStarted2) && NotStarted3 == 0)
{
if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 3;
}
}
else if ((NotStarted2 > NotStarted1) && NotStarted3 == 0)
{
if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 3;
}
}
//control comes here only when the first server is active after some time
else if (NotStarted2 == NotStarted3 && NotStarted1 == 0)
{
if (server_Started3 == 1 & server_Started2 == 1 & server_Started1 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 1;
}
}
else if ((NotStarted2 > NotStarted3) && NotStarted1 == 0)
{
if (server_Started3 == 1 & server_Started2 == 1 & server_Started1 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 1;
}
}
else if ((NotStarted3 > NotStarted2) && NotStarted1 == 0)
{
if (server_Started3 == 1 & server_Started2 == 1 & server_Started1 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 1;
}
}
//control comes here only when the second server is active after some time
else if (NotStarted3 == NotStarted1 && NotStarted2 == 0)
{
if (server_Started3 == 1 & server_Started1 == 1 & server_Started2 == 0)
{
retVal = 2;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 2;
}
}
else if ((NotStarted3 > NotStarted1) && NotStarted2 == 0)
{
if (server_Started3 == 1 & server_Started1 == 1 & server_Started2 == 0)
{
retVal = 2;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 2;
}
}
else if ((NotStarted1 > NotStarted3) && NotStarted2 == 0)
{
if (server_Started3 == 1 & server_Started1 == 1 & server_Started2 == 0)
{
retVal = 2;
}
else if (server_Started1 == 1 & server_Started2 == 1 & server_Started3 == 1)
{
retVal = 2;
}
}
else if (NotStarted1 == 1 && NotStarted2 == 0 && NotStarted3 == 0)
{
if ((server_Started1 > server_Started2) && (server_Started1 > server_Started3))
{
retVal = 2;
}
else if (server_Started1 == 0 && server_Started2 == 0 && server_Started3 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
retVal = 1;
}
else if ((server_Started2 > server_Started1) && (server_Started2 > server_Started3))
{
retVal = 1;
}
else if ((server_Started3 > server_Started1) && (server_Started3 > server_Started2))
{
retVal = 1;
}
else if (server_Started1 == server_Started2 && server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started1 == server_Started3 && server_Started2 == 0)
{
retVal = 2;
}
else if (server_Started2 == server_Started3 && server_Started1 == 0)
{
retVal = 1;
}
}
else if (NotStarted1 == 1 && NotStarted2 == 1 && NotStarted3 == 0)
{
if ((server_Started1 > server_Started2) && (server_Started1 > server_Started3))
{
retVal = 2;
}
else if (server_Started1 == 0 && server_Started2 == 0 && server_Started3 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
retVal = 1;
}
else if ((server_Started2 > server_Started1) && (server_Started2 > server_Started3))
{
retVal = 1;
}
else if ((server_Started3 > server_Started1) && (server_Started3 > server_Started2))
{
retVal = 1;
}
else if (server_Started1 == server_Started2 && server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started1 == server_Started3 && server_Started2 == 0)
{
retVal = 2;
}
else if (server_Started2 == server_Started3 && server_Started1 == 0)
{
retVal = 1;
}
}
else if (NotStarted1 > NotStarted2 && NotStarted1 > NotStarted3)
{
if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
if (NotStarted2 > NotStarted3)
{
retVal = 3;
}
else
{
retVal = 2;
}
}
}
else if (NotStarted2 > NotStarted3 && NotStarted2 > NotStarted1)
{
if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
if (NotStarted1 > NotStarted3)
{
retVal = 3;
}
else
{
retVal = 1;
}
}
}
else if (NotStarted3 > NotStarted1 && NotStarted3 > NotStarted2)
{
if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
if (NotStarted1 > NotStarted2)
{
retVal = 2;
}
else
{
retVal = 1;
}
}
}
else if (NotStarted1 == NotStarted2 && NotStarted2 == NotStarted3 && NotStarted1 == NotStarted3)
{
if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
retVal = 1;
}
}
else if (NotStarted1 == NotStarted2 && NotStarted1 > NotStarted3 && NotStarted2 > NotStarted3)
{
if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
retVal = 3;
}
}
else if (NotStarted2 == NotStarted3 && NotStarted2 > NotStarted1 && NotStarted3 > NotStarted1)
{
if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
retVal = 1;
}
}
else if (NotStarted1 == NotStarted3 && NotStarted1 > NotStarted2 && NotStarted3 > NotStarted2)
{
if (server_Started1 == 1 && server_Started2 == 1 && server_Started3 == 1)
{
retVal = 2;
}
}
}
//control comes here only when server1 and server2 is active
else if (server1 == "active" && server2 == "active")
{
if (NotStarted1 > NotStarted2)
{
if (server_Started1 == 1 && server_Started2 == 1)
{
retVal = 2;
}
}
else if (NotStarted1 == NotStarted2)
{
if (server_Started1 == 0 && server_Started2 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 && server_Started2 == 0)
{
retVal = 2;
}
else if (server_Started1 == 0 && server_Started2 == 1)
{
retVal = 1;
}
else if (server_Started1 == 1 && server_Started2 == 1)
{
retVal = 1;
}
}
else
{
if (server_Started1 == 1 && server_Started2 == 1)
{
retVal = 1;
}
}
}
//control comes here only when server3 and server2 is active
else if (server2 == "active" && server3 == "active")
{
if (NotStarted2 > NotStarted3)
{
if (server_Started2 == 1 && server_Started3 == 1)
{
retVal = 3;
}
}
else if (NotStarted2 == NotStarted3)
{
if (server_Started2 == 0 && server_Started3 == 0)
{
retVal = 2;
}
else if (server_Started2 == 1 && server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started2 == 0 && server_Started3 == 1)
{
retVal = 2;
}
else if (server_Started2 == 1 && server_Started3 == 1)
{
retVal = 2;
}
}
else
{
if (server_Started2 == 1 && server_Started3 == 1)
{
retVal = 2;
}
}
}
//control comes here only when server1 and server3 is active
else if (server1 == "active" && server3 == "active")
{
if (NotStarted1 > NotStarted3)
{
if (server_Started1 == 1 && server_Started3 == 1)
{
retVal = 3;
}
}
else if (NotStarted1 == NotStarted3)
{
if (server_Started1 == 0 && server_Started3 == 0)
{
retVal = 1;
}
else if (server_Started1 == 1 && server_Started3 == 0)
{
retVal = 3;
}
else if (server_Started1 == 0 && server_Started3 == 1)
{
retVal = 1;
}
else if (server_Started1 == 1 && server_Started3 == 1)
{
retVal = 1;
}
}
else
{
if (server_Started1 == 1 && server_Started3 == 1)
{
retVal = 1;
}
}
}
return retVal;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Use arrays to hold your servers, then loop over the arrays instead of repeating the same code for each server. In the loop you have a server AND its index, so you can omit changing just one number and the server while copying around the code. Rinse and repeat for NotStarted and the other values you calculate for each server.</p>\n\n<p>Furthermore, it looks like you have an unrolled sorting algorithm in your code. If you combine a server and its NotStarted and other calculated values into a struct, you can just use an array of struct values and then sort it with a custom sorting function. Or use a LINQ expression. I'm still seven hours away from my dev PC, maybe I can hack something together this evening...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T10:53:33.280",
"Id": "15978",
"ParentId": "15975",
"Score": "6"
}
},
{
"body": "<p>A few simple things before getting to the meat of the problem.</p>\n\n<p>Method variables start with lowercase letters. There are a number of cases where you are not consistent with this and it will confuse other people that read your code. For the same reason, you should be consistent with camelCase of underscore_separated variable names.</p>\n\n<p>Don't create a new <code>List</code> instance if you are going to assign the result of a function to that variable on the next line.</p>\n\n<pre><code>List<int> Paserver = new List<int>();\nPaserver = GetPaServer();\n</code></pre>\n\n<p>This can all just be one line of code.</p>\n\n<p>Abstract away repeated functionality in methods. The code you are using to create <code>NotStarted#</code> and <code>server_Started#</code> only changes based on the id and status string.</p>\n\n<pre><code>private int serverJobCount(PaEntities server, int id, string status) {\n return (from serverID in server.AppPM_Pat\n where serverID.Status == status && serverID.ServerId == id\n select serverID.ServerId).Count();\n}\n</code></pre>\n\n<p>Now to your actual question. As you have seen, the process for doing this gets complicate when there are three servers. And it would get even longer if you had 4. The good news is that there is already a way to solve this for any number of servers. You should think of this problem as if you gave a value to each server and that value represented how much that server should be favoured to get a new job. Once you have that, all you need to do is sort those vales and the first server in the list is the one you should schedule the job with.</p>\n\n<p>To make this easier, lets first make a class that represents a server. This will remove the need for all of your <code>thing#</code> and <code>otherThing#</code> variables.</p>\n\n<pre><code>public class Server : IComparable {\n //It looks like the server can only have one started job, so I made this boolean.\n public bool Started { get; private set; }\n public int NotStarted { get; private set; }\n\n public Server(bool started, int notStarted) {\n Started = started;\n NotStarted = notStarted;\n }\n\n //This is where the magic happens\n public int CompareTo(object obj) {\n Server other = obj as Server;\n if (other != null) {\n //This is where you put your ordering logic. I filled in values to give you a feel.\n //You should ensure the logic is correct. I also noticed that the posted code did not cover all cases.\n if (NotStarted < other.NotStarted) {\n return -1;\n } else if (NotStarted == other.NotStarted) {\n if (Started && !other.Started) {\n return -1;\n } else if (Started == other.NotStarted) {\n return 0;\n } else {\n return 1;\n }\n } else {\n return 1;\n }\n } else {\n throw new ArgumentException(\"Object is not a Server\");\n }\n }\n}\n</code></pre>\n\n<p>Now this is all you have to do to get the next server id.</p>\n\n<pre><code>public int getServerToSchedule() {\n using (PaEntities server = new PaEntities()) {\n List<Server> servers = new List<Server>();\n foreach (int paServer in GetPaServer()) {\n servers.Add(new Server(serverJobCount(server, paServer, \"Started\") == 1,\n serverJobCount(server, paServer, \"NotStarted\")));\n servers.Sort()\n return servers.First();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T13:04:18.933",
"Id": "15979",
"ParentId": "15975",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T11:13:37.193",
"Id": "15975",
"Score": "8",
"Tags": [
"c#",
"entity-framework"
],
"Title": "How to reduce my code length without changing concept?"
}
|
15975
|
<p>I understand that I should use prepared statements to prevent SQL injection. Unfortunately, having read the PHP docs on the matter I am none the wiser. Here is one of my simple active record SQL queries in a CI2 model, could someone show me an example of how I might turn this into a prepared statement - do I even need to?</p>
<pre><code>function get_item($id){
$this->db
->select('*')
->from('item_entries')
->where('item_entries.item_id', $id)
->join('item_categories_rel', 'item_categories_rel.item_id = item_entries.item_id');
$query = $this->db->get();
if(is_object($query)){return $query->result_array();}else{return $query;}
}
</code></pre>
<p>Am I correct in thinking prepared statements are only necessary if I am accepting user data - if so lets assume <code>$id</code> is user submitted. Although it is not, I am about to write some form to db statements, so advice in preparation for this is appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T16:26:30.347",
"Id": "26031",
"Score": "1",
"body": "Your code is fine, everything that goes through ActiveRecord is properly escaped. Unless you do your own where statements, things like `$this->db->where('col = ' . $value)`, you are safe."
}
] |
[
{
"body": "<p>I'm not really sure if this question is on topic, but I just started using SQL myself, so here's a chance for me to apply what I've learned. The following is using PDO.</p>\n\n<pre><code>//unspecified placeholder\n$sql = \"SELECT * FROM item_entries WHERE item_id=?\";\n$sth = $dbh->prepare( $sql );\n$sth->execute( array( $id ) );\n\n//specific placeholder\n$sql = \"SELECT * FROM item_entries WHERE item_id=:id\";\n$sth = $dbh->prepare( $sql );\n$sth->execute( array( ':id' => $id ) );\n</code></pre>\n\n<p>The idea being that the SQL statements don't have values directly injected into them by using placeholders. In the first example that placeholder was unspecified <code>?</code>. You can use any number of unspecified placeholders, but then the array you pass in to the <code>execute()</code> function has to be in the same order. While this may not be a big deal for one input, it could quickly become tedious trying to keep track of multiples. Which is where the second example comes in. It uses specific placeholders <code>:id</code> to define keys in the execution array. This means these elements can be in any order so long as the correct key is associated with the correct input.</p>\n\n<p>As for if this is only necessary for user data? I don't know, but I'm just as prone to make mistakes as users, so it couldn't hurt. I'm quite interested to here if I got this right as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T16:31:26.270",
"Id": "15987",
"ParentId": "15982",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T15:00:10.040",
"Id": "15982",
"Score": "3",
"Tags": [
"php",
"codeigniter",
"sql-injection"
],
"Title": "Codeigniter active record"
}
|
15982
|
<p>I thought it was a good idea to use this in my C++ projects:</p>
<pre><code>class CRAIICall
{
public:
typedef void (WINAPI * FnType)(HANDLE);
CRAIICall(HANDLE h, FnType fun)
: m_h(h), m_fun(fun)
{}
~CRAIICall() {
if (m_h) { m_fun(m_h); }
}
private:
HANDLE m_h;
FnType m_fun;
};
</code></pre>
<p>and use it like this in a function:</p>
<pre><code>HMODULE hSrClient = ::LoadLibraryW(L"srclient.dll");
CRAIICall(hSrClient, (CRAIICall::FnType)::FreeLibrary);
</code></pre>
<p>so that I can simply return from my function at any point, or throw exceptions.</p>
<p>Is it safe to cast a function pointer like this?</p>
|
[] |
[
{
"body": "<p>No it is not safe (It is undefined behavior):</p>\n\n<p>The called function may put stuff on the stack (or somewhere else) as the return value. Expecting the caller to deal with it at their end. If the caller does not deal with the return value appropriately then you have undefined behavior (the returned object may have a destructor that needs to be called for example).</p>\n\n<p>This line is probably not doing what you expect:</p>\n\n<pre><code>CRAIICall(hSrClient, (CRAIICall::FnType)::FreeLibrary);\n</code></pre>\n\n<p>This is creating a temporary object. Which goes out of scope at the end of the expression (the semicolon in this case). And thus the temporary objects destructor is getting called just after the constructor completes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T16:48:42.217",
"Id": "15989",
"ParentId": "15984",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "15989",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T15:55:51.400",
"Id": "15984",
"Score": "4",
"Tags": [
"c++",
"casting",
"raii"
],
"Title": "CRAIICall class"
}
|
15984
|
<p>I have a parent object (a display window) and it has a few child objects (buttons and controls on the window). I would like one child object to hide itself when another is clicked. Currently, I have my parent object bind to a custom event expected to be fired from the child object. Then, the parent object passes the command on to its other child.</p>
<p>Example:</p>
<pre><code>//Namespace for the 'Orders' page.
$(function Orders() {
"use strict";
var orders = $('#Orders');
var ordersSearchResult = new OrdersSearchResult();
var ordersSearchDisplay = new OrdersSearchDisplay();
var ordersEditDisplay = new OrdersEditDisplay();
ordersSearchResult.selector.bind('searchResultLinkClicked', function () {
ordersEditDisplay.hide();
ordersSearchDisplay.fadeIn();
});
});
</code></pre>
<p>I have two questions / concerns about this code:</p>
<ul>
<li>I expose a property called 'selector' for <code>ordersSearchResult</code>. This is a direct reference to the jQuery DOM element. As I understand it this is bad practice -- objects should expose methods to affect their DOM elements, but not the DOM elements themselves. Previously, I passed the <code>onSearchResultLinkClicked</code> anonymous function into a method of <code>ordersSearchResult</code> which bound the event to the selector internally. I felt that that implementation was counter-intuitive, though, as it did not read very clearly to see anonymous functions being passed into 'binding' methods.</li>
<li><code>ordersEditDisplay</code> and <code>ordersSearchDisplay</code> expose methods <code>hide()</code> and <code>fadeIn()</code> which affect their DOM elements, but <code>ordersEditDisplay</code>/<code>ordersSearchDisplay</code> are <strong>not</strong> DOM elements themselves. Is it bad practice to 'confuse' other developers like this? The code could read: <code>ordersEditDisplay.selector.hide()</code> but I did not want to expose the selector publically.</li>
</ul>
|
[] |
[
{
"body": "<p>It's really hard to judge if exposing <code>selector</code> is the <i>"right"</i> thing to do without reviewing more of your source code.\nAlso, it depends on your architecture design. If you're using a <a href=\"http://www.phpzag.com/php-model-view-controller-mvc/\" rel=\"nofollow noreferrer\">Model View Controller</a> approach, then yes. Elements associated with the view will be exposed.\nCheck out some of the examples for <a href=\"http://documentcloud.github.com/backbone/#View\" rel=\"nofollow noreferrer\">Backbone.js</a>.</p>\n<p>Here are some other factors that come into play:</p>\n<ul>\n<li>Coding standards</li>\n<li>size of your source</li>\n<li>how strictly you're required to follow Object Oriented Programming, OOP.</li>\n<li>who will maintain your code.</li>\n</ul>\n<p>The code you provided looks great. As long as you produce consistent readable code that has a good level of data abstraction and <b>works</b>, then you shouldn't worry about the small details.</p>\n<p>If you're still concerned about it though then just create an adapter for the <code>.bind()</code>.</p>\n<p>Old Code:</p>\n<pre><code>ordersSearchResult.selector.bind('searchResultLinkClicked', function () {\n ordersEditDisplay.hide();\n ordersSearchDisplay.fadeIn();\n});\n</code></pre>\n<p>New Code:</p>\n<pre><code>...\nOrdersSearchResult.prototype.bind = function(eventName, fn ){\n this.selector.bind( eventName, fn );\n};\n...\nvar ordersSearchResult = new OrdersSearchResult();\nordersSearchResult.bind('searchResultLinkClicked', function () {\n ordersEditDisplay.hide();\n ordersSearchDisplay.fadeIn();\n}); \n</code></pre>\n<p>Here are a few additional tips.</p>\n<h2>1) Name variables and properties based on their overall purpose and type.</h2>\n<blockquote>\nProgrammer A: There's a problem with orders in your code.<br/>\nProgrammer B: Which one? Are you talking about the function, jQuery object, element id, or something else?\n</blockquote>\n<p>To avoid this situation, create unique names assuming the language is case insensitive.</p>\n<p>Old code:</p>\n<pre><code>$(function Orders() {\n "use strict";\n var orders = $('#Orders');\n ...\n</code></pre>\n<p>New code:</p>\n<pre><code>$(function OrdersFunc() {\n "use strict";\n var $orders = $('#OrdersTable');\n ...\n</code></pre>\n<p>More info here: <a href=\"https://stackoverflow.com/questions/203618/how-to-name-variables\">"How to name variables"</a></p>\n<h2>2) Add the dollar sign as a prefix for jQuery variables.</h2>\n<p>It would make more sense to rename <code>selector</code> as <code>$el</code>.</p>\n<h2>3) Try not to create method names that are the same from a different library API.</h2>\n<p><code>ordersEditDisplay.hide()</code> sounds like <code>ordersEditDisplay</code> returns a jQuery object, but that isn't the case.\nInstead of <code>ordersEditDisplay.hide();</code>, try <code>ordersEditDisplay.hideView();</code></p>\n<h2>4) Use the Singleton Pattern or an object literal to create a namespace.</h2>\n<p>Great examples can be found <a href=\"https://stackoverflow.com/questions/1635800/javascript-best-singleton-pattern\">here</a></p>\n<h2>Final Code:</h2>\n<pre><code>var mySite = {};\nmySite.Orders = {};\nmySite.Orders.init = function() {\n "use strict";\n var $orders = $('#OrdersTable');\n\n var ordersSearchResult = new OrdersSearchResult();\n var ordersSearchDisplay = new OrdersSearchDisplay();\n var ordersEditDisplay = new OrdersEditDisplay();\n\n ordersSearchResult.$el.bind('searchResultLinkClicked', function () {\n ordersEditDisplay.hideView();\n ordersSearchDisplay.fadeInView();\n });\n};\n$(mySite.Orders.init);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T20:25:54.290",
"Id": "25986",
"Score": "0",
"body": "I appreciate your thorough response. Parts of it I have applied to my code, but I can't help but feel that the final code has changed stylistically, but not structurally. While it is more clear that a jQuery element is exposed -- the true issue hasn't been resolved. Is it standard to expose jQuery elements publicly from objects? It does not seem that way to me. I think the hideView over hide suggestion is a very strong improvement. Naming standards are always tricky, but I definitely appreciate the points you've made."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T21:39:18.163",
"Id": "25989",
"Score": "1",
"body": "@SeanAnderson Updated my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T18:47:35.963",
"Id": "15993",
"ParentId": "15986",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15993",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T16:22:13.837",
"Id": "15986",
"Score": "5",
"Tags": [
"javascript",
"jquery"
],
"Title": "Having a parent respond to a child's event"
}
|
15986
|
<p>I have been doing server-side development for a couple of years, but I am just now getting into doing some client-side programming. As a JavaScript exercise, I created a dead-simple jQuery image slider plugin, but I don't know if I did it the "right" way.</p>
<p>Specifically, I was wondering what improvements ought to be made to make the code clearer and more self-documenting. Also, are their any places where I have "re-invented the wheel" where I could have used the JS (or jQuery) standard library? Feel free to point out any glaring deficiencies, egregious oversights, or logical aberrations.</p>
<pre><code>(function ($) {
$.fn.sliderize = function( options ) {
var settings = $.extend({
srcAttrib: "src", // data attribute containing image source
delayTime: 6000,
transitionTime: 1000,
randomize: false, // "randomize" the slides
width: 700,
height: 276
}, options);
// If we don't do this, then the plugin can throw the browser into an infinite loop :-o
if (this.length === 0 || this.find('img').length === 0) {
return new Array();
};
var images = new Array(),
statePlaying = true,
currentIndex = 0;
enqueue = function($image) {
images.push($image);
}
nextImg = function() {
// Check to see if random setting is on
if (settings.randomize) {
// Selects a "random" index... ensures that the same slide does not display 2x in a row
while(true) {
candidateIndex = Math.floor(Math.random() * (images.length - 1));
if (candidateIndex !== currentIndex) {
currentIndex = candidateIndex;
break;
}
}
} else if (currentIndex === images.length - 1) {
// If we're at the end, then get the first image again
currentIndex = 0;
} else {
// Otherwise, increment the index
currentIndex++;
}
// Implement a crude form of preloading, loading 1 image in advance
if (images[currentIndex].data('loaded') !== true) {
theSrc = images[currentIndex].data(settings.srcAttrib);
images[currentIndex].attr('src', theSrc)
.data('loaded', true)
.css({
position: "absolute",
top: 0,
left: 0,
margin: 0
});
}
return images[currentIndex];
}
playShow = function($img) {
if (statePlaying === false) return;
$img.fadeIn(settings.transitionTime / 2, function() {
$nextImg = nextImg();
setTimeout(function() {
$img.fadeOut(settings.transitionTime / 2, function() {
playShow($nextImg);
});
}, settings.delayTime - settings.transitionTime);
});
};
// LOOP THROUGH IMAGES AND ADD THEM TO THE QUEUE
this.find('img').each(function() {
enqueue($(this));
$(this).hide();
});
// Ensure that the container element is position relatively
this.css({
width: settings.width,
height: settings.height,
position: 'relative'
}).addClass('loading');
currentIndex = -1;
setTimeout(playShow(nextImg()), 0);
// Maintain chainability
return this;
};
})(jQuery);
</code></pre>
<p>And here is an example of the usage:</p>
<pre><code><div id="slider-container">
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
data-src="img/1.jpg" />
<!-- ...More images -->
</div>
<!-- ...cut... -->
<script type="text/javascript">
jQuery(document).ready(function() {
$('#slider-container').sliderize({randomize: true});
});
</script>
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>It's more idiomatic to use <code>[]</code> rather than <code>new Array()</code></p></li>\n<li><p>You should use <code>var</code> with your functions too. E.g. </p>\n\n<pre><code>var enqueue = function($image) {\n images.push($image);\n}\n</code></pre>\n\n<p>Otherwise you're defining them in the global scope. Similarly <code>candidateIndex</code>, <code>theSrc</code>, ... <a href=\"http://www.jslint.com/\" rel=\"nofollow\">JSLint</a> is your friend.</p></li>\n<li><p><code>candidateIndex = Math.floor(Math.random() * (images.length - 1));</code></p>\n\n<p>has an out-by-one bug: it cannot select the last image. Of course, if you want to be clever you can replace the (fixed)</p>\n\n<pre><code>while(true) {\n candidateIndex = Math.floor(Math.random() * (images.length));\n if (candidateIndex !== currentIndex) {\n currentIndex = candidateIndex;\n break;\n }\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>candidateIndex = Math.floor(Math.random() * (images.length - 1));\nif (candidateIndex >= currentIndex) candidateIndex++;\n</code></pre></li>\n<li><p>Although not many people do it, it's best practice to use string literals for object keys. E.g. instead of</p>\n\n<pre><code>{\n position: \"absolute\",\n top: 0,\n left: 0,\n margin: 0\n}\n</code></pre>\n\n<p>you would have</p>\n\n<pre><code>{\n \"position\": \"absolute\",\n \"top\": 0,\n \"left\": 0,\n \"margin\": 0\n}\n</code></pre></li>\n<li><p>Variable names prefixed with <code>$</code> are somewhat unusual.</p></li>\n<li><p>In defining the plugin you used the name avoidance strategy, but when using it you don't. The reason for wrapping the plugin definition in</p>\n\n<pre><code>(function($){\n ...\n})(jQuery);\n</code></pre>\n\n<p>is that some other library may have defined <code>$</code>. It would be advisable to use the same boilerplate when invoking the plugin:</p>\n\n<pre><code>(function($){\n $(document).ready(function() {\n $('#slider-container').sliderize({randomize: true});\n });\n})(jQuery);\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T14:40:00.957",
"Id": "26021",
"Score": "0",
"body": "Thank you. That was very helpful! About #4, why is it preferred to use string literals for keys?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T14:54:54.897",
"Id": "26023",
"Score": "0",
"body": "@Andrew, because if your keys are language keywords, you *have* to use string literals; if you always use string literals you don't have to remember which are the special cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T19:59:54.913",
"Id": "26039",
"Score": "0",
"body": "re: #5, it's very common to prefix variables with a $ when they reference jquery objects. See here: http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T20:15:20.757",
"Id": "26040",
"Score": "0",
"body": "@pulazzo, thanks for the link. I'm not a big fan of Hungarian notation, but I suppose it has its place in dynamically typed languages."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T07:02:14.007",
"Id": "16001",
"ParentId": "15988",
"Score": "4"
}
},
{
"body": "<p>Here are some tips:</p>\n\n<h2>1) Fail as soon as possible.</h2>\n\n<p>Place your if guard at the top of the function.</p>\n\n<p>Old Code:</p>\n\n<pre><code>$.fn.sliderize = function (options) {\n ... code\n if (this.length === 0 || this.find('img').length === 0) {\n return [];\n };\n ... more code\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>$.fn.sliderize = function (options) {\n if (this.length === 0 || this.find('img').length === 0) {\n return [];\n };\n ... more code\n</code></pre>\n\n<h2>2) Use truthy and falsely</h2>\n\n<pre><code>Boolean(undefined); // => false\nBoolean(null); // => false\nBoolean(false); // => false\nBoolean(0); // => false\nBoolean(\"\"); // => false\nBoolean(NaN); // => false\n\nBoolean(1); // => true\nBoolean([1,2,3]); // => true\nBoolean(function(){}); // => true\n</code></pre>\n\n<p>Take from <a href=\"http://james.padolsey.com/javascript/truthy-falsey/\">http://james.padolsey.com/javascript/truthy-falsey/</a></p>\n\n<p>Old Code:</p>\n\n<pre><code>if (images[currentIndex].data('loaded') === false ) {\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>if (!images[currentIndex].data('loaded')) { \n</code></pre>\n\n<h2>3) Use <code>jQuery.delay()</code> instead of <code>window.setTimeout()</code>.</h2>\n\n<p>Doc for <a href=\"http://api.jquery.com/delay/\">jQuery.delay()</a></p>\n\n<p>Old Code:</p>\n\n<pre><code>$img.fadeIn(settings.transitionTime / 2, function () {\n $nextImg = nextImg();\n setTimeout(function () {\n $img.fadeOut(settings.transitionTime / 2, function () {\n playShow($nextImg);\n });\n }, settings.delayTime - settings.transitionTime);\n}); \n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var fadeDelay = settings.transitionTime / 2;\n$img.fadeIn(fadeDelay, function () {\n $nextImg = nextImg();\n})\n.delay(settings.delayTime - settings.transitionTime)\n.fadeOut(fadeDelay, function () {\n playShow($nextImg);\n});\n</code></pre>\n\n<h2>4) <code>window.setTimeout()</code> requires a function.</h2>\n\n<p>The function passed to <code>.setTimeout()</code> auto starts, which doesn't make any sense.</p>\n\n<p>Old Code:</p>\n\n<pre><code>setTimeout(playShow(nextImg()), 0);\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>playShow(nextImg());\n</code></pre>\n\n<h2>5) <code>candidateIndex</code> and <code>theSrc</code> are global. Make sure to define them.</h2>\n\n<h2>6) Only set <code>currentIndex</code> once.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>var currentIndex = 0;\n...\ncurrentIndex = -1;\n</code></pre>\n\n<p>New Code: </p>\n\n<pre><code>var currentIndex = -1;\n</code></pre>\n\n<h2>7) Have a function that returns the current image wrapped inside a jQuery.</h2>\n\n<p>This way if you have a bug in your program you can fail silently instead of crashing the javascript environment.</p>\n\n<p>Code:</p>\n\n<pre><code>Sliderize.prototype.getCurrentImage = function () {\n return $(this.images[this.currentIndex]);\n};\n</code></pre>\n\n<h2>8) <code>settings.randomize</code> should always be false if there is only one image.</h2>\n\n<p>Otherwise there will be an infinite loop when trying to get a random index.</p>\n\n<h2>9) Don't crame everything inside <code>$.fn.sliderize</code>.</h2>\n\n<p>The reasons is because each call to <code>.sliderize()</code> will recreate everything inside that function. And plus functions longer than 10 lines cause confusion.\nYou could make an object to store all that functionality. Refer to the final code as a reference.\nExample:</p>\n\n<pre><code>$.fn.sliderize = function (options) {\n if ($(this).find('img').length) {\n var obj = new Sliderize(options);\n obj.attachTo($(this));\n obj.playShow();\n }\n return this;\n};\n</code></pre>\n\n<h2>10) Return <code>this</code> in jQuery plugins.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>if (!this.length || !this.find('img').length) {\n return [];\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>if( !$(this).find(\"img\").length ){\n return this;\n}\n</code></pre>\n\n<h2>11) Make complex functions testable.</h2>\n\n<p>nextImg is too long and hard to understand. Break this up into smaller functions.</p>\n\n<p>Here's one part you can break up.\nOld Code:</p>\n\n<pre><code>if (settings.randomize) {\n // Selects a \"random\" index... ensures that the same slide does not display 2x in a row\n while(true) {\n candidateIndex = Math.floor(Math.random() * (images.length - 1));\n if (candidateIndex !== currentIndex) {\n currentIndex = candidateIndex;\n break;\n }\n }\n} else if (currentIndex === images.length - 1) {\n // If we're at the end, then get the first image again\n currentIndex = 0;\n} else {\n // Otherwise, increment the index\n currentIndex++;\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>Sliderize.getNextIndex = function (i, len, isRandom) {\n if (isRandom && 1 < len) {\n var oldI = i;\n while (i === oldI) {\n i = Math.floor(Math.random() * len);\n }\n } else {\n i++;\n }\n return (len <= i) ? 0 : i;\n};\nSliderize.prototype.updateIndex = function () {\n this.currentIndex = Sliderize.getNextIndex(this.currentIndex, this.images.length, this.settings.randomize);\n};\n</code></pre>\n\n<p>Sample Testcase for <code>Sliderize.getNextIndex()</code>. If you're really serious about testing then use qUnit or another javascript testing framework.</p>\n\n<pre><code>var fn = Sliderize.getNextIndex;\nconsole.log( \"test `Sliderize.getNextIndex` without randomness\" );\nconsole.log( fn(0,5, false) === 1 );\nconsole.log( fn(1,5, false) === 2 );\nconsole.log( fn(4,5, false) === 0 );\n\nconsole.log( \"test `Sliderize.getNextIndex` with randomness\" );\nconsole.log( fn(0,5, true) !== 0 );\nconsole.log( fn(1,5, true) !== 1 );\nconsole.log( fn(4,5, true) !== 4 );\n\nconsole.log( \"test `Sliderize.getNextIndex` at odd conditions\" );\nconsole.log( fn(5,5, false) === 0 );\nconsole.log( fn(0,1, true) === 0 );\nconsole.log( fn(0,1, false) === 0 );\n</code></pre>\n\n<h2>12) Delete <code>enqueue</code> since it's too simple and doesn't seem useful.</h2>\n\n<p>Old Code:</p>\n\n<pre><code>enqueue = function ($image) {\n images.push($image);\n}\n...\n// LOOP THROUGH IMAGES AND ADD THEM TO THE QUEUE\nthis.find('img').each(function () {\n enqueue($(this));\n $(this).hide();\n});\n</code></pre>\n\n<p>New Code A:</p>\n\n<pre><code>// LOOP THROUGH IMAGES AND ADD THEM TO THE QUEUE\nthis.find('img').each(function () {\n images.push($(this));\n $(this).hide();\n});\n</code></pre>\n\n<p>New Code A can be further simplified by remembing that jQuery methods operate on a collection of jQuery objects and that collections can be converted to an array.</p>\n\n<p>New Code B:</p>\n\n<pre><code>images = images.concat( \n this.find('img').hide().toArray() \n);\n</code></pre>\n\n<h2>Final Code:</h2>\n\n<pre><code>(function ($) {\n var Sliderize = function (options) {\n this.images = [];\n this.statePlaying = true;\n this.currentIndex = 0;\n this.settings = $.extend({\n srcAttrib : \"src\",\n delayTime : 1000,\n transitionTime : 2000,\n randomize : false,\n width : 700,\n height : 276\n }, options);\n };\n Sliderize.getNextIndex = function (i, len, isRandom) {\n if (isRandom && 1 < len) {\n var oldI = i;\n while (i === oldI) {\n i = Math.floor(Math.random() * len);\n }\n } else {\n i++;\n }\n return (len <= i) ? 0 : i;\n };\n Sliderize.prototype.updateIndex = function () {\n this.currentIndex = Sliderize.getNextIndex(this.currentIndex, this.images.length, this.settings.randomize);\n };\n\n Sliderize.prototype.nextImg = function () {\n this.updateIndex();\n var currentImage = this.getCurrentImage();\n if (!currentImage.data('loaded')) {\n currentImage.attr('src', currentImage.data(this.settings.srcAttrib))\n .data('loaded', true).css({\n position : \"absolute\",\n top : 0,\n left : 0,\n margin : 0\n });\n }\n };\n Sliderize.prototype.getCurrentImage = function () {\n return $(this.images[this.currentIndex]);\n };\n Sliderize.prototype.playShow = function () {\n if (this.statePlaying) {\n var that = this,\n fadeDelay = this.settings.transitionTime / 2;\n this.getCurrentImage()\n .fadeIn(fadeDelay)\n .delay(this.settings.delayTime - this.settings.transitionTime)\n .fadeOut(fadeDelay, function () {\n that.nextImg();\n that.playShow();\n });\n }\n };\n Sliderize.prototype.addImagesToQueue = function ($imgs) {\n this.images = this.images.concat( \n $imgs.hide().toArray() \n );\n };\n Sliderize.prototype.changeElementToLoading = function ($el) {\n $el.css({\n width : this.settings.width,\n height : this.settings.height,\n position : 'relative'\n }).addClass('loading');\n };\n Sliderize.prototype.attachTo = function( $el ){\n this.addImagesToQueue($el.find('img'));\n this.changeElementToLoading($el);\n };\n $.fn.sliderize = function (options) {\n if ($(this).find('img').length) {\n var obj = new Sliderize(options);\n obj.attachTo( $(this) );\n obj.playShow();\n }\n return this;\n };\n})(jQuery);\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/Whtad/1/\">http://jsfiddle.net/Whtad/1/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-07T01:07:36.323",
"Id": "26465",
"Score": "0",
"body": "Thank you so much! Your suggestions were extremely helpful! Having never used JavaScript as an OO language, thinking in terms of objects is not to natural for me in JS. It certainly makes for cleaner, more extensible code though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:59:05.750",
"Id": "16014",
"ParentId": "15988",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "16001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T16:40:43.440",
"Id": "15988",
"Score": "11",
"Tags": [
"javascript",
"jquery"
],
"Title": "Trying to learn idiomatic JavaScript and jQuery"
}
|
15988
|
<p>I've implemented the following two versions of the classic <a href="http://en.wikipedia.org/wiki/Maximum_subarray_problem" rel="nofollow">"Max Sub-Array" problem</a> in Clojure, using the Kadane algorithm.</p>
<p>First with <code>loop</code> / <code>recur</code></p>
<pre class="lang-lisp prettyprint-override"><code>(defn max-sub-array [A]
(loop [x (first A)
a (rest A)
max-ending-here 0
max-so-far 0]
(if (seq a)
(recur (first a) (rest a) (max x, (+ max-ending-here x)) (max max-so-far, max-ending-here))
max-so-far)))
</code></pre>
<p>Then with <code>reduce</code></p>
<pre class="lang-lisp prettyprint-override"><code>(defn max-sub-array-reduction [A]
(letfn [(find-max-sub-array [[max-ending-here max-so-far] x]
[(max x (+ max-ending-here x)) (max max-so-far max-ending-here)])]
(second (reduce find-max-sub-array [0 0] A))))
</code></pre>
<p>Is there a more concise implementation, perhaps using <code>filter</code> or merely by making the <code>reduce</code> version more "idiomatic" somehow?</p>
|
[] |
[
{
"body": "<p>I think your implementations are succinct and straightforward.\nHowever, I prefer using primitives for loop args to avoid auto-boxing:</p>\n\n<pre><code>(defn maximum-subarray\n [^longs ls]\n (loop [i 0, meh 0, msf 0] ; index, max-ending-here, max-so-far\n (if (< i (alength ls))\n (recur (inc i) (max (+ meh (aget ls i)) 0) (max msf meh))\n msf)))\n</code></pre>\n\n<p>This function assumes a <code>longs</code> argument:</p>\n\n<pre><code>user> (def a (long-array [31 -41 59 26 -53 58 97 -93 -23 84]))\n#'user/a\nuser> (maximum-subarray a)\n187\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T13:24:13.767",
"Id": "16033",
"ParentId": "15992",
"Score": "0"
}
},
{
"body": "<p>Great answer from Jean Niklas L'Orange <a href=\"https://groups.google.com/d/topic/clojure/J-L3BUTaJ3E/discussion\" rel=\"nofollow\">on the Clojure Google Group</a>:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defn max-subarray [A]\n (let [pos+ (fn [sum x] (if (neg? sum) x (+ sum x)))\n ending-heres (reductions pos+ 0 A)]\n (reduce max ending-heres)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T04:02:45.110",
"Id": "16066",
"ParentId": "15992",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16066",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T18:38:06.190",
"Id": "15992",
"Score": "2",
"Tags": [
"clojure"
],
"Title": "More concise and/or idiomatic max subarray in Clojure?"
}
|
15992
|
<p>I'm new to Java and have been reading <em>Java for Dummies</em> and other ones as well. I've started building this program like a week ago. I'm sure it's very messy. Just seeing if someone can clean it up and show easier ways of doing things. I have like 4 classes, but I'll just post the main class and a subclass for now.</p>
<p>Here is my <code>BankMain</code> class...</p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
public class BankMain
{
private double availableBal =80;
private double totalBal =100;
static ArrayList<Integer> cardNum = new ArrayList<Integer>();
static Scanner input = new Scanner(System.in);
private String error; //String the error from the exception
{
error = "error";
}
public static void cardNumbers(){
Scanner input = new Scanner(System.in);
try{
System.out.println("Please select a 5 digit card number");
int num = input.nextInt();
checkNumber(num);
}
catch(invalidNumber err){
System.out.println("Caught Error: " + err.getError());
contC();
}
}
public static void contC(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Type 'c' to enter number again.");
String value = keyboard.next();
if(value.equalsIgnoreCase("c")){
cardNumbers();
}
else if (!keyboard.equals('c')){
System.out.println("Invalid Entry!");
}
}
public static void menu(){
System.out.println("ATM Menu:");
System.out.println();
System.out.println("1 = Create Account");
System.out.println("2 = Account Login");
System.out.println("3 = Exit ATM");
query();
}
public void startAtm()
{
menu();
}
public void drawMainMenu()
{
AccountMain main3 = new AccountMain();
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
switch(selection)
{
case 1:
viewAccountInfo();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
public void viewAccountInfo()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $"+totalBal);
System.out.println("\t--Available balance: $"+availableBal);
drawMainMenu();
}
public void deposit(int depAmount)
{
System.out.println("\n***Please insert your money now...***");
totalBal =totalBal +depAmount;
availableBal =availableBal +depAmount;
}
public void checkNsf(int withdrawAmount)
{
if(totalBal -withdrawAmount < 0)
System.out.println("\n***ERROR!!! Insufficient funds in you accout***");
else
{
totalBal =totalBal -withdrawAmount;
availableBal =availableBal -withdrawAmount;
System.out.println("\n***Please take your money now...***");
}
}
public void addFunds()
{
int addSelection;
System.out.println("Deposit funds:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
addSelection =input.nextInt();
switch(addSelection)
{
case 1:
deposit(20);
drawMainMenu();
break;
case 2:
deposit(40);
drawMainMenu();
break;
case 3:
deposit(60);
drawMainMenu();
break;
case 4:
deposit(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}
public void withdraw()
{
try{
int withdrawSelection;
System.out.println("Withdraw money:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
withdrawSelection =input.nextInt();
switch(withdrawSelection)
{
case 1:
checkAmount(20);
drawMainMenu();
break;
case 2:
checkAmount(40);
drawMainMenu();
break;
case 3:
checkAmount(60);
drawMainMenu();
break;
case 4:
checkAmount(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
default:
System.out.println("Invalid choice.");
withdraw();
}
}
catch(invalidAmount err){
System.out.println("Caught Error: " + err.getError());
viewAccountInfo();
}
}
public static void query(){
Scanner keyboard = new Scanner(System.in);
while (!keyboard.hasNextInt()) {
System.out.println("Invalid choice.");
menu();
}
int input = keyboard.nextInt();
if (input == 2){
BankMainPart2 main2 = new BankMainPart2();
System.out.println("Please enter your 5 digit card number.");
BankMainPart2.loginCard(cardNum);
}
else if (input == 1){
cardNumbers();
}
else if (input == 3){
System.out.println("Thank you, have a nice day!");
System.exit(0);
}
}
private static void checkNumber(int num) throws invalidNumber
//run the check activation exception
{
Scanner keyboard = new Scanner(System.in);
if(String.valueOf(num).length()!=5)
{
throw new invalidNumber("invalid number");
}
else {
cardNum.add(num);
System.out.println("Thank you! You're card number is " +num);
contC2();
}
}
private void checkAmount(int withdrawAmount) throws invalidAmount
//run the check activation exception
{
if(totalBal -withdrawAmount < 0)
{
throw new invalidAmount("\n***ERROR!!! Insufficient funds in you accout***");
}
else
{
totalBal =totalBal -withdrawAmount;
availableBal =availableBal -withdrawAmount;
System.out.println("\n***Please take your money now...***");
}
}
public static void contC2(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Type 'c' to return to main menu.");
String value = keyboard.next();
if(value.equalsIgnoreCase("c")){
menu();
}
else if (!keyboard.equals('c')){
System.out.println("Invalid Entry!");
contC2();
}
}
public static void main(String args[])
{
BankMain myAtm = new BankMain();
BankMainSub sub = new BankMainSub();
myAtm.startAtm();
}
}
</code></pre>
<p>Here is my subclass...</p>
<pre><code>public class BankMainSub extends BankMain {
private double availableBal3 =500;
private double totalBal3 =520;
public void businessAccount()
{
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
switch(selection)
{
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
default:
System.out.println("Invalid choice.");
businessAccount();
}
}
public void addFunds3()
{
int addSelection;
System.out.println("Deposit funds:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
addSelection = input.nextInt();
switch(addSelection)
{
case 1:
deposit2(20);
businessAccount();
break;
case 2:
deposit2(40);
businessAccount();
break;
case 3:
deposit2(60);
businessAccount();
break;
case 4:
deposit2(100);
businessAccount();
break;
case 5:
businessAccount();
break;
}
}
public void withdraw3()
{
int withdrawSelection;
System.out.println("Withdraw money:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
withdrawSelection =input.nextInt();
switch(withdrawSelection)
{
case 1:
checkNsf3(20);
businessAccount();
break;
case 2:
checkNsf3(40);
businessAccount();
break;
case 3:
checkNsf3(60);
businessAccount();
break;
case 4:
checkNsf3(100);
businessAccount();
break;
case 5:
businessAccount();
break;
}
}
public void viewAccountInfo3()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $"+totalBal3);
System.out.println("\t--Available balance: $"+availableBal3);
businessAccount();
}
public void deposit2(int depAmount)
{
System.out.println("\n***Please insert your money now...***");
totalBal3 =totalBal3 +depAmount;
availableBal3 =availableBal3 +depAmount;
}
public void checkNsf3(int withdrawAmount)
{
if(totalBal3 -withdrawAmount < 0)
System.out.println("\n***ERROR!!! Insufficient funds in you accout***");
else
{
totalBal3 =totalBal3 -withdrawAmount;
availableBal3 =availableBal3 -withdrawAmount;
System.out.println("\n***Please take your money now...***");
}
}
}
</code></pre>
<p>Here is <code>AccountMain</code>...</p>
<pre><code>import java.util.Scanner;
public class AccountMain {
public static void selectAccount(){
System.out.println("Which account would you like to access?");
System.out.println();
System.out.println("1 = Business Account ");
System.out.println("2 = Savings Account");
System.out.println("3 = Checkings Account");
System.out.println("4 = Return to Main Menu");
menuAccount();
}
public static void menuAccount(){
BankMain main = new BankMain();
BankMainSub sub = new BankMainSub();
BankMainPart3 main5 = new BankMainPart3();
Scanner account = new Scanner(System.in);
while (!account.hasNextInt()) {
System.out.println("Invalid choice.");
selectAccount();
}
int actNum = account.nextInt();
if (actNum == 1){
System.out.println("*Business Account*");
sub.businessAccount();
}
else if (actNum == 2){
System.out.println("*Savings Account*");
main.drawMainMenu();
}
else if (actNum == 3){
System.out.println("*Checkings Account*");
main5.checkingsAccount();
}
else if (actNum == 4){
BankMain.menu();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T20:10:27.100",
"Id": "25981",
"Score": "2",
"body": "Rule number 1: Don't repeat yourself. Rule number 2: Read more books. Try this http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-07T03:18:54.173",
"Id": "168735",
"Score": "0",
"body": "To continue what @LarryBattle said: Rule #3: DON'T REPEAT YOURSELF"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-11T20:08:11.840",
"Id": "304062",
"Score": "0",
"body": "Think of your `Main` class as the driver for the rest of your program. Don't make that top/main class the bank. Instead Main is where you instantiate and use your bank and other objects."
}
] |
[
{
"body": "<p>A few random notes:</p>\n\n<ol>\n<li><p>Floating point values are not precise. You should use <code>BigDecimal</code>s for the balance instead of <code>double</code>. Some useful reading:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">Why not use Double or Float to represent currency?</a></li>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n</ul></li>\n<li><p>Lots of methods calls each other recursively. Some possible code paths:</p>\n\n<ul>\n<li><code>menu</code> -> <code>query</code> -> <code>menu</code></li>\n<li><code>query</code> -> <code>cardNumbers</code> -> <code>checkNumber</code> -> <code>contC2</code> -> <code>menu</code></li>\n</ul>\n\n<p>If a user uses the application long enough they will get a <code>StackOverflowError</code> sooner or later. You should use loops to get the user's input and don't call again recursively the menu printer method from the input handler. </p>\n\n<p>A possible main menu method:</p>\n\n<pre><code>while (true) {\n print main menu\n read input\n if input invalid {\n continue\n }\n handle input (call submenu methods)\n}\n</code></pre>\n\n<p>A possible submenu method:</p>\n\n<pre><code>while (true) {\n print submenu\n read input\n if input invalid {\n continue\n }\n if user chose exit submenu {\n return\n }\n handle input\n}\n</code></pre></li>\n<li><p><code>BankMain</code> create new <code>Scanner</code>s in every method although it already has one in its <code>input</code> field.</p></li>\n<li><pre><code>private String error; // String the error from the exception\n{\n error = \"error\";\n}\n</code></pre>\n\n<p>The following is the same:</p>\n\n<pre><code>private String error = \"error\";\n</code></pre></li>\n<li><p><code>invalidAmount</code> should be <code>InvalidAmountException</code> (<em>Effective Java, 2nd Edition, Item 56: Adhere to generally accepted naming conventions</em>)</p></li>\n<li><pre><code>ArrayList<Integer> cardNum = new ArrayList<Integer>();\n</code></pre>\n\n<p>should be </p>\n\n<pre><code> List<Integer> cardNum = new ArrayList<Integer>();\n</code></pre>\n\n<p>(<em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em>)</p></li>\n<li><p>Comments like this are really hard to read on smaller screens because of the horizontal scrolling and the unnecessary spaces:</p>\n\n<pre><code>private static void checkNumber(int num) throws invalidNumber //run the check activation exception\n</code></pre>\n\n<p>You could put it above the method declaration.</p></li>\n<li>\n\n<pre><code>if (totalBal - withdrawAmount < 0) {\n throw new invalidAmount(\"\\n***ERROR!!! Insufficient funds in you accout***\");\n} else {\n totalBal = totalBal - withdrawAmount;\n availableBal = availableBal - withdrawAmount;\n System.out.println(\"\\n***Please take your money now...***\");\n}\n</code></pre>\n\n<p>If you throw an exception the else block is unnecessary, it could be this:</p>\n\n<pre><code>if (totalBal - withdrawAmount < 0) {\n throw new invalidAmount(\"\\n***ERROR!!! Insufficient funds in you accout***\");\n}\ntotalBal = totalBal - withdrawAmount;\navailableBal = availableBal - withdrawAmount;\nSystem.out.println(\"\\n***Please take your money now...***\");\n</code></pre>\n\n<p>It's often called as <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause</a>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T09:22:03.520",
"Id": "26005",
"Score": "0",
"body": "Actually, the last one is not quite right. The OP had it right. In your version, everything after the `if` block is executed regardless of whether the Exception was thrown or not. This is NOT the desired behaviour."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T10:15:01.480",
"Id": "26009",
"Score": "1",
"body": "@SoboLAN: When an exception is thrown the control returns to the caller or to the try/finally block so those statements do not run."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T11:35:22.103",
"Id": "26012",
"Score": "1",
"body": "Actually yes, you're right. I would be right if that was a `try/catch`, not a `throw new Exception` statement."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T20:11:56.170",
"Id": "15995",
"ParentId": "15994",
"Score": "10"
}
},
{
"body": "<p>You have good practice for coding in response already done.</p>\n\n<p>I would point out concept concern.</p>\n\n<p>If you use Java, do not use <code>ksh</code> or <code>c-shell</code> procedural paradigme.</p>\n\n<p>Because of ATM constraint, all your constant values (like 20, 40, 60, 100) have to be in an <code>Interface</code> and never hard coded in an other place. [in a normal environment they can be put in <code>aFile.properties</code>]</p>\n\n<p>Use an Enum for binding 1 and 20, 2 and 40 and so on</p>\n\n<p>So you can print for all Enum.values(), and always with the good choice in front of the value</p>\n\n<p>Read, and try samples from Effective Java, this book is <em>inevitable</em>, with another one to understand <em>Pattern Design</em> (Of all those that I was able to read, this is one who gave me the click, to understand the functioning of the design pattern) : <a href=\"http://shop.oreilly.com/product/9780596007126.do\" rel=\"nofollow\">Head first Design Pattern</a></p>\n\n<p>It begins with <code>Observer</code> pattern. With it, you have to remove <code>switch</code> and other <code>if</code> revealing a way to think the solution for the future, and not transmit the problem to the objects build to solve them.</p>\n\n<p>Another point : search in Effective Java <code>StringBuilder</code> </p>\n\n<p>With those two books you will avoid all beginner mistakes, and raise rapidly Java professionnal status.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-11T19:59:44.333",
"Id": "304059",
"Score": "0",
"body": "Ditto on the \"Head First Design Patterns\" book. In fact the \"Head First\" books in general are good learning tools IMO."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T07:20:54.610",
"Id": "16002",
"ParentId": "15994",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T19:18:57.983",
"Id": "15994",
"Score": "10",
"Tags": [
"java",
"beginner",
"finance"
],
"Title": "Bank ATM program"
}
|
15994
|
<p>I'm trying to write a matlab function that creates random, smooth trajectories in a square of finite side length. Here is my current attempt at such a procedure: </p>
<pre><code>function [] = drawroutes( SideLength, v, t)
%DRAWROUTES Summary of this function goes here
% Detailed explanation goes here
%Some parameters intended to help help keep the particles in the box
RandAccel=.01;
ConservAccel=0;
speedlimit=.1;
G=10^(-8);
%
%Initialize Matrices
Ax=zeros(v,10*t);
Ay=Ax;
vx=Ax;
vy=Ax;
x=Ax;
y=Ax;
sx=zeros(v,1);
sy=zeros(v,1);
%
%Define initial position in square
x(:,1)=SideLength*.15*ones(v,1)+(SideLength*.7)*rand(v,1);
y(:,1)=SideLength*.15*ones(v,1)+(SideLength*.7)*rand(v,1);
%
for i=2:10*t
%Measure minimum particle distance component wise from boundary
%for each vehicle
BorderGravX=[abs(SideLength*ones(v,1)-x(:,i-1)),abs(x(:,i-1))]';
BorderGravY=[abs(SideLength*ones(v,1)-y(:,i-1)),abs(y(:,i-1))]';
rx=min(BorderGravX)';
ry=min(BorderGravY)';
%
%Set the sign of the repulsive force
for k=1:v
if x(k,i)<.5*SideLength
sx(k)=1;
else
sx(k)=-1;
end
if y(k,i)<.5*SideLength
sy(k)=1;
else
sy(k)=-1;
end
end
%
%Calculate Acceleration w/ random "nudge" and repulive force
Ax(:,i)=ConservAccel*Ax(:,i-1)+RandAccel*(rand(v,1)-.5*ones(v,1))+sx*G./rx.^2;
Ay(:,i)=ConservAccel*Ay(:,i-1)+RandAccel*(rand(v,1)-.5*ones(v,1))+sy*G./ry.^2;
%
%Ad hoc method of trying to slow down particles from jumping outside of
%feasible region
for h=1:v
if abs(vx(h,i-1)+Ax(h,i))<speedlimit
vx(h,i)=vx(h,i-1)+Ax(h,i);
elseif (vx(h,i-1)+Ax(h,i))<-speedlimit
vx(h,i)=-speedlimit;
else
vx(h,i)=speedlimit;
end
end
for h=1:v
if abs(vy(h,i-1)+Ay(h,i))<speedlimit
vy(h,i)=vy(h,i-1)+Ay(h,i);
elseif (vy(h,i-1)+Ay(h,i))<-speedlimit
vy(h,i)=-speedlimit;
else
vy(h,i)=speedlimit;
end
end
%
%Update position
x(:,i)=x(:,i-1)+(vx(:,i-1)+vx(:,i))/2;
y(:,i)=y(:,i-1)+(vy(:,i-1)+vy(:,1))/2;
%
end
%Plot position
clf;
hold on;
axis([-100,SideLength+100,-100,SideLength+100]);
cc=hsv(v);
for j=1:v
plot(x(j,1),y(j,1),'ko')
plot(x(j,:),y(j,:),'color',cc(j,:))
end
hold off;
%
end
</code></pre>
<p>My original plan was to place particles within a square, and move them around by allowing their acceleration in the x and y direction to be governed by a uniformly distributed random variable. To keep the particles within the square, I tried to create a repulsive force that would push the particles away from the boundaries of the square.
In practice, the particles tend to leave the desired "feasible" region after a relatively small number of time steps (say, 1000)."</p>
<p>I'd love to hear your suggestions on either modifying my existing code or considering the problem from another perspective.</p>
<p>When reading the code, please don't feel the need to get hung up on any of the ad hoc parameters at the very beginning of the script. They seem to help, but I don't believe any beside the "G" constant should truly be necessary to make this system work.</p>
<p>Here is an example of the current output:</p>
<p><img src="https://i.stack.imgur.com/3Krio.jpg" alt="enter image description here"></p>
<p>Many of the vehicles have found their way outside of the desired square region, [0,400] X [0,400].</p>
|
[] |
[
{
"body": "<p>Random walks \"wander all around\" by definition. So you have to twist the odds of the walk staying in the area you want.</p>\n\n<p>It would be much simpler if you'd just make an attractor point at the center, that would move each point infinitesimally (some floating point value between 0 to 1 or sqrt(2) pixels) towards itself at each step.</p>\n\n<p>Another option would be to make the edges exponentially hard to reach. I'm thinking of an <a href=\"http://en.wikipedia.org/wiki/Exponential_map\" rel=\"nofollow\" title=\"Exponential map at Wikipedia\">Exponential_map</a> with a really steep slope at the edges and otherwise near linear curve. also see <a href=\"http://en.wikipedia.org/wiki/Gamma_curve\" rel=\"nofollow\" title=\"Gamma Curve at Wikipedia\">Gamma curve</a>. So essentially map an \"infinite\" area to the restricted space.</p>\n\n<p>Third option would be to think about how magnetism works. I mean, a magnet can't be any more magnetized to a certain direction after all it's particles are magnetized towards that direction. And the magnetization takes exponentially stronger field all the way towards that state. I've written a \"tape compression\" algorithm with Numpy using that idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T04:12:30.690",
"Id": "16000",
"ParentId": "15996",
"Score": "4"
}
},
{
"body": "<p>The simple solution would be:\nTry to walk, and as soon as you appear to step outside the box just retry the step untill your walker decides to step somewhere inside the box.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-18T08:11:08.397",
"Id": "17663",
"ParentId": "15996",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T19:53:50.693",
"Id": "15996",
"Score": "6",
"Tags": [
"matlab"
],
"Title": "Drawing random smooth lines contained within a square"
}
|
15996
|
<p>I implemented a queue capable of operating both in the FIFO mode and in the priority mode: when the priority mode is enabled, the elements are taken in order of decreasing priority; when the priority mode in disabled, the elements are taken in order of their arrival.</p>
<p>In order to manage the priority, I thought of using multiple queues (an array of <code>Queue</code> objects, that is <code>m_PriorityQueues</code> in the following code sample), one for each type of element; in this way, I can manage a priority based on the element type: just take first the elements from the queue at a higher priority and progressively from lower priority queues. In order to set the priority of different types of elements, I thought I'd pass an array of <code>Type</code> objects in ascending order of priority, so that each <code>Type</code> is associated with the index of a queue.</p>
<p>The user does not see multiple queues, but it uses the queue as if it were a single queue, so that the elements leave the queue in the order they arrive when the priority mode is disabled. In order to properly manage the switch from priority mode to FIFO mode, I have thought to use an additional queue (that is <code>m_FifoOrder</code> field in the following code sample) to manage the order of arrival of the types of elements: essentially, when a new item is enqueued, it is added to the <strong><em>i</em></strong>-th queue, and the <strong><em>i</em></strong> value which indexes the array of queues is inserted to this additional queue of integers.</p>
<pre><code>public class PriorityQueue
{
private Queue[] m_PriorityQueues;
private LinkedList<int> m_FifoOrder;
private Dictionary<Type, int> m_TypeMapping;
public PriorityQueue(Type[] prioritySet)
{
m_TypeMapping = new Dictionary<Type, int>();
for (int p = 0; p < prioritySet.Length; p++)
{
if (!m_TypeMapping.ContainsKey(prioritySet[p]))
m_TypeMapping.Add(prioritySet[p], p);
}
m_PriorityQueues = new Queue[m_TypeMapping.Count];
for (int i = 0; i < m_PriorityQueues.Length; i++)
m_PriorityQueues[i] = new Queue();
m_FifoOrder = new LinkedList<int>();
}
// Enable or disable the priority mode.
public bool IsPriorityEnabled { get; set; }
// Gets the priority count.
public int PriorityCount { get { return m_TypeMapping.Count; } }
// Gets the number of items actually enqueued in this queue.
public int Count { get { return m_FifoOrder.Count; } }
// Removes all objects from this queue.
public void Clear()
{
for (int i = 0; i < m_PriorityQueues.Length; i++)
m_PriorityQueues[i].Clear();
m_FifoOrder.Clear();
}
// Add an object to the end of this queue
public int Enqueue(object item)
{
int priority;
if (item == null)
{
priority = PriorityCount - 1; // higher priority
}
else if (!m_TypeMapping.TryGetValue(item.GetType(), out priority))
{
priority = 0; // lower priority for unknown types
}
m_PriorityQueues[priority].Enqueue(item);
m_FifoOrder.AddLast(priority);
return priority;
}
// Removes and returns the object at the beginning of this queue.
public bool TryDequeue(out object item)
{
if (IsPriorityEnabled)
{
for (int p = PriorityCount - 1; p >= 0; p--)
{
if (m_PriorityQueues[p].Count > 0)
{
item = m_PriorityQueues[p].Dequeue();
m_FifoOrder.Remove(p);
return true;
}
}
}
else
{
if (m_FifoOrder.Count > 0)
{
int index = m_FifoOrder.First.Value;
item = m_PriorityQueues[index].Dequeue();
m_FifoOrder.RemoveFirst();
return true;
}
}
item = null;
return false;
}
}
</code></pre>
<p><strong>UPDATE:</strong> I performed some tests and I noticed that the <code>TryDequeue</code> method of the version proposed above suffers from performance issues when the priority mode is enabled: the <a href="http://msdn.microsoft.com/en-us/library/k87xw3hb%28v=vs.100%29.aspx" rel="nofollow"><code>Remove</code> method</a>, called on <code>m_FifoOrder</code> linked list, performs a linear search, that is an O(n) operation. Obviously, the performance is reduced more so when n is very large.</p>
<p>In order to reduce the latency caused by this method, I created a new version of the priority queue: the <code>FastPriorityQueue</code> class. The inner class <code>ItemInfo</code> simply contains the object to be enqueued and the priority that is assigned during the queuing operation. An <code>ItemInfo</code> object is always inserted at the end of the <code>m_FifoOrder</code> linked list, so that the <a href="http://msdn.microsoft.com/en-us/library/ms132177.aspx" rel="nofollow"><code>AddLast</code> method</a> returns a reference to the last added <code>LinkedListNode<ItemInfo></code>: this reference is enqueued to one of the <code>m_PriorityQueues</code> queues depending on the chosen priority.</p>
<pre><code>public class FastPriorityQueue
{
private class ItemInfo
{
public object Data { get; set; }
public int Priority { get; set; }
}
private LinkedList<ItemInfo> m_FifoOrder;
private Queue<LinkedListNode<ItemInfo>>[] m_PriorityQueues;
private Dictionary<Type, int> m_TypeMapping;
public FastPriorityQueue(Type[] prioritySet)
{
m_TypeMapping = new Dictionary<Type, int>();
for (int p = 0; p < prioritySet.Length; p++)
{
if (!m_TypeMapping.ContainsKey(prioritySet[p]))
m_TypeMapping.Add(prioritySet[p], p);
}
m_PriorityQueues = new Queue<LinkedListNode<ItemInfo>>[m_TypeMapping.Count];
for (int i = 0; i < m_PriorityQueues.Length; i++)
m_PriorityQueues[i] = new Queue<LinkedListNode<ItemInfo>>();
m_FifoOrder = new LinkedList<ItemInfo>();
}
// Enable or disable the priority mode.
public bool IsPriorityEnabled { get; set; }
// Gets the priority count.
public int PriorityCount { get { return m_TypeMapping.Count; } }
// Gets the number of items actually enqueued in this queue.
public int Count { get { return m_FifoOrder.Count; } }
// Removes all objects from this queue.
public void Clear()
{
for (int i = 0; i < m_PriorityQueues.Length; i++)
m_PriorityQueues[i].Clear();
m_FifoOrder.Clear();
}
// Add an object to the end of this queue
public int Enqueue(object item)
{
int priority;
if (item == null)
{
priority = PriorityCount - 1; // higher priority
}
else if (!m_TypeMapping.TryGetValue(item.GetType(), out priority))
{
priority = 0; // lower priority for unknown types
}
LinkedListNode<ItemInfo> enqueued = m_FifoOrder.AddLast(
new ItemInfo
{
Data = item,
Priority = priority
});
m_PriorityQueues[priority].Enqueue(enqueued);
return priority;
}
// Removes and returns the object at the beginning of this queue.
public bool TryDequeue(out object item)
{
if (IsPriorityEnabled)
{
for (int p = PriorityCount - 1; p >= 0; p--)
{
if (m_PriorityQueues[p].Count > 0)
{
LinkedListNode<ItemInfo> dequeued = m_PriorityQueues[p].Dequeue();
item = dequeued.Value.Data;
m_FifoOrder.Remove(dequeued); // This method is an O(1) operation.
return true;
}
}
}
else
{
if (m_FifoOrder.Count > 0)
{
ItemInfo nodeItem = m_FifoOrder.First.Value;
item = nodeItem.Data;
m_PriorityQueues[nodeItem.Priority].Dequeue();
m_FifoOrder.RemoveFirst();
return true;
}
}
item = null;
return false;
}
}
</code></pre>
<p>Please review the above code samples and provide suggestions on how to improve them. Are there simpler solutions or more efficient than these? Also, if there are other solutions to switch between the two modes (FIFO mode or priority mode), please provide some details.</p>
<p><strong>UPDATE 2:</strong> here is an example of initialization of a <code>PriorityQueue</code> object. When the queue works in FIFO mode, therefore the priorities are ignored. Instead, when the priority mode is enabled, the next item removed from the queue depends on the priority of its type: items with the highest priority will be dequeued first.</p>
<pre><code>// list of types in order of priority
Type[] priorities = new Type[] { typeof(ObjectWithLowerPriority), typeof(ObjectWithIntermediatePriority), typeof(ObjectWithHigherPriority) };
PriorityQueue queue = new PriorityQueue(priorities);
queue.Enqueue(...);
queue.Enqueue(...);
// ... other calls to Enqueue method
queue.IsPriorityEnabled = false;
queue.Dequeue();
// ...
queue.IsPriorityEnabled = true; // priority mode enabled
queue.Dequeue();
// ...
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T14:40:58.243",
"Id": "26022",
"Score": "2",
"body": "Can't you make the queue generic? Wouldn't a more general approach to priorities be better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T15:50:06.740",
"Id": "26029",
"Score": "0",
"body": "@svick: According to your suggestion, I made the queue generic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T20:44:57.020",
"Id": "26043",
"Score": "1",
"body": "@enzom83, @svick, I don't understand why make the `PriorityQueue` generic: see the `Enqueue` method. If it's generic then `item.GetType()` is always `typeof(T)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T20:52:36.973",
"Id": "26044",
"Score": "0",
"body": "@RonKlein: Actually you're right... I have not thought about it since `T` is an interface in my tests. Basically I could restore the previous version or constrain `T` to be an interface or an abstract class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T08:50:58.287",
"Id": "26070",
"Score": "1",
"body": "@RonKlein It doesn't have to be. If `T` is an interface or a non-sealed class, the `item.GetType()` can be different from `T`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T14:01:41.923",
"Id": "26084",
"Score": "0",
"body": "@svick, yes, you're right, I didn't address the possibility of inheritance and/or interface implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T14:51:49.837",
"Id": "26086",
"Score": "0",
"body": "The main functionality is not clear (at least not to my eyes). Perhaps you could provide some unit tests that would demonstrate the expected functionality? For instance, what's the expected functionality for dequeue after several switches of `IsPriorityEnabled`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T22:27:43.543",
"Id": "26133",
"Score": "0",
"body": "@RonKlein: Well, both `PriorityQueue` and `FastPriorityQueue` can be used as a normal queue. The `Enqueue` method adds the specified object to the end of the queue, while the behavior of the `Dequeue` method depends on the `IsPriorityEnabled` property: if this property is set to `false`, then the queue works in _FIFO mode_, otherwise, if this property is enabled, the queue is operating in _priority mode_. I added an example in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-06T13:56:03.190",
"Id": "26443",
"Score": "0",
"body": "The question's code, as well as the one I see in as a review, might be *O(n)* in time (worst case) for `Dequeue`, when there are *n* actions of `Enqueue` in priority mode, and then *n* actions of `Dequeue` in non-priority mode. Please consider if this is the data structure you really want."
}
] |
[
{
"body": "<p>Layout looks good, I like the use of white space, and tabs. You have too many redundant comments that are unneeded.</p>\n\n<p>I am not big on the use of <code>m_</code> to signify class members, I think the <code>_</code> is more commonly used, but that is a debate for another time. I have changed it to <code>_</code> because that is what my eyes are used to.</p>\n\n<p>I would get rid of the Queue array and make it a dictionary of <code><int, LinkedList<ItemInfo>></code> This will keep the data structures you are using in the class more consistent, and the brain is able to deal with them a little more. The three class members can all be make readonly.</p>\n\n<p>I would change the Type[] variable in the constructor to IEnumerable. This will block any changes to the list within the class, and might improve speed a little. To initialize it, you can use the link .ToList() which changes it back to a list, and enables you to run the initialization code. Any changes made to the new list will not propagate back to the calling code. I would also change the p variable to priority, this makes the code more readable.</p>\n\n<p>The initialization of the _typeMapping dictionary should be moved to its own method to declutter the constructor. I would also initialize your IsPriorityEnabled property here, just to make sure it starts off in a known condition</p>\n\n<p>So the constructor now looks like:</p>\n\n<pre><code>public FastPriorityQueue(IEnumerable<Type> prioritySet)\n{\n _typeMapping = new Dictionary<Type, int>();\n _priorityQueues = new Dictionary<int, LinkedList<ItemInfo>>();\n _fifoOrder = new LinkedList<ItemInfo>();\n IsPriorityEnabled = false;\n\n InitializeTypeMapping(prioritySet);\n}\n\nprivate void InitializeTypeMapping(IEnumerable<Type> prioritySet)\n{\n var priorityList = prioritySet.ToList();\n for (var priority = 0; priority < priorityList.Count; priority++)\n {\n if (!_typeMapping.ContainsKey(priorityList[priority]))\n {\n _typeMapping.Add(priorityList[priority], priority);\n }\n }\n}\n</code></pre>\n\n<p>The Clear method could be streamlined a little but using a foreach loop.</p>\n\n<pre><code>public void Clear()\n{\n foreach (var list in _priorityQueues.Values)\n {\n list.Clear();\n }\n\n _fifoOrder.Clear();\n}\n</code></pre>\n\n<p>The Enqueue method can be cleaned up a lot. I'd start by pulling the logic to determine the priority out into its own method. At the same time, you could redo the if statements to make it much more readable. First check should be the null item check. If it is null, no point in going any further. The second check can be either an if statement, or the ? : operator as I used. </p>\n\n<pre><code>private int DeterminePriority(object item)\n{\n if (item == null)\n {\n return PriorityCount - 1; // higher priority\n }\n\n var itemType = item.GetType();\n return _typeMapping.ContainsKey(itemType) ? _typeMapping[itemType] : 0;\n}\n</code></pre>\n\n<p>You could then create the queueItem and add it to the queues. I suggest moving priority enqueue and the regular enqueue out into their own methods. I moved the regular Enqueue(ItemInfo x) into its own method to keep things consistent.</p>\n\n<pre><code>public int Enqueue(object item)\n{\n var priority = DeterminePriority(item);\n\n var queueItem = \n new ItemInfo\n {\n Data = item,\n Priority = priority\n };\n\n PriorityEnqueue(queueItem);\n Enqueue(queueItem);\n\n return priority;\n}\n\nprivate void Enqueue(ItemInfo queueItem)\n{\n _fifoOrder.AddLast(queueItem);\n}\n\nprivate void PriorityEnqueue(ItemInfo item)\n{\n if (!_priorityQueues.ContainsKey(item.Priority))\n {\n _priorityQueues[item.Priority] = new LinkedList<ItemInfo>();\n }\n\n _priorityQueues[item.Priority].AddLast(item);\n}\n</code></pre>\n\n<p>For your TryDequeue method, I would again separate the priority and regular dequeue into their own methods. This will allow you to use the ? : operator in the TryDequeue method and really clean it up. Again, do your fail check first in each method so you don't execute more code than you need to. You'll notice I've added a RemoveItem() method which removes the item from both Queues. Because the way the item was found, there is no need to figure out which dictionary row the item came from.</p>\n\n<pre><code>public bool TryDequeue(out object item)\n{ \n return IsPriorityEnabled ? PriorityDequeue(out item) : Dequeue(out item);\n}\n\nprivate bool Dequeue(out object item)\n{\n if (_fifoOrder.Count == 0)\n {\n item = null;\n return false;\n }\n\n var nextItem = _fifoOrder.First.Value;\n item = nextItem.Data;\n RemoveItem(nextItem);\n\n return true; \n}\n\nprivate bool PriorityDequeue(out object item)\n{\n var priorityQueue = _priorityQueues.Values.FirstOrDefault(v => v.Count > 0);\n\n if (priorityQueue == null)\n {\n item = null;\n return false;\n }\n\n var nextItem = priorityQueue.First.Value;\n item = nextItem.Data;\n RemoveItem(nextItem);\n\n return true;\n}\n\nprivate void RemoveItem(ItemInfo item)\n{\n _priorityQueues[item.Priority].Remove(item);\n _fifoOrder.Remove(item);\n}\n</code></pre>\n\n<p>So the whole class looks like:</p>\n\n<pre><code>public class FastPriorityQueue\n{\n private class ItemInfo\n {\n public object Data { get; set; }\n public int Priority { get; set; }\n }\n\n private readonly LinkedList<ItemInfo> _fifoOrder;\n private readonly IDictionary<int, LinkedList<ItemInfo>> _priorityQueues;\n private readonly IDictionary<Type, int> _typeMapping;\n\n public FastPriorityQueue(IEnumerable<Type> prioritySet)\n {\n _typeMapping = new Dictionary<Type, int>();\n _priorityQueues = new Dictionary<int, LinkedList<ItemInfo>>();\n _fifoOrder = new LinkedList<ItemInfo>();\n\n InitializeTypeMapping(prioritySet);\n }\n\n private void InitializeTypeMapping(IEnumerable<Type> prioritySet)\n {\n var priorityList = prioritySet.ToList();\n for (var priority = 0; priority < priorityList.Count; priority++)\n {\n if (!_typeMapping.ContainsKey(priorityList[priority]))\n {\n _typeMapping.Add(priorityList[priority], priority);\n }\n }\n }\n\n public bool IsPriorityEnabled { get; set; }\n\n public int PriorityCount { get { return _typeMapping.Count; } }\n\n public int Count { get { return _fifoOrder.Count; } }\n\n public void Clear()\n {\n foreach (var t in _priorityQueues.Values)\n {\n t.Clear();\n }\n\n _fifoOrder.Clear();\n }\n\n public int Enqueue(object item)\n {\n var priority = DeterminePriority(item);\n\n var queueItem = \n new ItemInfo\n {\n Data = item,\n Priority = priority\n };\n\n PriorityEnqueue(queueItem);\n Enqueue(queueItem);\n\n return priority;\n }\n\n private void Enqueue(ItemInfo queueItem)\n {\n _fifoOrder.AddLast(queueItem);\n }\n\n private void PriorityEnqueue(ItemInfo item)\n {\n if (!_priorityQueues.ContainsKey(item.Priority))\n {\n _priorityQueues[item.Priority] = new LinkedList<ItemInfo>();\n }\n\n _priorityQueues[item.Priority].AddLast(item);\n }\n\n private int DeterminePriority(object item)\n {\n if (item == null)\n {\n return PriorityCount - 1; // higher priority\n }\n\n var itemType = item.GetType();\n return _typeMapping.ContainsKey(item.GetType()) ? _typeMapping[itemType] : 0;\n }\n\n public bool TryDequeue(out object item)\n { \n return IsPriorityEnabled ? DequeuePriority(out item) : Dequeue(out item);\n }\n\n private bool Dequeue(out object item)\n {\n if (_fifoOrder.Count == 0)\n {\n item = null;\n return false;\n }\n\n var nextItem = _fifoOrder.First.Value;\n item = nextItem.Data;\n RemoveItem(nextItem);\n\n return true;\n }\n\n private bool DequeuePriority(out object item)\n {\n var priorityQueue = _priorityQueues.Values.FirstOrDefault(v => v.Count > 0);\n\n if (priorityQueue == null)\n {\n item = null;\n return false;\n }\n\n var nextItem = priorityQueue.First.Value;\n item = nextItem.Data;\n RemoveItem(nextItem);\n\n return true;\n }\n\n private void RemoveItem(ItemInfo item)\n {\n _priorityQueues[item.Priority].Remove(item);\n _fifoOrder.Remove(item);\n }\n}\n</code></pre>\n\n<p>I hope you picked up a few pointers with this.</p>\n\n<p>Good luck.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T20:40:06.810",
"Id": "16086",
"ParentId": "16005",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16086",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T11:05:55.240",
"Id": "16005",
"Score": "6",
"Tags": [
"c#",
"performance",
"queue"
],
"Title": "A queue that switches from FIFO mode to priority mode"
}
|
16005
|
<p>I have been developing a <a href="https://github.com/santosh/capitalizr/blob/master/capitalizr" rel="nofollow noreferrer">capitalizer</a> in Python. This is actually a script that an end user will type at their terminal/command prompt. I have made this script to:</p>
<ol>
<li>Taking the first argument as a file name and process it.</li>
<li>Don't process words that have 3 or less alphabet.</li>
</ol>
<p>Here's some code:</p>
<pre><code>#!/usr/bin/env python
#-*- coding:utf-8 -*-
from os import linesep
from string import punctuation
from sys import argv
script, givenfile = argv
with open(givenfile) as file:
# List to store the capitalised lines.
lines = []
for line in file:
# Split words by spaces.
words = line.split()
for i, word in enumerate(words):
if len(word.strip(punctuation)) > 3:
# Capitalise and replace words longer than 3 letters (counts
# without punctuation).
if word != word.upper():
words[i] = word.capitalize()
# Join the capitalised words with spaces.
lines.append(' '.join(words))
# Join the capitalised lines by the line separator.
capitalised = linesep.join(lines)
print(capitalised)
</code></pre>
<p>A lot more features still have to be added but this script does the stuff it is made for.</p>
<h3>What I want <em>(from you)</em>:</h3>
<p>I want this script to be emerge as a command line utility. So,</p>
<ol>
<li>How can I make this a better command line utility?</li>
<li>Could I have written in a better way?</li>
<li>Can this script be faster?</li>
<li>Are there any flaws?</li>
<li>Other than GitHub, how can I make it available to the world <em>(so that it is easier to install for end users)</em>? because GitHub is for developers.</li>
</ol>
<p>Please also post links to make my script and me even more mature.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T07:00:35.923",
"Id": "26051",
"Score": "2",
"body": "\"because GitHub is for developers.\" Non-developers tend to not use command line scripts..."
}
] |
[
{
"body": "<h3>As a Command Line Utility</h3>\n\n<p>The <a href=\"http://docs.python.org/library/argparse.html#module-argparse\">Argparse</a> module is designed to facilitate the creation of command line utilities. It makes processing command line arguments much easier, and will even automatically display usage information if the user incorrectly enters arguments.</p>\n\n<h3>Potential Flaws</h3>\n\n<p>Your program does not preserve whitespace. This could be by design but I suspect it is not.<br>\nExample: </p>\n\n<pre>\nthe quick brown fox\n</pre>\n\n<p>will become </p>\n\n<pre>\nthe Quick Brown Fox\n</pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T12:51:06.320",
"Id": "16009",
"ParentId": "16007",
"Score": "8"
}
},
{
"body": "<p><strong>How can you make this a better command-line utility?</strong></p>\n\n<p>Along with using argparse (which is a great suggestion), I would suggest adding options for reading files from stdin, and maybe an option to write to somewhere other than stdout (to a file, for example).</p>\n\n<p><strong>Could it be written better / can it be faster?</strong></p>\n\n<p>Of course! There's always room for improvement. The biggest performance issue I can see here is that you append the output to the <code>lines</code> list, then output at the very end. The downside to this is that you must hold the entire output in memory before you return. If the file is large, it will be slow due to all the allocation/garbage-collection, and in extreme cases you could run out of memory!</p>\n\n<p>Instead of appending to <code>lines</code> and joining at the end, I'd suggest you replace this line:</p>\n\n<pre><code>lines.append(' '.join(words))\n</code></pre>\n\n<p>with</p>\n\n<pre><code>print ' '.join(words) # probably needs replaced with something that preserves whitespace.\n</code></pre>\n\n<p>Then delete all lines that refer to <code>lines</code>:</p>\n\n<p><code>lines = []</code> and <code>capitalised = linesep.join(lines)</code> and <code>print(capitalised)</code></p>\n\n<p>With this, and allowing for input from stdin, you could use it in unix pipelines, like so: <code>cat somefile | capitalizer | grep 'Foo'</code> (or something like that), and you'll see output immediately (as opposed to when the entire file is processed).</p>\n\n<p><strong>Is there an easier way for end-users to install this?</strong></p>\n\n<p>Yes, kind-of... as long as your users are not afraid of the command-line (which I assume, since this is a command-line program), you can publish this to PyPi, then it can be installed with tools like PIP and easy_install.</p>\n\n<p>Here's a simple tutorial for <a href=\"http://wiki.python.org/moin/CheeseShopTutorial\" rel=\"nofollow\">getting started with PyPi</a></p>\n\n<p>When setup properly, installation can be a simple as:</p>\n\n<p><code>easy_install capitalizer</code> or <code>pip install capitalizer</code></p>\n\n<p>Finally, discovery is a bit better than just github, as users can find your app with tools like <a href=\"http://pypi.python.org/pypi\" rel=\"nofollow\">the PyPi website</a>, and <a href=\"https://crate.io/\" rel=\"nofollow\">crate.io</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T22:39:11.513",
"Id": "16016",
"ParentId": "16007",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "16016",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T12:09:18.237",
"Id": "16007",
"Score": "9",
"Tags": [
"python",
"performance",
"strings",
"file"
],
"Title": "Command-line utility to capitalize long words in a file"
}
|
16007
|
<p>The subject is this small project - <a href="https://github.com/salebab/database" rel="nofollow">PHP/MySQL Database wrapper</a></p>
<p>The three main goals of this projects are:</p>
<ul>
<li>Easy way to map database columns to object properties</li>
<li>Simple solution to insert or update data</li>
<li>Query builder class which generate sql query (something like ActiveRecord in CodeIgniter)</li>
</ul>
<p>Some examples:</p>
<pre><code>class User extends stdClass {
function getName() {
return $this->first_name . " ". $this->last_name;
}
}
class Post extends stdClass {
/**
* @var User
*/
public $author;
}
DB::getInstance()->setFetchTableNames(1);
$sql = DB::getInstance()
->select("p.*, u.*")
->from("posts p")
->join("INNER JOIN users u USING(user_id)")
->where("u.user_id = ?", $user_id)
->orderBy("p.title");
$stmt = $sql->execute();
/* @var Post[] $post_collection */
$post_collection = array();
while($post = $stmt->fetchInto(new Post, "p")) {
$post->author = $stmt->fetchIntoFromLastRow(new User, "u");
$post_collection[] = $post;
}
// Usage
foreach($post_collection as $post) {
echo $post->author->getName();
}
</code></pre>
<p>More examples are available in readme file at GitHub - <a href="https://github.com/salebab/database" rel="nofollow">https://github.com/salebab/database</a></p>
<p>So, please review <a href="https://github.com/salebab/database/tree/master/database" rel="nofollow">this classes</a> and I will be very pleased if you can give me some comment.</p>
|
[] |
[
{
"body": "<p>Firstly, a bit of humorous wordplay: witch = itch = burn; \"She's a witch! BURN HER!\" I think you meant \"which\" in this context. Now that is out of my system, on to the review :)</p>\n\n<p>Why are you extending the stdClass? This is the class reserved for typecasting variables as classes. It is just a wrapper that has no benefits of being extended from. If you are just trying to create a normal class then just drop the <code>extends stdClass</code> bit. Its unnecessary.</p>\n\n<p>Additionally, where did properties <code>$first_name</code> and <code>$last_name</code> come from? They were not declared. This means they either are coming from the parent class, which is impossible as the stdClass is empty, or they are defaulting to the public scope. If you were extending another class and that property was defined there, this would be fine, but default properties are bad. Besides, I have heard rumors that it will be deprecated soon, so prepare for the worst and just manually define their scope.</p>\n\n<pre><code>class User {\n public\n $first_name,\n $last_name\n ;\n //etc...\n}\n</code></pre>\n\n<p>What is the point of the <code>Post</code> class? Just to declare the <code>$author</code> property? This is unnecessary, especially for a full fledged class. The only time I could foresee something like this being ok is if it were part of an interface or abstract class, but then it should also declare the expected methods as well.</p>\n\n<p>Why is your database class completely static? I understand adopting a singleton pattern to ensure only one connection can be made, but after that you should be able to use the rest of your class like normal. Instead you are calling it statically everywhere. This is what you should be able to do with the singleton pattern. Notice how you only have to get the instance once.</p>\n\n<pre><code>$db = DB::getInstance();\n$db->setFetchTableNames( 1 );\n$sql = $db->select(//etc...\n</code></pre>\n\n<p>Why are you looping over the same information twice? If you find yourself looping over something in order to create an array so that you can loop over it again, don't. Just do it all the first time.</p>\n\n<pre><code>while( $post = $stmt->fetchInto( new Post(), 'p' ) ) {\n $post->author = $stmt->fetchIntoFromLastRow( new User(), 'u' );\n echo $post->author->getName();\n}\n</code></pre>\n\n<p>Now, I can't really help you much more because you've not posted all of your code, just examples. I can't review your class except in the abstract. If you want a more complete review, you should follow the FAQ and post all related code. For instance, you are asking about your database wrapper, but all you have posted are a couple of slightly related container classes and example usages. Where's the actually database wrapper?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T12:35:52.497",
"Id": "26195",
"Score": "0",
"body": "The subject of question isn't provided code, that is just example, the subject is code on github. I didn't read the FAQ and recomendation to include the whole code here. There is so much code, I cannot do that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T13:06:21.773",
"Id": "26197",
"Score": "0",
"body": "@sasa: You do not need to include ALL of your code, just the class in question. In this case that would be the DB class. The dependencies should be unnecessary as it should be obvious from the code what you are trying to do, if not, that will just be something I will point out. I wouldn't mind taking a look at this on github later, but I can't while I'm at work and I have classes in the afternoon, so I'm not sure when I could get around to it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T15:58:12.057",
"Id": "16078",
"ParentId": "16017",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T23:55:40.030",
"Id": "16017",
"Score": "4",
"Tags": [
"php",
"sql",
"mysql",
"pdo"
],
"Title": "PDO Database wrapper"
}
|
16017
|
<p>I have written <code>Validation</code> and <code>Form</code> classes in PHP.</p>
<ul>
<li><code>Validation</code> class allow you to define the rules of each field and a error message. </li>
<li><code>Form</code> class allow you to get a error message and also allow you to get a value of POST via <code>$_SESSION</code>. </li>
</ul>
<p>I stored in <code>$_SESSION</code> because if validation did not pass it will need to redirect back to main Form page and repopulate all the fields using <code>value()</code> method. </p>
<p>What do you think of <code>Validation</code> and <code>Form</code> classes - what can be improved?</p>
<p><strong>Validation Class</strong></p>
<pre><code>class Validation
{
protected $fields = array();
private $errors = array();
public function setRules($field, $errorMessage, $rules = array())
{
if (count($_POST) == 0) {
throw new Exception("The array of post parameters is empty");
}
if ($field == '') {
throw new Exception("field parameter is empty");
}
if (!is_array($rules) || count($rules) == 0) {
throw new Exception("The array of rules parameter is empty");
}
$errorMessage = ($errorMessage == '') ? $field : $errorMessage;
$this->fields[] = array(
'name' => $field,
'errorMessage' => $errorMessage,
'rules' => $rules,
);
}
public function validate()
{
if (count($_POST) == 0) {
throw new Exception("The array of post parameters is empty");
}
if (count($this->fields) == 0) {
throw new Exception("Validation rules is not set");
}
foreach ($this->fields as $field) {
$fieldName = $field['name'];
if (isset($_POST[$fieldName])) {
foreach ($field['rules'] as $rule) {
$param = false;
if ($arr = explode('=', $rule)) {
if (isset($arr[0]) && isset($arr[1])) {
$param = $arr[1];
$rule = $arr[0];
}
}
$output = $this->$rule($_POST[$fieldName], $param);
if ((in_array('required', $field['rules']) && $output == FALSE) || (!in_array('required', $field['rules']) && $output == FALSE && $_POST[$fieldName] != '')) {
if (!isset($this->errors[$fieldName])) {
$this->errors[$fieldName] = array('errorMessage' => $field['errorMessage']);
}
}
}
}
}
return (count($this->errors) == 0) ? true : false;
}
public function getError($field)
{
if (isset($this->errors[$field]) && $this->errors[$field] != '') {
return $this->errors[$field]['errorMessage'];
}
return false;
}
private function validEmail($value)
{
return filter_var($value, FILTER_VALIDATE_EMAIL);
}
private function required($value)
{
return ($value != '') ? true : false;
}
private function numeric($value)
{
return is_numeric($value) ? true : false;
}
private function exactLength($value, $param)
{
return (strlen($value) == $param) ? true : false;
}
}
</code></pre>
<p><strong>Form Class</strong></p>
<pre><code>class Form
{
private $validation;
function __construct($validation) {
$this->validation = $validation;
$_SESSION['posts'] = $_POST;
}
public function error($field)
{
return $this->validation->getError($field);
}
public function value($field) {
if (isset($_SESSION['posts'][$field]))
return $_SESSION['posts'][$field];
}
}
</code></pre>
<p><strong>Usage Testing:</strong></p>
<pre><code>// FAKE POST TEST
$_POST['name'] = 'Pau';
$_POST['email'] = 'hello@google';
$val = new Validation();
$form = new Form($val);
$val->setRules('name', 'Please enter your full name', array('exactLength=6','required'));
$val->setRules('email', 'Please enter your email', array('validEmail'));
if ($val->validate()) {
echo "Good! - Validation Passed";
} else {
echo "Bad! - Validation Not Passed";
echo $form->error("name");
}
</code></pre>
|
[] |
[
{
"body": "<p>Short on time, but here's a few quick things:</p>\n\n<ul>\n<li>Consider making individual validators rather than putting all of the different validation rules in one class.\n<ul>\n<li>One option would be to make a <code>Field</code> class and have <code>Form</code> contain a collection of <code>Field</code>s (with each field having a collection of <code>Validator</code>s)</li>\n</ul></li>\n<li>Pass in $_POST instead of accessing it in your class (what if you want to validate $_GET or something?)</li>\n<li>Form shouldn't directly depend on <code>$_SESSION</code></li>\n<li><code>$_SESSION['posts'] = $_POST;</code> The form shouldn't be responsible for storing state. If you want to do that, do it outside of the <code>Form</code> class.</li>\n<li>How do you know which validation(s) failed?</li>\n<li>The two exceptions thrown in validate should be reconsidered. A missing field should probably be considered empty (and thus a required validation failed), and a <code>Form</code> with no rules, should probably always validate as <code>true</code>. (Also, they should probably be specialized exception classes, not just the generic <code>Exception</code>)</li>\n<li><code>return ($value != '') ? true : false;</code> Is redundant: <code>return ($val != '');</code>\n<ul>\n<li>In particular, any expression of the form <code>(expr) ? true : false</code> can be written as <code>(expr)</code></li>\n</ul></li>\n<li>Be careful with implicit typecasts (for example, some of your string comparisons might should be <code>===</code>)</li>\n<li><code>$this->errors[$fieldName] = array('errorMessage' => $field['errorMessage']);</code> You're clobbering any old errors</li>\n<li>There should probably be some way to tell which elements have errors. How did you know name has an error if validate fails? How do you know it's not email? </li>\n</ul>\n\n<p>(I will likely come back to this. Also, I haven't forgotten about your post from 2 days ago that I said the same thing on... Just been very busy :D)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T22:41:41.687",
"Id": "26134",
"Score": "0",
"body": "Thanks for answer. Looking forward for more details :P Oh please clarity what do you mean by \"Consider making individual validators rather than putting all of the different validation rules in one class.\" ... If would be great if you can show example of code and improve my code. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T14:09:02.863",
"Id": "26147",
"Score": "1",
"body": "@I'll-Be-Back: instead of having one `Validator` class, you may have `Validator_email`, `Validator_price`...etc This way you can unittest each class individually, and you may also create new validators by extending from old ones"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T18:46:48.733",
"Id": "26408",
"Score": "0",
"body": "@I'll-Be-Back, @Quamis nailed it. Each validator should be responsible for one validation (fairly related to separation of concerns). I would have an interface that has one method: `public function validate();`. That would then return an array of any errors. (Or an empty array if there are no errors. Or perhaps `true`, or, you get the point.) All of your validators would then implement that interface. If you want, I can still type out a full example with a few interfaces. The Zend_Validate stuff is a fairly good real-world example though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T01:32:19.403",
"Id": "16019",
"ParentId": "16018",
"Score": "5"
}
},
{
"body": "<p>Well, first off, I think using client side cookies, instead of session cookies, might be a little better here. It puts less strain on your server and keeps unnecessary transfers from occurring. But the difference might be trivial, depending on the type of traffic you are expecting. Corbin touched on a few good points, +1 to him, below are some that I found.</p>\n\n<p><code>$fields</code> should only be protected if it is being shared, either by a parent or child class. Since the <code>Validation</code> class isn't extending anything I think its safe to say that no parent classes are using it. Its a little harder to tell if it has any children that might use it. I don't see any in the code you posted, but that doesn't mean its not being done somewhere else. Just know that protected means a property is to be shared but not available outside of a parent/child relationship, otherwise it should be public or private, depending on how you are planning on using it. Though typically public properties are avoided in favor of setters/getters.</p>\n\n<p>As Corbin has said, you should pass in the POST array instead of explicitly calling for it in your class. For instance, say you parsed a JSON file and wanted to verify it before using it, this class would be the perfect candidate, but because you have limited it to using only POST values you will either have to create a new class just for JSON, or you will have to modify this one to use both POST and JSON, and the cycle will continue the more things you add. Better to just generalize it now. This will also mean that verifying that the POST array was set will become unnecessary, at least here.</p>\n\n<p>Also, an easier way to determine if an array is empty is to use the <code>empty()</code> function. This holds true for anywhere you are comparing the size of an array to zero.</p>\n\n<pre><code>if( ! is_array( $rules ) || empty( $rules ) ) {\n</code></pre>\n\n<p>Since it appears obvious that you only want an array to be passed as your ruleset, perhaps a better way of passing the <code>$rules</code> parameter would be to use type hinting in addition to a default value. This would throw an error automatically if some other form of variable was used, meaning you don't have to explicitly check it anymore, except for empty of course, you can just assume its an array and work from there.</p>\n\n<pre><code>public function setRules( $field, $errorMessage, Array $rules = array() ) {\n</code></pre>\n\n<p>If you are like me and are unlucky enough not to be able to use short ternary yet, then the following ternary statement is fine, but, if your PHP version is >= 5.3, then know that you can change it. Also, an empty string translates to a FALSE state, so explicitly checking it should be unnecessary; and those parenthesis are also unnecessary.</p>\n\n<pre><code>$errorMessage = ($errorMessage == '') ? $field : $errorMessage;\n//The same thing in 5.3\n$errorMessage = $errorMessage ?: $field;\n</code></pre>\n\n<p>Perhaps a better way to parse your rules would be to use array functions rather than explicitly declaring each array element. This will make your nested if statements completely unnecessary. Additionally, try not to define variables in your statements. It can make debugging hard, besides, the only way this function would return false is if you passed it an empty string. If you use <code>array_filter()</code> in your <code>setRules()</code> method before setting this value to the fields array then all such elements will automatically be removed from your array.</p>\n\n<pre><code>$rules = array_filter( $rules );\nif( empty( $array ) { /* throw error */ }\n//complete setRules() and start validate()\n\n$ruleParams = explode( '=', $rule );\n$rule = array_pop( $ruleParams );\n$param = array_shift( $ruleParams );\n</code></pre>\n\n<p>Be careful of variable-functions, or in this case variable-methods. Typically most people will glare at you and call you dirty names for doing this. They are very hard to debug for. I understand what you are trying to do, but I'm almost tempted to tell you to do it manually.</p>\n\n<p>The following if statement is working too hard. First, it is just too long. You can abstract some of those statements to make this a bit easier to read.</p>\n\n<pre><code>if ((in_array('required', $field['rules']) && $output == FALSE) || (!in_array('required', $field['rules']) && $output == FALSE && $_POST[$fieldName] != '')) {\n//compared to\n$noOutput = $output == FALSE;\n$required = in_array( 'required', $field[ 'rules' ] );\nif( ( $required && $noOutput ) || ( ! $required && $noOutput && $_POST[ $fieldName ] ) ) {\n</code></pre>\n\n<p>Additionally, the above statement is redundant. At least in as far as you are checking if a field exists in your array on every iteration. Do it once outside of the loop and use that instead. But what is this even doing? You are saying that if one parameter is required, they all are? Did you instead mean to check if <code>$rule == 'required'</code>? This just seems a bit odd.</p>\n\n<pre><code>$required = in_array( 'required', $field[ 'rules' ] );\nforeach( $this->fields AS $field ) {\n //etc...\n if( ( $required && $noOutput ) || ( ! $required && $noOutput && $_POST[ $fieldName ] ) ) {\n</code></pre>\n\n<p>Alright the next statement I sort of get, you don't want to overwrite any existing messages, but why not instead just log them all using a multidimensional array?</p>\n\n<pre><code>if (!isset($this->errors[$fieldName])) {\n $this->errors[$fieldName] = array('errorMessage' => $field['errorMessage']);\n}\n//compared to\n$this->errors[ $fieldsName ] [] = array( 'errorMessage' => $field[ 'errorMessage' ] );\n</code></pre>\n\n<p>No need to explicitly define a TRUE/FALSE state for the return value. Just return the count, or <code>empty()</code> check, either one would result in the same thing, though I would use the latter as it does not require the added negation.</p>\n\n<pre><code>return ! count($this->errors);\n//or\nreturn empty( $this->errors );\n</code></pre>\n\n<p>The following statement will always be true, at least partially. Each element of the <code>$errors</code> property is an array, so it will never be equal to an empty string. Maybe you meant to use an <code>empty()</code> check here, but even that should be impossible. The <code>$errors</code> property is private and I don't see any method unsetting values from this array, therefore, if the <code>$field</code> index is set, the value should be as well. Just remove the second check.</p>\n\n<pre><code>if (isset($this->errors[$field]) && $this->errors[$field] != '') {\n//compared to\nif( isset( $this->errors[ $field ] ) ) {\n</code></pre>\n\n<p>Then the above could be rewritten so that you only have one return statement. Though this ternary statement is getting a bit long and complicated, so this might be unwise.</p>\n\n<pre><code>return isset( $this->errors[ $field ] ) ? $this->errors[ $field ] [ 'errorMessage' ] : FALSE;\n</code></pre>\n\n<p>Please, always use braces on your statements. PHP inherently requires them, otherwise you wouldn't have to add them if your statements extend more than one line. This would be different if that wasn't the case, but it is and it can cause issues. Besides, this is inconsistent with the rest of your code.</p>\n\n<pre><code>if (isset($_SESSION['posts'][$field]))\n return $_SESSION['posts'][$field];\n//use the following instead\nif( isset( $_SESSION[ 'posts' ] [ $field ] ) ) {\n return $_SESSION[ 'posts' ] [ $field ];\n}\n</code></pre>\n\n<p>Correct me if I'm wrong, but I'm not sure your usage tests works. You pass your validation class to the form class, but because nothing has been done to it yet it will not reflect in the form class. This means that calling for the errors from the form class is pointless. You should just wait to inject the validation class until you add everything you need to first.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T15:20:16.817",
"Id": "16077",
"ParentId": "16018",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16077",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T01:02:50.163",
"Id": "16018",
"Score": "5",
"Tags": [
"php",
"design-patterns",
"classes",
"php5",
"validation"
],
"Title": "Validation and Form classes"
}
|
16018
|
<p>I have a catalogue of activities that are marked based on the age group that they are relevant to. There are 14 checkboxes for checking what grades. K, 1 - 12, and Adult. I have a switch statement to change the K and Adult to a numeric representation.</p>
<p>The following PHP code grabs the grades checked and displays them in consecutive groups.
Aka. K, 1, 2, 3, 5, 6, 7, 10, 11, Adult will display as K - 3, 5 - 7, 10 - Adult.</p>
<p>What I would like to ask is, is this a clumsy solution for my problem? Can I learn to make this more efficient or less prone to issues?</p>
<pre><code>// generated through database, but set manually here for testing
$new_grades_array = array(K, 1, 2, 3, 5, 6, 7, 10, 11, Adult)
// grades related variables
$last = ""; // records previous grade in loop for checking consecutiveness
$display = ""; // concatenated display of results
$conseq = FALSE; // records if previous grade was consecutive
for ($i = 0; $i < count($new_grades_array); $i++):
// set grade digit for K and Adult
switch ($new_grades_array[$i]):
case "K":
$currentgrade_dig = 0;
break;
case "Adult":
$currentgrade_dig = 13;
break;
default:
$currentgrade_dig = $new_grades_array[$i];
endswitch;
// concatenates string to display variable based on situation
if ($i == 0): // if the first grade listed
$display = $new_grades_array[$i];
elseif ($i +1 == count($new_grades_array)): //if the last grade listed
if ($conseq != FALSE):
$display .= " - " . $last . ", " . $new_grades_array[$i];
else:
$display .= ", " . $new_grades_array[$i];
endif;
$conseq = FALSE;
elseif ($currentgrade_dig - $last ==1): // if consecutive number from previous
$conseq = TRUE;
else: // if not a consecutive number
if ($conseq != FALSE):
$display .= " - " . $last . ", " . $new_grades_array[$i];
$conseq = FALSE;
else:
$display .= ", " . $new_grades_array[$i];
endif;
endif;
$last = $new_grades_array[$i];
endfor;
print $display;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T20:45:14.280",
"Id": "26053",
"Score": "1",
"body": "You could replace the switch statement with an lookup array. And instead of the for-loop, you can use an foreach-loop"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T22:26:09.650",
"Id": "26054",
"Score": "3",
"body": "Is there any particular reason why you're not using { and }?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T22:11:41.650",
"Id": "26719",
"Score": "0",
"body": "The BEST reason, I think, is because it is in a template and I believe it is somewhat standard in templating? I was working inside of a template someone else had created and they were using the alternative syntax. I actually prefer the alternative syntax because I think it makes my code easier for me to read. Since then, I've read that it is an old syntax that it is being used less. So I am not sure if I will continue when coding in general."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T11:00:44.330",
"Id": "28809",
"Score": "1",
"body": "Using alternate syntax in php code (where you're not jumping in and out of php/html) makes it _harder_ to read because blocks are not immediately identifiable."
}
] |
[
{
"body": "<p>If we are speaking about conversion of some numeric value to its text representation when some very limited number of numeric values has non-numeric text representation and vice versa, then the most efficient way will be:</p>\n\n<pre><code>$display = $i == 0? \"K\" : ($i == 13 ? \"Adult\" : $i);\n$i = $text == \"k\" ? 0 : ($text == \"Adult\" ? 13 : $text);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:06:57.363",
"Id": "26055",
"Score": "0",
"body": "Thanks! This looks like it will be very useful. I am not familiar with the above syntax though, could you explain it or give me a term to lookup?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:10:00.240",
"Id": "26056",
"Score": "0",
"body": "It is a ternary operator. It exist in many modern languages. `op1 ? op2 : op3` The first operand is a boolean expression. If its value true then the op2 is evaluated otherthise op3 is evaluated"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:10:43.217",
"Id": "26057",
"Score": "0",
"body": "@SweetTomato it's called a \"ternary operator\". Search for that term [on this page](http://php.net/manual/en/language.operators.comparison.php)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:11:08.583",
"Id": "26058",
"Score": "0",
"body": "http://php.net is a very good souce of information on php. I believe the best one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:16:59.560",
"Id": "26059",
"Score": "0",
"body": "Thank you! I used the ternary operator by changing my switch statement to: $currentgrade_dig = $new_grades_array[$i] == \"K\" ? 0 : $new_grades_array[$i] == \"Adult\" ? 13 : $new_grades_array[$i];"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:21:44.160",
"Id": "26060",
"Score": "0",
"body": "Reading the page recommended by @bhamby, I found that return-by-reference functions and stacking ternary operators are not recommended. Am I doing both in my example since I am looking for the K, then Adult, then referencing $new_grades_array[$i]?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:29:08.523",
"Id": "26061",
"Score": "0",
"body": "1) there is no returning by reference in my example. 2) \"Obvious\" to who? To the programmer or to the compiler? ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:30:56.447",
"Id": "26062",
"Score": "0",
"body": "Yes, I did a mistake. well, no one is error proof. I fixed the answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:41:20.593",
"Id": "26063",
"Score": "0",
"body": "Thanks @serge, I didn't realize it was a problem that could be fixed with the parenthesis. So, stacking is not recommended when you don't explicitly state the order of operations? (And I think I misunderstood the returning-by-reference statement, so never mind on that)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:43:48.977",
"Id": "26064",
"Score": "0",
"body": "Not at all, Thank you to make me looking at this. Actually I was surprised that php evaluates this operator in non-usual (at least for me) direction"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T21:44:08.087",
"Id": "26065",
"Score": "0",
"body": "Many people recommend using explicit parentheses for any complex expression where the default precedence isn't obvious. Stacked ternary expressions are definitely one of these cases."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T20:58:14.557",
"Id": "16024",
"ParentId": "16023",
"Score": "0"
}
},
{
"body": "<p>Here are some tips.</p>\n\n<h2>1) Have a function that returns the grade value.</h2>\n\n<p>This helps avoid duplicated code and increases readablilty.</p>\n\n<p>Code:</p>\n\n<pre><code>function getGradeValue($val){\n switch ($val) {\n case \"K\":\n $val = 0;\n break;\n case \"Adult\":\n $val = 13;\n break;\n default:\n }\n return $val;\n}\n</code></pre>\n\n<h2>2) Create a function to retrieve the final output.</h2>\n\n<p>This allow for an easier way to test the overall functionality and helps to eliminate global variables.</p>\n\n<h2>3) Create unit tests to speed up testing</h2>\n\n<p>Simple Testcases:</p>\n\n<pre><code>function println( $str ){\n print( $str . \"<br/>\\n\" );\n}\nfunction testThis( $arr, $expect ){\n $result = getGroupedGradesAsString( $arr );\n if( $result == $expect ){\n println( \"Passed:\" );\n }else{\n println( \"Fail:\" . $result . \" != \" . $expect );\n }\n}\ntestThis( array(\"K\", 1, 2, 3, 5, 6, 7, 10, 11, \"Adult\"), \"K - 3, 5 - 7, 10 - 11, Adult\" );\ntestThis( array(\"K\"), \"K\" );\ntestThis( array(\"K\", \"Adult\"), \"K, Adult\" );\ntestThis( array(\"K\", 1, 2, 7, 11, 12), \"K - 2, 7, 11 - 12\" );\ntestThis( array( 6, 7, 8), \"6 - 8\" );\ntestThis( array(\"K\", 2, 4, 6, 8, 10, 12), \"K, 2, 4, 6, 8, 10, 12\" );\ntestThis( array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, \"Adult\"), \"1 - Adult\" );\n</code></pre>\n\n<h2>4) Use a loop to find the last consistent number.</h2>\n\n<p>Refer to <code>getGroupedGradesAsString()</code> in the final code for more information.</p>\n\n<h2>Final Code:</h2>\n\n<pre><code><?php\n// By Larry Battle [http://bateru.com/news/]\nfunction getGradeValue($val){\n switch ($val) {\n case \"K\":\n $val = 0;\n break;\n case \"Adult\":\n $val = 13;\n break;\n default:\n }\n return $val;\n}\nfunction getGroupedGradesAsString($arr) {\n $output = \"\";\n for ($i = 0, $len = count($arr); $i < $len; $i++) {\n $output .= (($i) ? \", \" : \"\" ) . $arr[$i];\n if( getGradeValue($arr[$i]) == getGradeValue($arr[$i+1])-1 ){\n do{\n $i++;\n }while( getGradeValue($arr[$i]) == getGradeValue($arr[$i+1])-1);\n $output .= \" - \" . $arr[$i];\n }\n }\n return $output;\n}\n?>\n</code></pre>\n\n<p>Demo here: <a href=\"http://codepad.org/zi8oavlv\" rel=\"nofollow\">http://codepad.org/zi8oavlv</a></p>\n\n<p>Here's a shorter version but might be a litter bit harder to understand.</p>\n\n<pre><code><?php\n // By Larry Battle [http://bateru.com/news/]\nfunction getGradeValue($val){\n return ( $val == \"K\" || $val == \"Adult\" ) ? (($val == \"K\") ? 0 : 13 ) : $val;\n}\nfunction getGroupedGradesAsString($arr) {\n $output = \"\";\n for ($i = 0, $len = count($arr); $i < $len; $i++) {\n $output .= (($i) ? \", \" : \"\" ) . $arr[$i];\n if( getGradeValue($arr[$i]) !== getGradeValue($arr[$i+1])-1 ){\n continue;\n }\n while( getGradeValue($arr[++$i]) === getGradeValue($arr[$i+1])-1);\n $output .= \" - \" . $arr[$i];\n }\n return $output;\n}\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T21:46:42.917",
"Id": "26717",
"Score": "0",
"body": "Hi Larry! Thanks for your tips, I will use these for future programming! I am impressed at how short your getGroupedGradesAsString function is and will study that to improve my coding later. Also, my output was not completely correct, but in yours it is. I didn't catch it because I was only testing it against one array situation. I have never seen a test function to compare output with desired output, so thank you for sharing that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T07:55:51.890",
"Id": "16051",
"ParentId": "16023",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-28T20:33:29.220",
"Id": "16023",
"Score": "2",
"Tags": [
"php"
],
"Title": "Generating an array of school grades"
}
|
16023
|
<p>I want to build a set of <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="nofollow">builders</a> for generating test data. On one side I want my builders API to be natural to use for my teammates. On the other side I'm great fun of creating <a href="http://en.wikipedia.org/wiki/Domain-specific_language" rel="nofollow">DSLs</a>, because it eliminates writing the same boilerplate code and let you read the code as English sentences. </p>
<p>However, I found those requirements quite incompatible. I've shown my builders to my teammate and what was intuitive to me, was not for him. He would need to learn my DSL.</p>
<p>How would you improve my design decisions in Builder pattern?</p>
<p><strong>Decision #1: Long domain names vs. new short names</strong> </p>
<p>I started with traditional <code>withX()</code> methods for setting field <em>X</em>. For <em>X</em> I used names that are well known in our domain and commonly used in the rest of implementation.</p>
<pre><code>Flight.Builder.create()
.withOrigin(Airport.LAX)
.withDestination(Airport.JFK)
.build();
</code></pre>
<p>Then I thought this takes too much space, so I used method names that are shorter but uncommon in the rest of the implementation.</p>
<pre><code>Flight.Builder.create()
.from(Airport.JFK)
.to(Airport.LAX)
.build();
</code></pre>
<p>Another programmer prefered traditional names from the domain: origin, destination.</p>
<p><strong>Decision #2: Clear method names vs. duplicate methods with type-overloading</strong></p>
<p>Another weak point I found was redundancy of some information. For instance, in the following code:</p>
<pre><code>Flight.Builder.create()
.withPassenger(Passenger.ADULT) // that's a template
.withPassenger(Passenger.Builder.create().withName("KENNEDDY"))
.withStatus(Status.CANCELLED)
.build();
</code></pre>
<p>the redundancy is in passenger-passenger, and in status-status. So I removed redudant words from method names and used type-overloading.</p>
<pre><code>Flight.Builder.create()
.with(Passenger.ADULT)
.with(Passenger.Builder.create().withName("KENNEDDY"))
.with(Status.CANCELLED)
.build();
</code></pre>
<p>The programmer who knows data model underlying this builder and was used to more traditional builder pattern, was confused with my approach.</p>
<p><strong>Decision #3: Changing words order and delegating builder creation</strong></p>
<p>Then I found builder creation kind of boilerplate code that makes it harder to read:</p>
<pre><code>Flight.Builder.create()
.withPassenger(Passenger.Builder.create().withName("KENNEDDY"))
.build();
</code></pre>
<p>I shortened those constructs. I also found this incompatible with English words order in sentence, where you don't say "what.build()", but "build(what)". Here's the result.</p>
<pre><code>build(flight()
.withPassenger(passenger().withName("KENNEDDY")));
</code></pre>
<p>How would you improve my design decisions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T08:48:40.510",
"Id": "26069",
"Score": "0",
"body": "Is my question too loooong or title unclear? Any feedback is welcome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T10:38:18.517",
"Id": "26074",
"Score": "0",
"body": "The question and the title seem fine although it might fit better to Programmers.SE."
}
] |
[
{
"body": "<p>A few, rather subjective thoughts:</p>\n\n<p><strong>Decision #1:</strong></p>\n\n<p>Here you have a flight builder. Which group of sentences looks more natural from the following?</p>\n\n<ul>\n<li><em>a flight builder with origin</em></li>\n<li><em>a flight builder with destination</em></li>\n</ul>\n\n<p>or</p>\n\n<ul>\n<li><em>a flight builder from</em></li>\n<li><em>a flight builder to</em></li>\n</ul>\n\n<p>The first two looks better for me.</p>\n\n<p>Furthermore, if origin and destination are in your domain you should use them. Using synonyms could be confusing.</p>\n\n<p><strong>Decision #2:</strong></p>\n\n<p>I may be worth to note that if you have more than one field with the same type (strings and ints are common) it would not work. Having builders in the same application and one half of them is using <code>with()</code> while the other half is using <code>withX()</code> is also confusing.</p>\n\n<p><strong>Decision #3:</strong></p>\n\n<p>The <code>passenger().withName(\"KENNEDDY\")</code> statements make me think about where the passenger instance comes from. A database or maybe a cache? I think a <code>create</code> word somewhere would make it obvious that it's a new instance and it would be helpful for readers although renaming <code>passenger()</code> to <code>createPassenger()</code> does not seem natural in this code too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T08:23:52.417",
"Id": "26106",
"Score": "1",
"body": "Regarding passenger creation. In our business domain passenger instances are not shared across flight. Instead, they are created for each flight separately, so `createPassenger()` or `createPax()` would be more clear. (pax is common synonym here)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T09:51:46.767",
"Id": "16027",
"ParentId": "16025",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16027",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T07:58:55.627",
"Id": "16025",
"Score": "2",
"Tags": [
"java",
"design-patterns"
],
"Title": "Is my DSL good idea to replace builder pattern?"
}
|
16025
|
<p>My Haskell set/map/list folds often become terse and difficult to read. I'm looking for tips on how to make my functional code easier to follow.</p>
<p>I'm working around a bug/feature in a plotting library. I have a map from tags to lists of (time,count) which I plot as a stacked graph:</p>
<pre><code>import Data.Time (UTCTime)
import qualified Data.Map as M
import qualified Data.Set as S
type CountMap = M.Map String [(UTCTime, Int)]
-- Data used for plotting data series 'foo' and 'bar'
test :: CountMap
test =
M.fromList [ ("foo", [(read "2012-09-28 12:00:00", 3), (read "2012-09-29 12:00:00", 4)])
, ("bar", [(read "2012-09-28 12:00:00", 3)])
]
</code></pre>
<p>You will note that the above "bar" series is missing a sample for 2012-09-29. I need to fill these gaps with zeros before I pass the data to the plotting library. </p>
<p>The same data with the gaps closed becomes:</p>
<pre><code>fromList [ ("bar",[(2012-09-28 12:00:00 UTC,3),(2012-09-29 12:00:00 UTC,0)])
, ("foo",[(2012-09-28 12:00:00 UTC,3),(2012-09-29 12:00:00 UTC,4)])]
</code></pre>
<p>The code I use for filling the gaps with zero samples is as follows:</p>
<pre><code>import Data.Time (UTCTime)
import qualified Data.Map as M
import qualified Data.Set as S
-- Insert zero counts into date buckets that are missing a sample.
substZeroCount :: CountMap -> CountMap
substZeroCount m =
M.map zeros m
where
allDates = M.fold (flip (foldr (\(date,_) -> S.insert date))) S.empty m
zeros cs = M.toList $ S.fold insertMissing (M.fromList cs) allDates
insertMissing date acc = if M.member date acc then acc else M.insert date 0 acc
</code></pre>
<p>It works and it's not even too long. But somehow I don't feel happy about its readability. It looks somehow too terse. Maybe it's just about code layout.. or perhaps there'd be a nicer way to compose these functions. Or maybe it's just because a lot happens in 3 lines of code. ;)</p>
<p>Any suggestions on how to make <code>substZeroCount</code> easier on the eyes?</p>
|
[] |
[
{
"body": "<p>I think you should keep <code>CountMap</code> as <code>Map String (Map UTCTime Int)</code>. That is a better way of keeping counts. If you do that then you can use <code>mysc</code> function directly. I find <code>mysc</code> much more readable and clear. </p>\n\n<pre><code>import Data.Time (UTCTime)\nimport qualified Data.Map as M\n\ntype CountMap = M.Map String [(UTCTime,Int)]\n\n-- Data used for plotting data series 'foo' and 'bar'\ntest :: CountMap\ntest =\n M.fromList [ (\"foo\", [(read \"2012-09-28 12:00:00\", 3), (read \"2012-09-29 12:00:00\", 4)])\n , (\"bar\", [(read \"2012-09-28 12:00:00\", 3)])\n ]\n\nsusetCount :: CountMap -> CountMap\nsusetCount = M.map M.toList . mysc . M.map M.fromList\nmysc m = M.map (flip M.union allelems) m\n where\n -- Find all possible UTCTime that can exist. \n allelems = M.map (const 0) $ M.foldr' M.union M.empty m\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T10:32:04.300",
"Id": "26073",
"Score": "0",
"body": "Nice! You probably mean M.fold instead of M.foldr'?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T10:38:20.907",
"Id": "26075",
"Score": "0",
"body": "Nurpax: Yeah you can use M.fold with some changes but this will also work ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T10:47:48.593",
"Id": "26076",
"Score": "0",
"body": "At least my Data.Map doesn't have a `foldr'`, only `fold`, hence the question. Replacing `M.foldr'` above with M.fold works without any other changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T11:06:22.413",
"Id": "26077",
"Score": "0",
"body": "@Nurpax You might have been using older version of containers. It now has that. http://hackage.haskell.org/packages/archive/containers/0.4.2.1/doc/html/Data-Map.html#v:foldr-39-"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T11:44:25.007",
"Id": "26079",
"Score": "0",
"body": "Gotcha, I was running an old HP. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T11:56:17.953",
"Id": "26080",
"Score": "0",
"body": "@Nurpax Also just to mention that use fold is now deprecated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T07:48:47.753",
"Id": "26105",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/5978/discussion-between-nurpax-and-satvik)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T10:05:23.397",
"Id": "16029",
"ParentId": "16026",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16029",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T09:03:51.540",
"Id": "16026",
"Score": "3",
"Tags": [
"haskell",
"datetime",
"functional-programming"
],
"Title": "Filling gaps in time series data"
}
|
16026
|
<p>the following is my code for the Java class connection to mysql server, i need to see if there is any suggestion to make it better.</p>
<p>this class not making the connection, it just control transactions, selecting, updating & deleting.</p>
<pre><code>package database;
import java.sql.*;
import java.util.*;
import core.*;
public class CruesDataAccessor {
private PreparedStatement preparedStatement;
private PreparedStatement updateStatement;
private PreparedStatement insertStatement;
private PreparedStatement deleteStatement;
private ResultSet dataResultSet;
private Connection connection;
private Vector<String> columensDataTypes;
private Vector<String> columensNames;
private Vector<Object> queryDataVtr;
private Vector<Object> filteredColNames;
private int count = 0;
private Vector<Integer> colsWidth;
private String tablename;
// the constructor
public CruesDataAccessor(Connection conn) {
connection = conn;
try {
} catch (Exception e) {
myError(e, "1");
}
}
// setting connection
public void setConnection(Connection conn) {
connection = conn;
try {
} catch (Exception e) {
myError(e, "2");
}
}
// used to get the data based on a mysql statement
public void clearMe(){
columensDataTypes.removeAllElements();
columensNames.removeAllElements();
queryDataVtr.removeAllElements();
filteredColNames.removeAllElements();
colsWidth.removeAllElements();
}
public Vector<?> getData(String sqlStmnt) {
// remove illegal characters from the mysql statement
sqlStmnt = Declare.replaceIllegalChars(sqlStmnt);
//sqlStmnt = sqlStmnt.toLowerCase();
// used to fill the names of the columns
filteredColNames = new Vector<Object>();
queryDataVtr = new Vector<Object>();
columensNames = new Vector<String>();
// used to fill column widths
colsWidth = new Vector<Integer>();
try {
count = 0;
// a prepare a MySQL statement
preparedStatement = connection.prepareStatement(sqlStmnt);
// execute the query and get the result
dataResultSet = preparedStatement.executeQuery(sqlStmnt);
// get the types of the data
ResultSetMetaData resultSetMetaData = dataResultSet.getMetaData();
count = resultSetMetaData.getColumnCount();
columensDataTypes = new Vector<String>();
// parse the data and fill the necessary variables
for (int i = 0; i < count; i++) {
columensNames.addElement(resultSetMetaData.getColumnName(i + 1));
setTableName(resultSetMetaData.getTableName(1));
setFilteredColumnNames(resultSetMetaData.getColumnName(i + 1));
setColsWidth(resultSetMetaData.getColumnName(i + 1).length());
String dataType = resultSetMetaData.getColumnTypeName(i + 1);
if (dataType.indexOf("String") != -1) {
columensDataTypes.add("string");
} else if (dataType.indexOf("Date") != -1 ||
dataType.indexOf("Timestamp") != -1) {
columensDataTypes.add("date");
} else if ((dataType.indexOf("BigDecimal") != -1) ||
(dataType.indexOf("Integer") != -1) ||
(dataType.indexOf("Long") != -1)) {
columensDataTypes.add("number");
} else {
columensDataTypes.add("string");
}
}
// filling the information in a vector
Vector<String> recordVtr;
while (dataResultSet.next()) {
recordVtr = new Vector<String>();
for (int i = 0; i < count; i++) {
try {
recordVtr.addElement(dataResultSet.getString(i + 1));
} catch (SQLException ex1) {
recordVtr.addElement("");
}
}
queryDataVtr.add(recordVtr);
}
// closing
try {
dataResultSet.close();
dataResultSet = null;
} catch (Exception exx) {
myError(exx, "3");
dataResultSet = null;
}
} catch (Exception exx) {
try {
dataResultSet.close();
} catch (Exception ex) {
}
myError(exx, "4");
dataResultSet = null;
}
preparedStatement = null; //
return queryDataVtr;
}
// get the column names in a vector
public Vector<String> getColumnNames() {
return columensNames;
}
// filter the column names
public void setFilteredColumnNames(String str) {
boolean found = false;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '_') {
filteredColNames.add(str.substring(i + 1, str.length()));
found = true;
break;
}
}
if (!found) {
filteredColNames.add(str);
}
}
// get the types of the column fields
public Vector<String> getDataTypes() {
return this.columensDataTypes;
}
// get the filtered column names
public Vector<?> getfilteredColumNames() {
return filteredColNames;
}
// get the column counts
public int getColumnCount() {
return count;
}
// set default column widths
public void setColsWidth(int width) {
colsWidth.add(new Integer(100));
}
// get column widths
public Vector<Integer> getColumnsWidth() {
return colsWidth;
}
// used to update the database with an SQL statement
public synchronized boolean UpdateDB(String sql) {
sql = Declare.replaceIllegalChars(sql);
//sql = sql.toLowerCase();
int result = 0;
try {
updateStatement = connection.prepareStatement(sql);
result = updateStatement.executeUpdate();
updateStatement = null; //
} catch (SQLException sexx) {
myError(sexx, "5");
Declare.exCounter += 1;
// sexx.printStackTrace();
System.out.println("Erro: "+sexx);
} catch (Exception exx) {
System.out.println("Erro: "+exx);
// myError(exx, "6");
}
if (result == 1) {
return true;
} else {
return false;
}
}
// used to insert in the database with an SQL statement
public synchronized boolean InsertDB(String sql) {
sql = Declare.replaceIllegalChars(sql);
int result = 0;
try {
insertStatement = connection.prepareStatement(sql);
result = insertStatement.executeUpdate();
insertStatement = null; //
} catch (SQLException sexx) {
System.out.println("Erro: "+sexx);
myError(sexx, "7");
} catch (Exception exx) {
myError(exx, "8");
System.out.println("Erro: "+exx);
}
if (result == 1) {
return true;
} else {
return false;
}
}
// used to delete from the database with an SQL statement
public synchronized boolean DeleteDB(String sql) {
int result = 0;
try {
deleteStatement = connection.prepareStatement(sql);
result = deleteStatement.executeUpdate();
deleteStatement = null; //
} catch (Exception exx) {
myError(exx, "9");
System.out.println("Erro: "+exx);
}
if (result == 1) {
return true;
} else {
return false;
}
}
public void setTableName(String tablename) {
this.tablename = tablename;
}
public String getTableName() {
return this.tablename;
}
// used to lock the table
public synchronized boolean lockTable(String sql) {
//sql = sql.toLowerCase();
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate(sql);
stmt = null; //
} catch (SQLException sexx) {
myError(sexx, "14");
return false;
} catch (Exception exx) {
myError(exx, "15");
return false;
}
return true;
}
// used to unlock the table
public synchronized boolean unlockTable(String sql) {
//sql = sql.toLowerCase();
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate(sql);
stmt = null; //
} catch (SQLException sexx) {
myError(sexx, "16");
return false;
} catch (Exception exx) {
myError(exx, "17");
return false;
}
return true;
}
// use to start aut commit mode
public synchronized boolean initAutoCommit() {
try {
if(connection.getAutoCommit()){
System.out.println("SetAutoCommit = false");
connection.setAutoCommit(false);
}
} catch (SQLException sexx) {
myError(sexx, "18");
return false;
} catch (Exception exx) {
myError(exx, "19");
return false;
}
return true;
}
// use to begin the transaction
public synchronized boolean beginTransaction() {
Statement stmt = null;
Declare.exCounter = 0;
try {
stmt = connection.createStatement();
stmt.executeUpdate("START TRANSACTION;");
System.out.println("START TRANSACTION");
stmt = null; //
} catch (SQLException sexx) {
myError(sexx, "20");
return false;
} catch (Exception exx) {
myError(exx, "21");
return false;
}
return true;
}
// used to end the transaction
public synchronized boolean endTransaction() {
try {
connection.commit();
System.out.println("Transaction Commited");
} catch (SQLException sexx) {
// myError(sexx, "22");
System.out.println(sexx);
return false;
} catch (Exception exx) {
myError(exx, "23");
return false;
}
return true;
}
// used to rollback the transaction
public synchronized boolean rollBack() {
try {
connection.rollback();
System.out.println("Transaction Rolled Back");
} catch (SQLException sexx) {
myError(sexx, "24");
return false;
} catch (Exception exx) {
myError(exx, "25");
return false;
}
return true;
}
// used to modify the language
public synchronized boolean modifyLanguage(String sql) {
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate(sql);
stmt = null; //
} catch (SQLException sexx) {
myError(sexx, "26");
return false;
} catch (Exception exx) {
myError(exx, "27");
return false;
}
return true;
}
// a general error routine
private void myError(Exception c, String no) {
Declare.exCounter+= 1;
c.printStackTrace();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>scanned your code, good to go, just one thing-- by Convention Java methods start with lower case. \nSo, the method \"<strong>UpdateDB()</strong>\" better suit <strong>updateDb()</strong> or <strong>updateDatabase()</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T23:00:00.463",
"Id": "16245",
"ParentId": "16030",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T10:18:56.280",
"Id": "16030",
"Score": "4",
"Tags": [
"java",
"mysql"
],
"Title": "MySQL Java Connection with my application"
}
|
16030
|
<p>My goal was to create class, that can run external method in non blocking manner.
Second requirement was to be able to abort method run if it is needed (i.e. running user script).
I decided to do that with Thread instead of Task, because only Thread can be truly aborted.
Because Thread have big creation overhead, it is initialized and started in advance and resumed if work is needed.</p>
<p>What do you think about my implementation ?</p>
<p>Example usage:</p>
<pre><code>//generic type param is used as external method argument (instead of object)
AbortableStepWorker<int> worker = new AbortableStepWorker<int>(someMethodWithIntArgument);
worker.Start();
worker.DoWork(someArgument);
while(!worker.WaitForWorkDone(someTimeout))
if(cancelWasRequested)
{
worker.Stop(lastChanceTimeout);
return false;
}
//if we've managed to get here, then work was done
//run result:
var result = !worker.Stopped;
</code></pre>
<p>and class implementation:</p>
<pre><code>public class AbortableStepWorker<T> : IDisposable
{
public AbortableStepWorker(Func<T, bool> externalWork)
{
if (externalWork == null) throw new ArgumentNullException("workMethod");
this.externalWork = externalWork;
ThreadInstance = new Thread(Worker) { Priority = ThreadPriority.BelowNormal };
}
private readonly Func<T, bool> externalWork;
private T externalWorkParam;
private void Worker()
{
try
{
while (true)
{
resumeEvent.WaitOne(Timeout.Infinite);
if (stopRequested)
return;
if (!externalWork(externalWorkParam))
return;
workDoneEvent.Set();
}
}
catch (ThreadAbortException) { }
finally { workDoneEvent.Set(); }
}
private bool stopRequested = false;
private AutoResetEvent resumeEvent = new AutoResetEvent(false);
private ManualResetEvent workDoneEvent = new ManualResetEvent(false);
public Thread ThreadInstance { get; private set; }
public void Start()
{
ThreadInstance.Start();
}
/// <summary>
/// Allows inner thread to do externalWork call.
/// </summary>
public void DoWork(T param)
{
externalWorkParam = param;
workDoneEvent.Reset();
resumeEvent.Set();
}
/// <summary>
/// Waits for DoWork to finish.
/// </summary>
/// <param name="millisecondsTimeout">Timeout.</param>
/// <returns>True if work is not still running.</returns>
public bool WaitForWorkDone(int millisecondsTimeout)
{
return workDoneEvent.WaitOne(millisecondsTimeout);
}
/// <summary>
/// Waits specified time for worker method to end. If time elapsed, aborts thread.
/// </summary>
/// <param name="millisecondsTimeout">Timeout before thread abort.</param>
public void Stop(int millisecondsTimeout = 0)
{
if (Stopped)
return;
bool wasWorking = !workDoneEvent.WaitOne(0);
stopRequested = true;
resumeEvent.Set();
if (!ThreadInstance.Join(wasWorking ? millisecondsTimeout : Timeout.Infinite))
ThreadInstance.Abort();
}
public bool Stopped
{
get
{
return ThreadInstance.Join(0);
}
}
#region IDisposable
public void Dispose()
{
if (ThreadInstance.ThreadState != ThreadState.Unstarted)
{
Stop();
ThreadInstance.Join();
}
resumeEvent.Dispose();
workDoneEvent.Dispose();
}
#endregion //IDisposable
}
</code></pre>
|
[] |
[
{
"body": "<p><a href=\"https://stackoverflow.com/a/1560567/41071\"><strong>You should never use <code>Thread.Abort()</code>.</strong></a> If you don't have control over the code that's executing in the thread, then you don't know what will that abort do. It's quite possible it will leave some object in an inconsistent state, or something like that. If you do have control over the code, you should instead use cooperative cancellation using <code>CancellationToken</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T07:01:43.270",
"Id": "26103",
"Score": "0",
"body": "I don't have control over the external method, that's why I cannot use CancellationToken mechanism.\n\nI cannot agree that we should never use Thread.Abort(). We should just avoid using it if that is possible:\nhttp://stackoverflow.com/questions/4359910/is-it-possible-to-abort-a-task-like-aborting-a-thread-thread-abort-method\n\nI put all effort to ensure nice cancelation. I try to abort thread only if external method hanged. Then I'm catching ThreadAbortException.\n\nThe question is, could it be done better ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-07T22:51:04.183",
"Id": "155396",
"Score": "0",
"body": "@Kuba The best way to ensure nice cancellation of external code is to kill the process :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T00:29:49.360",
"Id": "16045",
"ParentId": "16036",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T17:55:40.130",
"Id": "16036",
"Score": "3",
"Tags": [
"c#",
"multithreading",
"delegates"
],
"Title": "Cancelable thread worker"
}
|
16036
|
<p>In the book <em>Real World Haskell</em>, the author writes in the first line of every file that uses, for example the following: <code>file: ch05/PrettyJSON</code>. The chapter slash and the name of a module.</p>
<p>I wanted to create a script which reads the first line and copies the files to the appropriate directory. In the above example we should copy the file to the directory ch05. I wanted to write this in Haskell in order to use it for "real world" applications.</p>
<p>But before starting writing to Haskell I wrote it in Python:</p>
<pre><code>import os
import shutil
current_dir = os.getcwd()
current_files=os.listdir(current_dir)
haskell_files=filter(lambda x:x.find(".hs")!=-1,current_files)
for x in haskell_files:
with open(x,"r") as f:
header=f.readline()
try:
chIndex=header.index("ch")
except ValueError as e:
continue
number=header[chIndex:chIndex+4]
try:
os.mkdir(number)
shutil.copy2(x,number)
except OSError as e:
shutil.copy2(x,number)
</code></pre>
<p>And then I tried to write the same code in Haskell:</p>
<pre><code>f x = dropWhile (\x-> x/='c') x
g x = takeWhile (\x-> x=='c' || x=='h' || isDigit x) x
z= do
y<-getCurrentDirectory
e<-getDirectoryContents y
let b=findhs e
mapM w b
findhs filepaths = filter (isSuffixOf ".hs") filepaths
w filename= do
y<-readFile filename
let a=(g.f) y
if "ch" `isPrefixOf` a
then do
createDirectoryIfMissing False a
g<-getCurrentDirectory
writeFile (g ++"/"++ a ++ "/" ++ filename) y
else
return ()
main=z
</code></pre>
<p>Haskell code should be more elegant and more compact but it is not. Can you give me suggestions on making the above program more Haskellish?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T14:04:02.660",
"Id": "26085",
"Score": "0",
"body": "A few links for scripting shell tasks in Haskell: [Haskell shell examples](http://www.haskell.org/haskellwiki/Applications_and_libraries/Operating_system#Haskell_shell_examples), [Shelly: Write your shell scripts in Haskell](http://www.yesodweb.com/blog/2012/03/shelly-for-shell-scripts), [Practical Haskell Programming: Scripting with Types](http://www.scribd.com/doc/36045849/Practical-Haskell-Programming-scripting-with-types)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T09:00:18.970",
"Id": "26091",
"Score": "1",
"body": "Interesting question though. I think it breaks down to: How to code a completely sequential thing in \"good\" Haskell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T09:51:23.327",
"Id": "26092",
"Score": "1",
"body": "You 've got the point @JFritsch. Can we write \"good\" sequential Haskell programs? This is the real question. Because if we want to do \"Real World Haskell\" I think that we should know how to write sequential code in Haskell."
}
] |
[
{
"body": "<p>The first thing you note is that although haskellers like one character variable names in a small scope, we do not like one character functions in a global scope.</p>\n\n<p>There is an implicit partial function in your code. The function that gets the chapter name from the file (called <code>getChapter</code> in the code below), which takes strings (the content of the file) and gives a chapter name if it exists in the string. This seems like a good idea to make explicit using the <code>Maybe</code> type so that this fact does not need to be expressed in the control flow of the program. Note that I have split the getting of the chapter from the contents into the pure part (looking at the string) and the impure part (reading the file), this might be overkill but it's nice to remove impure functions whenever possible.</p>\n\n<pre><code>type Chapter = String\n\ngetChapter :: String -> Maybe Chapter\ngetChapter ('c':'h':xs) = Just ('c':'h': takewhile isDigit xs)\ngetChapter (_:xs) = getChapter xs\ngetChapter [] = Nothing\n\nmain :: IO ()\nmain = do \n dir <- getCurrentDirectory\n files <- getDirectoryContents dir\n mapM_ process (filter (isPrefixOf \".hs\") files)\n\nprocess :: FilePath -> IO ()\nprocess fileName = do\n chapter <- liftM getChapter (readFile fileName)\n when (isJust chapter)\n (copyToChapter fileName (fromJust chapter))\n\ncopyToChapter :: FilePath -> Chapter -> IO ()\ncopyToChapter fileName chapter = do\n createDirectoryIfMissing False chapter\n copyFile fileName (chapter ++ \"/\" ++ fileName)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T11:56:36.010",
"Id": "26115",
"Score": "0",
"body": "Your getChapter is slightly broken, as it takes only the first digit of the chapter. Also, you waste a lot of time reading the whole file, if the chapter is not specified."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T19:12:05.070",
"Id": "26127",
"Score": "0",
"body": "@KarolisJuodelΔ I fixed the single digit thing. About wasting a lot of time: The original solution does that too (`dropWhile (/='c')`) so I just thought it was part of the specification."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T12:22:35.383",
"Id": "16032",
"ParentId": "16038",
"Score": "3"
}
},
{
"body": "<pre><code>getChapter :: String -> IO (Maybe String)\ngetChapter name = if \".hs\" `isSuffixOf` name then do\n ln <- withFile name ReadMode hGetLine\n return $ fmap (take 4) $ find (\"ch\" `isPrefixOf`) $ tails ln\n -- note, this is what your Pythod code does\n else return Nothing\n\ncopyToChapter :: String -> String -> IO ()\ncopyToChapter file chapter = do\n createDirectoryIfMissing False chapter\n copyFile file (chapter ++ \"/\" ++ file)\n\nprocess :: String -> IO ()\nprocess file = do\n chapter <- getChapter file\n maybe (return ()) (copyToChapter file) chapter\n\nmain = do \n dir <- getCurrentDirectory\n files <- getDirectoryContents dir\n mapM process files \n</code></pre>\n\n<p>This should be an improvement. Note that this is actually longer. Of course, you could write</p>\n\n<pre><code>getChapter name = if \".hs\" `isSuffixOf` name then withFile name ReadMode hGetLine >>= return . fmap (take 4) . find (\"ch\" `isPrefixOf`) . tails\n else return Nothing\ncopyToChapter file chapter = createDirectoryIfMissing False chapter >> copyFile file (chapter ++ \"/\" ++ file)\nprocess file = getChapter file >>= maybe (return ()) (copyToChapter file)\nmain = getCurrentDirectory >>= getDirectoryContents >>= mapM process\n</code></pre>\n\n<p>if you like few lines of code. I'd advise against it though.</p>\n\n<p>In general, you should not expect Haskell to be better at procedural tasks than procedural languages.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T14:18:36.793",
"Id": "26093",
"Score": "3",
"body": "`hould not expect Haskell to be better at procedural tasks than procedural languages.` -- but note that because of monads, structuring procedural programs is a lot easier as code blocks are first class. error handling may also be simplified thanks to monads. Abstraction capaabilities always help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T10:01:43.267",
"Id": "16039",
"ParentId": "16038",
"Score": "1"
}
},
{
"body": "<p>Notes:</p>\n\n<ul>\n<li>don't use single letter variable names for top level bindings</li>\n<li>leave spaces around syntax like <code>=</code> and <code><-</code></li>\n<li>use meaningful variable names for system values (such as file contents)</li>\n<li>inline single uses of tiny functions, such as your <code>findhs e</code></li>\n<li>give your core algorithm, <code>w</code>, a meaningful name</li>\n<li>don't use long names for local parameters like <code>filepaths</code>. <code>fs</code> is fine.</li>\n<li>use pointfree style for arguments in the final position</li>\n<li>use <code>when</code> instead of <code>if .. then ... else return ()</code></li>\n<li>use the filepath library for nice file path construction</li>\n<li>your only use of <code>f</code> and <code>g</code> is to compose them. so do that and name the result.</li>\n<li>use section syntax for lambdas as function arguments to HOFs</li>\n<li>indent consistently</li>\n<li>use <code>mapM_</code> when the result you don't care about.</li>\n</ul>\n\n<p>Resulting in:</p>\n\n<pre><code>import Data.Char\nimport Data.List\nimport Control.Monad\nimport System.Directory\nimport System.FilePath\n\nclean = takeWhile (\\x -> x == 'c' || x == 'h' || isDigit x)\n . dropWhile (/='c')\n\nprocess path = do\n y <- readFile path\n\n let a = clean y\n\n when (\"ch\" `isPrefixOf` a) $ do\n createDirectoryIfMissing False a\n g <- getCurrentDirectory\n writeFile (g </> a </> path) y\n\nmain = do\n y <- getCurrentDirectory\n e <- getDirectoryContents y\n mapM_ process $ filter (isSuffixOf \".hs\") e\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T15:00:17.843",
"Id": "26094",
"Score": "0",
"body": "much nicer. `getCurrentDirectory` is superfluous though - in the `when` clause don't need `g`, and in `main`, you can replace `y` with `\".\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T15:08:48.447",
"Id": "26095",
"Score": "1",
"body": "In the sense of the original python code, the name of target directory has to be computed as `take 4 <$> find (isPrefixOf \"ch\") (tails y)` where `y` is extracted from `head . lines <$> readFile path` ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T16:03:12.673",
"Id": "26367",
"Score": "1",
"body": "`main` can be written as `main = getCurrentDirectory >>= getDirectoryContents >>= mapM_ process . filter (isSuffixOf \".hs\")`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-13T18:24:00.143",
"Id": "176940",
"Score": "0",
"body": "@nponeccop Much more monadic!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T14:16:46.280",
"Id": "16040",
"ParentId": "16038",
"Score": "17"
}
},
{
"body": "<p>Other way you could write your Shell-like scripts in Haskell is using <a href=\"http://hackage.haskell.org/package/shelly\" rel=\"nofollow\">Shelly</a> library. It provides functionality specifically suited for such tasks, kind of DSL, which brings you more brevity. <a href=\"https://github.com/yesodweb/Shelly.hs/blob/master/README.md\" rel=\"nofollow\">Its GitHub page</a> contains a bunch of usefull links with examples.</p>\n\n<p>E.g. Don's program could be rewritten to:</p>\n\n<pre><code>{-# LANGUAGE OverloadedStrings #-}\nimport Data.Text.Lazy as LT\nimport Data.Text.Lazy.IO as LTIO\nimport Prelude as P hiding (FilePath)\nimport Data.Char\nimport Shelly\n\nclean = LT.takeWhile (\\x -> x == 'c' || x == 'h' || isDigit x)\n . LT.dropWhile (/='c')\n\nreadFileP = liftIO . LTIO.readFile . unpack . toTextIgnore\n\nprocess path = shelly $ do\n y <- readFileP path\n let a = clean y\n\n when (\"ch\" `LT.isPrefixOf` a) $ do\n let p = fromText a\n mkdir_p p\n cp path p\n\nmain = shelly $ do\n e <- ls \".\"\n mapM_ process $ P.filter (hasExt \"hs\") e\n</code></pre>\n\n<p>The only flaw here is a bit bloated <code>readFileP</code>. I did not find a better way (which might be due to my beginner level). Possibly such function could become a part of <code>Shelly</code> library itself.</p>\n\n<p>So far I found combination of Haskell and Shelly quite good as \"a scripting language for every day task\" and start to rewrite my scripts utilizing Shelly. That is a nice entrance gateway to Haskell language itself for me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T17:34:07.040",
"Id": "16041",
"ParentId": "16038",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16040",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T08:26:35.393",
"Id": "16038",
"Score": "15",
"Tags": [
"python",
"haskell"
],
"Title": "Script for copying files to the appropriate directory"
}
|
16038
|
<p>I wanted something more flexible than System.Collections.ObjectModel.ReadOnlyCollection.
The goal was: consuming classes should only see what I want to show them, not whole underlying collection.</p>
<p>For example: I have an array of 10 elements. If I want to show consumer only first 5 elements, I don't want to create new List and rewrite that data.
Another example: I want to show consumer reordered collection, why create new List and rewrite all ?</p>
<p>Here is interface (.NET version defined in 4.5):</p>
<pre><code>public interface IReadOnlyCollection<out T> : IEnumerable<T>
{
T this[int index] { get; }
int Count { get; }
}
</code></pre>
<p>and implementation (not tested yet):</p>
<pre><code>public delegate T ProxiedIndexer<out T>(int index);
public class ProxiedReadOnlyCollection<T> : IReadOnlyCollection<T>, IEnumerable<T>
{
public ProxiedReadOnlyCollection(ProxiedIndexer<T> indexer, Func<int> countGetter)
{
this.indexer = indexer;
this.countDelegate = countGetter;
}
#region IReadOnlyCollection
/// <summary>
/// Override to decorate in fly.
/// </summary>
public virtual T this[int index]
{
get
{
if (index < 0 || index >= countDelegate())
throw new IndexOutOfRangeException();
return indexer(index);
}
}
public int Count { get { return countDelegate(); } }
private readonly ProxiedIndexer<T> indexer;
private readonly Func<int> countDelegate;
#endregion //IReadOnlyCollection
#region IEnumerable
public IEnumerator<T> GetEnumerator()
{
return this.Enumerate().GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
private IEnumerable<T> Enumerate()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
#endregion //IEnumerable
</code></pre>
<p>Useful extensions:</p>
<pre><code>public static IReadOnlyCollection<T> AsReadOnly<T>(this IList<T> list)
{
return new ProxiedReadOnlyCollection<T>(i => list[i], () => list.Count);
}
public static IReadOnlyCollection<T> AsReadOnly<T>(this T[] array)
{
return new ProxiedReadOnlyCollection<T>(i => array[i], () => array.Length);
}
public static IReadOnlyCollection<T> AsReadOnly<T>(this IEnumerable<T> enumerable)
{
return enumerable.ToArray().AsReadOnly();
}
public static IReadOnlyCollection<T> Reverse<T>(this IReadOnlyCollection<T> readOnlyCollection)
{
return new ProxiedReadOnlyCollection<T>(i => readOnlyCollection[readOnlyCollection.Count - 1 - i], () => readOnlyCollection.Count);
}
</code></pre>
<p>What do you think about my implementations and other possible class use cases ?</p>
<p><strong>EDIT</strong></p>
<p>To understand how this 'collection' works lets look at constructor. It needs two delegates:</p>
<ul>
<li>indexer - for given index it returns T (this is exposed to consumer as T this[int index])</li>
<li>countGetter - just returns element count</li>
</ul>
<p>So the whole point is that consumer sees it as indexed collection, but there is no real collection at all. It is similar to IEnumerable's yield (generating items on demand, not storing them).</p>
<p><strong>Performance (on i7-2760, Win7):</strong></p>
<p>Iterating all elements:</p>
<pre><code> var enumerable = Enumerable.Range(0, 100000000);
var list = enumerable.ToList();
int x;
var frameworkReadOnly = new ReadOnlyCollection<int>(list);
var start = DateTime.Now;
for (int i = 0; i < list.Count; i++)
x = frameworkReadOnly[i];
Console.WriteLine((DateTime.Now - start).TotalMilliseconds);//632 ms
var proxiedReadOnly = list.AsReadOnly();
start = DateTime.Now;
for (int i = 0; i < proxiedReadOnly.Count; i++)
x = proxiedReadOnly[i];
Console.WriteLine((DateTime.Now - start).TotalMilliseconds);//935 ms
</code></pre>
<p>ProxiedReadOnlyCollection is ~ 50% slower.
It's even worse when we change initialization to:</p>
<pre><code>var proxiedReadOnly = new ProxiedReadOnlyCollection<int>(i => i, () => 100000000);
</code></pre>
<p>1633 ms => ~160% slower</p>
<p>It's slower significantly. But have in mind what we were measuring. These were access times. Lets measure creation times:</p>
<pre><code>var enumerable = Enumerable.Range(0, 100000000);
var list = enumerable.ToList();
var frameworkReadOnly = new ReadOnlyCollection<int>(list);
</code></pre>
<p>1468 ms</p>
<pre><code>var proxiedReadOnly = new ProxiedReadOnlyCollection<int>(i => i, () => 100000000);
</code></pre>
<p>1 ms</p>
<p>Total times:</p>
<ul>
<li>framework collection: 2100 ms</li>
<li>proxied collection: 1634 ms</li>
</ul>
<p><strong>Conclusions:</strong></p>
<p>Although access time for proxied collection is bigger, it has no creation overhead and could be faster when iterating all elements once. That's the key - one time. If consumer would iterate all elements several times, then framework's ReadOnlyCollection is faster.</p>
<p>Of course there is also memory benefit (proxied collection does not remember elements, it only serves them on demand).</p>
<p>Serving elements on demand could be implemented as lazy object initialization, which has its own benefits.</p>
<p>Cons:
Slower performance when it comes to accessing elements many times. In some cases we cannot predict element at specified index, so creating them on demand is not an option. Other time we just want to create items in advance.</p>
<p>For me it's just a tool, that can do some tasks better than .NET ReadOnlyCollection and other worse.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T04:35:02.577",
"Id": "26098",
"Score": "0",
"body": "I think it's a nice abstraction, but could you please add some usage cases?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T12:41:21.683",
"Id": "26117",
"Score": "0",
"body": "Edited original post. Added performance measurements + pros/cons, which should help to answer when to use it.\nOriginally I created this class for some script algorithm simulations, but I don't want to show this use case here (lots of code and niche)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T12:29:36.520",
"Id": "26270",
"Score": "1",
"body": "The only problem I have here is that you haven't yet stated the problem. I say that because without knowing the problem it's not possible for us to know if this is the ___right___ solution. Can you state the actual problem (even if it's a fabrication to protect your niche)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:06:42.923",
"Id": "26301",
"Score": "0",
"body": "This is supposed to be lazy indexing collection proxy. Actually I don't have a problem with implementation. Main reason for posting this was: am I doing it right ? Were you doing something similar ? What do you think about my approach ? This is how I understand \"code review\"."
}
] |
[
{
"body": "<p>I don't see how would this be useful.</p>\n\n<p>If you want to return the first 5 items from a collection, use LINQ: <code>Take(5)</code>. This will return <code>IEnumerable</code>, but that's most likely okay.</p>\n\n<p>If you want to return reordered collection and don't want to modify the original list, you do need to create the sorted list, so your code won't be useful in that case either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T07:29:14.650",
"Id": "26104",
"Score": "0",
"body": "\"I don't see how would this be useful...\"\nI think you are missing the point that I am working with indexed collections.\n\nTake(5) will return IEnumerable, as you said. Then we have to make list from it and only then we are able to create .NET's ReadOnlyCollection.\n\nOrdering IEnumerable collection has huge overhead. Reversing IEnumerable is also unnecessary if we already have indexed collection."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T00:36:09.693",
"Id": "16046",
"ParentId": "16044",
"Score": "1"
}
},
{
"body": "<p>The ReadOnlyCollection has all the IEnumerable extension methods so on the other side anyone can call on that a ToList() so you will loose the read-only-thing. You are reinventing the wheel for no real reason.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T08:28:15.923",
"Id": "26107",
"Score": "0",
"body": "Am I ?\nYou are expecting second WriteLine in following code to print '5' ?\n var collection = new ReadOnlyCollection<int>(new List<int>(new int[] { 0 }));\n Console.WriteLine(collection[0]);\n collection.ToList()[0] = 5;\n Console.WriteLine(collection[0]);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T09:06:32.953",
"Id": "26109",
"Score": "0",
"body": "It will write out 0 but this is becouse integers are value types try this with a simple POCO class (one int type auto property)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T10:51:25.443",
"Id": "26113",
"Score": "0",
"body": "I was afraid that you would write that this is value type case :|\nThat's not the case. If you would write: readOnlyCollection.ToList()[0] = new FooClass();then readOnlyCollection[0] still returns old reference.\nIf collection is hosting reference types that support state change (through properties, methods, whatever), then they could be changed. But that's different context. You cannot blame ReadOnlyCollection for this. In this case it doesn't matter if objects are hosted in ReadOnlyCollection, List, Array or other IEnumerable implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T11:35:14.037",
"Id": "26114",
"Score": "0",
"body": "Now i know that you are familiar with all these stuff i understand what you are like to tell us and the idea is not bad but i still think is unnecessary. With your solution the other side will enumerate on the collection through your collection and maybe not only once which will be slover then creating a brand new list (IEnumerable.ToList<T> is watching after ICollection implementation!)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T12:25:12.367",
"Id": "26116",
"Score": "0",
"body": "I have edited original post to add performance measurements and some conclusions."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T08:11:28.520",
"Id": "16052",
"ParentId": "16044",
"Score": "0"
}
},
{
"body": "<p>That seems like way to much work to test and maintain for an improvement that needs to be measured in milliseconds (and that's only under the circumstances of your test case).</p>\n\n<p>(Developer cycles are more valuable than CPU cycles!)</p>\n\n<p>You'd be better off just using the BCL ReadOnlyCollection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T17:54:39.550",
"Id": "26123",
"Score": "1",
"body": "It depends. In performance measurement example I used 100 million item collection. ReadOnlyCollection needed > 400 mb memory. What if collection is to big to fit in the memory ?\n\nTime performance improvement is connected to concrete scenario. Think about binary search. There would be huge gain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T18:19:42.993",
"Id": "26124",
"Score": "0",
"body": "Yes, but if you are working on a project that actually requires you to process a 100 million item collection, then you can probably afford to buy more RAM and CPU power (which would actually cost less in the long-run than paying you to create/maintain a more efficient ReadOnlyCollection class)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T18:44:10.927",
"Id": "26125",
"Score": "0",
"body": "Maybe I wrote wrong examples. Think of my implementation like indexed brother of IEnumerable's yield. Collection is providing elements on demand and does not store them - creates them in fly (we could decorate it to do caching but that is different story)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T17:35:48.227",
"Id": "16060",
"ParentId": "16044",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T22:30:56.387",
"Id": "16044",
"Score": "3",
"Tags": [
"c#",
"collections",
"generics"
],
"Title": "ReadOnlyCollection - my alternative to .NET one"
}
|
16044
|
<p>I'm trying to write a function that finds the largest two numbers from a list of positive integers in Clojure.</p>
<p>I've toyed around with Scheme in the past, but I'm very new to Clojure. This is what I came up with:</p>
<pre><code>; Accumulator function for reduce later
(defn top-two [acc x]
(let [big1 (first acc) big2 (second acc)]
(cond
(> x big1) [x big1]
(> x big2) [big1 x]
:else acc)))
(defn top-two-list [coll]
(reduce top-two [0 0] coll))
</code></pre>
<p>This works, but I'm wondering if there is a way to simplify the <code>top-two</code> function, or to make this more readable or idiomatic.</p>
<p>This could be done much simpler if I was willing to sort the entire list, but I'm looking for an O(n) solution.</p>
<p>Any thoughts?</p>
|
[] |
[
{
"body": "<p>This looks like a clean way to find the max two elements. It can be shortened a little bit with destructuring:</p>\n\n<pre><code>; Accumulator function for reduce later\n(defn top-two [[big1 big2 :as acc] x]\n (cond\n (> x big1) [x big1]\n (> x big2) [big1 x]\n :else acc))\n\n(defn top-two-list [coll]\n (reduce top-two [0 0] coll))\n</code></pre>\n\n<p>You could also write something like so:</p>\n\n<pre><code>(defn top-two [coll]\n (let [big1 (apply max coll)\n big2 (apply max (remove #(= big1 %) coll))]\n [big1 big2]))\n</code></pre>\n\n<p>But I think it is programmer preference which you prefer. Both solutions are O(n), however the second ends up scanning the list twice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T18:48:17.937",
"Id": "26126",
"Score": "0",
"body": "Thanks much, I thought there must be something like this destructuring concept."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T09:49:40.017",
"Id": "16053",
"ParentId": "16047",
"Score": "4"
}
},
{
"body": "<p>An alternative way of finding the largest two numbers in a list would be:</p>\n\n<pre><code>(take 2 (sort > coll))\n</code></pre>\n\n<p>Sort the collection using the <code>></code> function as a comparator then take the first 2 values.</p>\n\n<p>For example:</p>\n\n<pre><code>user=> (take 2 (sort > [6 5 3 1 7 4 9 2 0 8]))\n(9 8)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T10:51:24.127",
"Id": "133897",
"Score": "1",
"body": ":) Well, yes, sorting makes such an exercise trivial -- and significantly slower."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-14T20:29:29.747",
"Id": "73627",
"ParentId": "16047",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16053",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T01:14:04.123",
"Id": "16047",
"Score": "3",
"Tags": [
"clojure"
],
"Title": "Find largest two numbers from list using clojure"
}
|
16047
|
<p>I have 2 input fields to input the duration of a CD song. The first input is for minutes and the second is for seconds</p>
<p>When submitting the form, I must insert in the db the duration either in seconds (minutes + seconds) or <code>NULL</code>.</p>
<p>Here's my validation formula:</p>
<pre><code>$warning = array();
function val_duration($min, $sec, $required = false) {
global $warning;
if (!empty($min) || !empty($sec)) {
if (!empty($min) && (!is_numeric($min) || !ctype_digit($min) || $min > 60)) {
$warning['min'] = 'The minutes must contain a positive numeric value between 1 and 60';
} else {
$min_in_sec = $min * 60;
}
if (!empty($sec) && (!is_numeric($sec) || !ctype_digit($sec) || $sec > 59)) {
$warning['sec'] = 'The seconds must contain a positive numeric value between 1 and 59';
} else {
$tmpsec = $sec;
}
$value = $min_in_sec + $tmpsec;
} else {
if ($required) {
$warning['duration'] = "The duration is a required field";
}
$value = NULL;
}
return $value;
}
// HTML
<input id="min" name="min" type="text" value="...">
<input id="sec" name="sec" type="text" value="...">
// validate
$min = ltrim(trim($_POST['min']), '0');
$sec = ltrim(trim($_POST['sec']), '0');
$duration_in_secs = val_duration($min, $sec, true); // duration
// mySQL
enter $duration_in_secs in db (either seconds or NULL)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T06:40:09.883",
"Id": "26102",
"Score": "3",
"body": "`$warning` doesn't seem to be accessible outside of the function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T15:14:07.727",
"Id": "26121",
"Score": "1",
"body": "true. i edited my code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T08:23:28.067",
"Id": "26175",
"Score": "0",
"body": "Is the maximum length of the song 59 minutes 59 seconds? And what if the user wants to input 2.5 minutes as `150 seconds` (maybe they are getting that info in total seconds from a different source/app and don't want to make the conversion)?"
}
] |
[
{
"body": "<ol>\n<li><p>I'm not familiar with PHP too much but <a href=\"https://stackoverflow.com/a/5166527/843804\">globals are usually considered harmful</a>. I don't know what's the best practice in PHP but passing the <code>$warning</code> argument by reference seems a good idea here.</p></li>\n<li><p>When a field is not posted you get various PHP notices. I guess it's better to avoid these notices:</p>\n\n<pre><code>PHP Notice: Undefined index: min in /tmp/x.php on line ...\nPHP Notice: Undefined index: sec in /tmp/x.php on line ...\n</code></pre>\n\n<p>A robust code should handle these cases.</p></li>\n<li><p><code>tmpsec</code> and <code>min_in_sec</code> are not initialized in every code paths, so you can get notices about these too when there is no <code>min</code> key in the <code>$_POST</code> array:</p>\n\n<pre><code>PHP Notice: Undefined variable: tmpsec in /tmp/x.php on line 24\nPHP Notice: Undefined variable: min_in_sec in /tmp/x.php on line 2\n</code></pre>\n\n<p>I think it's cleaner to initialize all variables. It also could help debugging since you don't have to ignore lots of PHP notice messages when you are looking for an <a href=\"https://stackoverflow.com/a/4261200/843804\">uninitialized global variable</a>.</p></li>\n<li><p><code>tmpsec</code> and <code>min_in_sec</code> could be omitted if you reorganize the code to not count anything until it is sure that there isn't any input error. (See below.)</p></li>\n<li><p>A small note: The function is a little bit inconsistent: it allows <code>60</code> as minute but doesn't as seconds. It would be cleaner and more common to set one hour as hours = 1, minutes = 0 and seconds = 0.</p></li>\n</ol>\n\n\n\n<pre><code>$warning = array();\n\nfunction val_duration(&$warning, $min, $sec, $required = false) {\n if (empty($min) && empty($sec)) {\n if ($required) {\n $warning['duration'] = \"The duration is a required field\";\n }\n return NULL;\n }\n\n if (!ctype_digit($min) || $min > 61) {\n $warning['min'] = 'The minutes must contain a positive numeric value between 1 and 60';\n }\n if (!ctype_digit($sec) || $sec > 59) {\n $warning['sec'] = 'The seconds must contain a positive numeric value between 1 and 59';\n }\n if (!empty($warning)) {\n return NULL;\n }\n\n return $min * 60 + $sec;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T20:13:17.217",
"Id": "26129",
"Score": "1",
"body": "val_duration($warning, 1, 1) will produce warning. Also var_duration($warning, \"-1\", \"10\") will produce -70. See my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T17:09:16.880",
"Id": "26152",
"Score": "0",
"body": "@sasa: Thanks, I've not noticed this bug (it's in the original code too). Maybe I'm too tired but I could not reproduce the second one. It puts a message to the `warning` array and returns `NULL` instead of only returning `-70`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T17:51:43.327",
"Id": "16061",
"ParentId": "16049",
"Score": "3"
}
},
{
"body": "<p>Here are some tips:</p>\n\n<ul>\n<li>The name of the function should be clearer.</li>\n<li>Try to avoid <code>ctype_digit</code> usage, because it may produce unexpected results - <code>ctype_digit(42)</code> returns <code>FALSE</code>.</li>\n<li>Because you are working with integers, you should cast values to integers. Note that inputs are always strings.</li>\n<li>You must check for negative values as well.</li>\n<li>Second can be 0. For example: 2 min and 0 sec. Also, some songs can last less than a minute (classic songs)</li>\n<li>Consider that some CD songs may have a duration of more than 60 mins, CD medium can store 80 mins (and it can be one song), and some mix or classic songs. So, maybe you should avoid a minute check.</li>\n</ul>\n\n<p></p>\n\n<pre><code><?php\n$warning = array();\n\n\n/**\n * Validate song duration\n * @param $min\n * @param $sec\n * @param $required\n * @return int|NULL\n */\nfunction validate_duration($min, $sec, $required = false) {\n global $warning;\n\n $min = (int) $min;\n $sec = (int) $sec;\n\n if($required && $min == 0 && $sec == 0) {\n $warning['duration'] = \"The duration is a required field.\";\n return NULL;\n }\n\n if($sec < 0 OR $sec > 59) {\n $warning['sec'] = 'The seconds must be between 0 and 59';\n }\n\n if($min < 0 OR $min > 60) {\n $warning['min'] = 'The minutes must be between 0 and 60';\n }\n\n // for songs bigger then 60 minutes\n if($min == 60 && $sec > 0) {\n $warning['duration'] = \"Song must last more then one second and maximum 60 minutes.\";\n }\n\n return !empty($warning) ? $min * 60 + $sec : NULL;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T20:10:17.623",
"Id": "16062",
"ParentId": "16049",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16062",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T05:18:13.930",
"Id": "16049",
"Score": "2",
"Tags": [
"php",
"datetime",
"converting"
],
"Title": "Converting minutes and seconds in seconds"
}
|
16049
|
<p>I have a problem from UVA online judge <a href="http://uva.onlinejudge.org/external/104/10474.html" rel="nofollow">here</a>. I have read it tons of times, and as they said, I have to get the answer really fast. </p>
<p>I have used a binary search and <code>std::sort</code>, but I am still having a time error. I don't know any faster way of searching on an array other than binary search. </p>
<p>Any feedback please?</p>
<pre><code>#include <stdio.h>
#include <string>
#include <algorithm>
int n,q,vec[100000];
int inicio,final,medio,busca;
int cont;
int busquedabinaria()
{
//busqueda binaria
std::sort(vec,vec+n);
inicio=0;
final=n-1;
medio=(inicio+final)/2;
while(inicio<=final)
{
if(vec[inicio]==busca)
return inicio;
if(vec[medio]==busca)
return medio;
if(vec[final]==busca)
return final;
medio = (inicio + final) / 2;
if (vec[medio] > busca)
final = medio - 1;
else if (vec[medio] < busca)
inicio = medio + 1;
// found
}
return -1;
}
int main()
{
freopen("in.txt", "rt",stdin);
freopen("out.txt", "wt",stdout);
while (scanf("%d %d\n",&n,&q)!=EOF && (n!=0 || q!=0) )
{
for (int i=0;i<n;i++)
{
scanf("%d\n",&vec[i]);
}
printf("CASE# %d:\n",cont+1);
cont++;
while(q--)
{
scanf("%d\n",&busca);
int res=busquedabinaria();
if(res!=-1)
{
while (vec[res-1]==busca && res>0)
{
res--;
}
printf("%d found at %d\n",busca,res+1);
}
else
printf("%d not found\n",busca);
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T13:32:41.797",
"Id": "26119",
"Score": "0",
"body": "I know that in UVa OJ, your program should read from standard input and write to standard output. You are reading from \"in.txt\" so no input is provided to your program and it hangs till getting TLE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T17:02:51.297",
"Id": "26122",
"Score": "0",
"body": "Yes, but thats just for debbuging, when you submit it you should erease it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T15:58:03.353",
"Id": "26150",
"Score": "1",
"body": "The problem is you have applied a brute force technique to the problem. The quickest solution would be to work out a formula that allows you to calculate the count of each number. When Your input is `1 9999999` this technique will be infinitely quicker than a brute force approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T07:15:11.473",
"Id": "26172",
"Score": "2",
"body": "Do you want this code analysed as C++? Also, English identifiers would help."
}
] |
[
{
"body": "<p>Your solution is slow because it performs the sorting before every binary search! Just move the sorting to the line above the</p>\n\n<pre><code>printf(\"CASE# %d:\\n\",cont+1);\n</code></pre>\n\n<p>and you'll see the difference.</p>\n\n<p>I also add my solution just to see what's possible to optimize (it uses custom int reader, without sort and the binary search):</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#define SIZE 16*1024\n#define N 10001\nstatic unsigned int values[N];\nstatic int buffer_size = 0;\nstatic int buffer_pos = -1; \nstatic char buffer[SIZE];\n\nunsigned int readInt()\n{\n unsigned int value = 0;\n unsigned int digits = 0;\n char b;\n\n if (buffer_pos == -1)\n {\n buffer_size = fread(buffer, 1, SIZE, stdin);\n buffer_pos = 0;\n }\n\n while(buffer_size > 0)\n {\n\n if (buffer_pos == buffer_size)\n {\n buffer_size = fread(buffer, 1, SIZE, stdin);\n buffer_pos = 0;\n }\n\n while(buffer_pos < buffer_size) \n {\n b = buffer[buffer_pos++]; \n if (b == '\\n' || b == ' ') \n {\n return value;\n }\n else\n {\n value = value*10 + (b - '0');\n digits++;\n }\n }\n }\n return value;\n}\n\nint main(int argc, char **argv)\n{\n long time = clock();\n\n char buffer[8192];\n setvbuf(stdout, buffer, _IOFBF, sizeof(buffer)); \n unsigned int n, q, num, max, min, c = 0;\n\n while(1)\n {\n c++;\n n = readInt();\n q = readInt();\n\n if(n==0 && q==0) break;\n\n max = 0;\n min = N;\n memset(values, 0, N * sizeof(unsigned int)); \n\n for(unsigned int i=0; i<n; i++)\n {\n num = readInt();\n values[num]++;\n if(num > max) max = num;\n if(num < min) min = num;\n }\n\n unsigned int pos = 1, temp;\n for(unsigned int i=min; i <= max; i++)\n {\n if(values[i] !=0){\n temp = values[i];\n values[i] = pos;\n pos += temp;\n }\n\n }\n\n printf(\"CASE# %d:\\n\", c);\n unsigned qval;\n for(unsigned int i=0; i<q; i++)\n {\n qval = readInt();\n int ret = values[qval];\n if(ret == 0) \n printf(\"%d not found\\n\", qval);\n else \n printf(\"%d found at %d\\n\", qval, ret);\n }\n }\n //printf(\"Time (ms): %ld\\n\", clock()-time);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T09:19:13.973",
"Id": "27722",
"ParentId": "16050",
"Score": "3"
}
},
{
"body": "<p>As @cat_baxter points out, you are re-sorting the marbles before every query. You should do it once per test case.</p>\n\n<p>Your <code>busquedabinaria()</code> uses global variables everywhere. Pass the parameters properly β there's no excuse for that kind of sloppiness.</p>\n\n<p>If you're going to use <code>std::sort()</code>, why not also use <code>std::binary_search()</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T12:48:52.253",
"Id": "33065",
"ParentId": "16050",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27722",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T07:55:34.413",
"Id": "16050",
"Score": "3",
"Tags": [
"c++",
"performance",
"search",
"binary-search",
"time-limit-exceeded"
],
"Title": "UVA 10474 - \"Where is the marble?\" time limit"
}
|
16050
|
<p>So I'm writing a program to format names to title case and display them in alphabetic order. Any advice please? And how can i add more methods?</p>
<pre><code>public static void main (String [] args)
{
//local variables
string name1;
string name2;
myLib = new Library();
/******************** Start main method *****************/
//prompt user for first Name
System.out.print("Enter First Name : ");
name1 = Keyboard.readChar();
//prompt user for second
System.out.print("Enter Second Name : ");
name2 = Keyboard.readChar();
//Format names to Title Case
name1.replace(0, name1.length(), name1.toString().toLowerCase());
name2.replace(0, name2.length(), name2.toString().toLowerCase());
name1.setCharAt(0, Character.toTitleCase(name1.charAt(0)));
name2.setCharAt(0, Character.toTitleCase(name2.charAt(0)));
//clear the screen
myLib.clrscr();
//Display names in alphabet order
if (name1.toString().compareTo(name2.toString()) >= 0) {
System.out.println(name2 + " " + name1);
} else {
System.out.println(name1 + " " + name2);
}
//pause the screen
//myLib.pause();
} //end main method
} //end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T06:03:21.480",
"Id": "26139",
"Score": "1",
"body": "Could you post the `string` class too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-16T05:32:08.747",
"Id": "108902",
"Score": "0",
"body": "@palacsint First rename, then post. Calling a class `string` is confusing itself and using a lowercase class name is too strange in Java."
}
] |
[
{
"body": "<p>Create a List</p>\n\n<pre><code>List<String> al = new ArrayList<String();\n</code></pre>\n\n<p>and add (you can also use something like <code>while(! stringRead.isEmpty()) {..}</code> )</p>\n\n<pre><code>name = Keyboard.readChar()).toLowerCase();\nal.add(name.substring(0, 1).toUpperCase() + name.substring(1));\n</code></pre>\n\n<p><em>EDIT after comment</em></p>\n\n<p>1Β°) then Sort (the list is 'cloned') and print directly frome the Constructor <code>return</code><br> This solution is recommended to protect data published in a Web page.</p>\n\n<pre><code>System.out.println(new TreeSet<String>(al).toString());\n</code></pre>\n\n<p>2Β°) The List is sorted then printed</p>\n\n<pre><code>Collections.sort(al);\nSystem.out.println(al.toString());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T10:25:34.407",
"Id": "26142",
"Score": "0",
"body": "References to objects should be as generic as possible (i.e. `List<String> a1` is preferred over `ArrayList<String> a1`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T11:52:54.617",
"Id": "26144",
"Score": "0",
"body": "@lchau . Exact, thanks - A mistake I maid sometime : because Eclipse's completion is too useful, I forgot to refer to Interface by removing `Array`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T17:28:10.530",
"Id": "26153",
"Score": "0",
"body": "+1 and a note: `Collections.sort` would keep the duplicated elements in the list (unlike the `TreeSet` and other sets)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T07:51:03.057",
"Id": "16069",
"ParentId": "16063",
"Score": "1"
}
},
{
"body": "<p>Usually in these cases you can implement a <code>Comparator<String></code>. This way it'll be portable, and can make use of the <a href=\"http://docs.oracle.com/javase/tutorial/collections/index.html\" rel=\"nofollow\">Collections API</a> (e.g. <code>Collections.sort(collection, TITLE_CASE_COMPARATOR);</code>.</p>\n\n<pre><code>private static final Comparator<String> TITLE_CASE_COMPARATOR = new Comparator<String>() {\n @Override\n public int compare(String o1, String o2) { \n // null-safe checks\n // equal\n if (o1 == null && o2 == null) { return 0; }\n // greater than, implies o2 is null\n else if (o1 != null) { return 1; } \n // less than, implies o1 is null\n else if (o2 != null) { return -1; } \n\n // title case comparison here\n }\n};\n</code></pre>\n\n<p>Some other ideas/methods you can also consider:</p>\n\n<ul>\n<li>Check cases where title cases do not apply (just to name a few [there are more]: a, an, the, or)</li>\n<li>Think about <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=65\" rel=\"nofollow\">choosing the right collection</a>, some collections take a <code>Comparator</code> as an argument which maintains the order for you (depending when/where you want to display the sorted results)</li>\n<li>You might also consider a pretty formatting for it, such as the total of entries that were processed (maintaining a history of previous inputs)</li>\n<li>Additional considerations for handling input (empty input, ignoring invalid characters, duplicate entries)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T10:43:48.347",
"Id": "16074",
"ParentId": "16063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T21:06:27.590",
"Id": "16063",
"Score": "3",
"Tags": [
"java",
"homework",
"functional-programming"
],
"Title": "Format names to title case"
}
|
16063
|
<p>There can be a business or security requirement that certain fields on a model should never be exposed in an API. One approach to this is to tell the developers not to ever put the field in the API output, but I prefer to protect them at the model level because that's where the requirement actually is.</p>
<p>The goal of this is to have a simple way to specify fields that should be prevented from being exposed. This is one approach and I would love feedback both on the implementation and on the approach. Ideas and criticism are very welcome.</p>
<h3>Implementation - Extend ActiveRecord::Base</h3>
<pre><code># Provide a system for specifying private attributes that shouldn't be exposed
module ActiveRecord
class Base
class << self
# Instead of setting the instance variable when this is called, we only check
# if it's defined. It's only set when attr_private is called. This allows us
# to know if the model has ever set any private attributes or not
def private_attributes
instance_variable_defined?('@private_attributes') ? @private_attributes : []
end
def is_private_attribute?(name)
private_attributes.include?(name.to_sym)
end
protected
# Set the @private_attributes variable with an array of attribute symbols
def attr_private(*args)
(@private_attributes ||= []).push(*args.collect { |a| a.to_sym }).uniq!
end
# Specify public attributes, which conversely privatizes the other attributes
# If private attributes have previously been declared, attr_public can override
# the setting. If it is the first time, make all the attributes private unless
# they are in the args.
def attr_public(*args)
if instance_variable_defined?('@private_attributes') && !@private_attributes.empty?
@private_attributes.delete_if { |n| args.include?(n.to_sym) }
else
attr_private(*attribute_names.reject { |n| args.include?(n.to_sym) })
end
end
end
# Run the to_xml options through a filter
def to_xml(options={})
super(secure_private_options(options))
end
# Run the serializable_hash options through a filter
def serializable_hash(options={})
super(secure_private_options(options))
end
protected
# Filter the options to make sure private attributes aren't included
def secure_private_options(options={})
(options[:except] ||= []).push(*self.class.private_attributes)
options[:only].delete_if { |n| self.class.is_private_attribute?(n) } if options.has_key?(:only)
options[:methods].delete_if { |n| self.class.is_private_attribute?(n) } if options.has_key?(:methods)
options
end
end
end
</code></pre>
<h3>Example of use in a third party library - RABL</h3>
<pre><code># Modify Rabl's builder to check if a method is private before exposing it
module Rabl
class Builder
protected
# Don't output the
def attribute(name, options={})
unless @_object.class.respond_to?(:is_private_attribute?) && @_object.class.is_private_attribute?(name)
@_result[options[:as] || name] = data_object_attribute(name) if @_object && @_object.respond_to?(name)
end
end
end
end
</code></pre>
<h2>Example of general use on a model instance</h2>
<pre><code># An example of usage.
# Fields: category_id, name, description, supplier
#
# Let's assume we never want supplier to be exposed.
#
class Product < ActiveRecord::Base
attr_private :supplier
end
Product.first.to_json
#=> { "category_id": 1, "name": "Bucky Balls", "description": "Awesome Magnets" }
Product.is_private_attribute?(:supplier)
#=> true
Product.is_private_attribute?(:category_id)
#=> false
Product.private_attributes
#=> [ :supplier ]
# You can also use attr_public, which takes the attributes_names and makes all of them private except the items listed in the attr_public arguments
</code></pre>
<h2>Additional notes</h2>
<ul>
<li>You could support role based access control by turning the underlying instance variable into a hash keyed to the role instead of a single array.</li>
<li>The attributes could still be exposed by having them called directly, which allows for usage in cases where you actually WANT them exposed (like perhaps an admin panel).</li>
</ul>
<h2>Questions</h2>
<ol>
<li><p>As you see in the <code>secure_private_options</code> method, I check the passed in methods to make sure they aren't on the blacklist. This is fine for using attr_private to declare methods that shouldn't called, but I can't figure out how to set it so that <code>attr_public</code> can automatically include all getter attribute methods as well as just the attributes. For example, if I have a custom method called <code>full_name</code> that I want to protect, it would be nice if <code>attr_public</code> would automatically protect it.</p></li>
<li><p>Is there something in <code>ActiveRecord</code> or Rails that provides for this functionality already?</p></li>
<li><p>What use cases am I not thinking about?</p></li>
</ol>
<p>A gist of this code can be found <a href="https://gist.github.com/3806392" rel="nofollow">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T06:03:18.797",
"Id": "26138",
"Score": "0",
"body": "Some advice I've received so far: 1) Make it an include for ActiveModel instead of ActiveRecord::Base. 2) Follow the attr_accessible conventions for Blacklist / Whitelist rules. 3) Add support for roles."
}
] |
[
{
"body": "<p>With regard to (1): I suppose you could consider wrapping an entire model instance in an object that presents some methods itself (like a filtered <code>to_json</code>, or filtered <code>columns</code>), and forwards only allowed methods to the model on <code>method_missing</code>. Basically proxying (maybe even duck typing) the wrapped model minus the private attributes/methods.</p>\n\n<p>I.e. set <code>attr_public/private</code> on your model like now, and add a <code>filtered_for(role)</code> (or whatever) method, that uses the black/whitelist to construct a filtering proxy around the model itself. <code>Sieve</code> seems like good name for such a thing, but it's probably taken :)</p>\n\n<p>Admittedly, it's a heavy-handed approach, and I haven't tried it out in any way, but it's an idea.</p>\n\n<p>As for (2), I just don't know - I'm still pretty new to Rails. (So this entire answer might be wrong-headed. You've been warned.)<br>\nThe issue does remind me of <a href=\"https://github.com/rails/strong_parameters\" rel=\"nofollow\">the <code>strong_parameters</code> gem</a>, though - if only because I've just started using it. You're sort of doing the same, just on the response-side of things.</p>\n\n<p>Regardless of how you implement it, a solid test suite for the API would be a boon. Write some functional tests that fail spectacularly if responses include attributes they shouldn't. While this isn't itself perfect, it has the benefit of catching cases where a gung-ho programmer simply bypasses all the protection to output an otherwise privat attribute.</p>\n\n<p>A rambling answer, and perhaps entirely wrong, but if not then maybe you can use it for something.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T01:09:30.933",
"Id": "16093",
"ParentId": "16064",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T22:01:08.527",
"Id": "16064",
"Score": "3",
"Tags": [
"ruby",
"security",
"ruby-on-rails",
"api",
"active-record"
],
"Title": "Protecting certain model attributes from being exposed in an API"
}
|
16064
|
<p>Sometimes I need <code>toString()</code> to be quite verbose, normally I don't. It can't be nicely solved by using other methods as <code>toString()</code> is what gets shown in debugger (and also in the logs unless I call some method explicitly). As nobody should ever rely on its behavior, I wonder if the following is acceptable</p>
<pre><code>public static boolean volatile verboseToString;
public String toString() {
return toString(verboseToString);
}
public String toString(boolean verbose) {
if (verbose) {
return longDescription();
} else {
return shortDescription();
}
}
</code></pre>
<p>Is there any better solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T05:30:55.613",
"Id": "26235",
"Score": "0",
"body": "Just had another thought, are you concatenating using `+` or `StringBuilder`? It might make a difference if the verbosity is expensive and is constantly being created. But may not be needed as it could be optimized by the compiler."
}
] |
[
{
"body": "<p>Personally, I use <code>toDebugString()</code> to prevent misuse for others that may be using this class (or even myself down the line). It has clear intent/purpose (self documenting) without requiring extra thinking to read the javadoc.</p>\n\n<p>On related note, you may find this <a href=\"http://www.javapractices.com/topic/TopicAction.do;jsessionid=341DEC0F4A83C47D92FB7A44D2298BF3?Id=55\" rel=\"nofollow\">reference</a> (A collection of \"best\" java practices) on implementing <code>toString()</code> helpful as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T17:39:00.260",
"Id": "26156",
"Score": "0",
"body": "But is there any way to make my debugger use `toDebugString()`? I don't think so, and I don't want to repeat the explicit method call in each logging/debugging statement. I'm afraid I didn't formulate my question clearly enough..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T18:12:52.557",
"Id": "26157",
"Score": "1",
"body": "Typically when you're debugging, you'll be using an IDE to step through your code -- debugging vis-a-vis print statements is not good practice since it could be an improper use of the API and thus hidden from your `toString()` method. But, you could also decorate it with an interface with something like `IsDebuggable` and use an intermediary (processor) to do handle it. Then you would implement `IsDebuggable` to all classes that you'd want to see as verbose (enforcing a contract) and then use it as such: `processClass(IsDebuggable someClass) { someClass.toDebugString(); }` )"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T10:19:35.937",
"Id": "16073",
"ParentId": "16071",
"Score": "3"
}
},
{
"body": "<p>It reminds me <a href=\"http://xunitpatterns.com/Test%20Logic%20in%20Production.html\" rel=\"nofollow\">Test Logic in Production</a> chapter from the <em>XUnit Test Patterns</em> book.</p>\n\n<p><em>Effective Java, 2nd Edition, Item 10: Always override toString</em> suggest that,</p>\n\n<blockquote>\n <p>When practical, the <code>toString</code> method should return all of the interesting\n information contained in the object [...]</p>\n</blockquote>\n\n<p>So, I'd use the <code>toString</code> method for only logging and debugging (whether it's verbose or not) and use another methods where specific formats are required.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T17:35:06.503",
"Id": "26155",
"Score": "0",
"body": "Sure, the problem is that \"all of the interesting information\" is actually very long, and sometimes I need \"the most important information\" only, depending on what I'm currently doing. As an example imagine \"class Person\". When working with a single person, you may want to see everything; when looking at a list of tens of them, the name alone is nearly too much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T17:23:52.250",
"Id": "16079",
"ParentId": "16071",
"Score": "2"
}
},
{
"body": "<p>You could try to use Logger level to control verbose mode.</p>\n\n<pre><code>public String toString() {\n return toString(logger.isDebugEnabled());\n}\n\npublic String toString(boolean verbose) {\n if (verbose) {\n return longDescription();\n } else {\n return shortDescription();\n }\n}\n</code></pre>\n\n<p>Advantage of this approach is that it's easier to control toString() verbosity level - simply by config file for you logging framework, JMX extension, ...</p>\n\n<p>This could also give you more flexibility - based on log level (INFO, DEBUG, TRACE), your could control how much information you put into toString().</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T21:00:58.170",
"Id": "51106",
"Score": "0",
"body": "This makes sense, although it couples two thing together: the decision if there's an output at all and the the decision how detailed it is. So you can end up with either a long output or none at all."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T19:17:20.287",
"Id": "16117",
"ParentId": "16071",
"Score": "6"
}
},
{
"body": "<p>I decided that using such a global variable is fine. As nobody should ever rely on the behavior of <code>toString()</code>, it can't be a problem. Instead of the global public variable I'll use a method so it looks a bit cleaner.</p>\n\n<p>It's ugly, but it does what I need and there's no nice way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T21:05:05.737",
"Id": "31999",
"ParentId": "16071",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "31999",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T09:23:38.150",
"Id": "16071",
"Score": "5",
"Tags": [
"java",
"static"
],
"Title": "Configuring toString via a public static variable"
}
|
16071
|
<p><img src="https://i.stack.imgur.com/qFMEj.png" alt="enter image description here"></p>
<p>The requirement is to be able to cache method invocations made on a boundary layer (Services layer). I'm using Unity to inject the concrete implementation of the Service layer classes. The intercepting <code>CacheCallHandler</code> caches all the responses across this layer.</p>
<p>The twist is that this is a multi-threaded environment with multiple clients invoking the same boundary layer in the context of a single request. If a service layer call is already in "flight", it should wait for the original invokers return and use that.</p>
<p>I've used Reactive extensions to implement this.</p>
<pre><code>/// <summary>
/// Intercepts the calls and tries to retrieve from the cache
/// </summary>
class CacheCallHandler : ICallHandler
{
[Dependency]
public ICache RequestCache { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
IMethodReturn mesg = null;
string cacheKey = CacheKeyGenerator.GetCacheKey(input);
//create the task to retrieve the data
var task = new Task<IMethodReturn>(() =>
{
return getNext()(input, getNext);
});
//make it observable
var observableItem = task.ToObservable();
//try to add it to the cache
//we need to do this in the order of Add and then try to get, otherwise multiple thread might enter the same area
if (RequestCache.TryAdd(cacheKey, observableItem))
{
//if the add succeeed, it means that we are responsible to starting this task
task.Start();
}
else
{
if ( RequestCache.TryGetValue(cacheKey, out observableItem) )
{
//do nothing, the observable item is already updated with the requried reference
}
else
{
throw new CacheHandlerException("Could not add to cache AND could not retrieve from cache either. Something's wrong", input);
}
}
//observe the return
if ( observableItem != null )
mesg = observableItem.FirstOrDefault();
if (mesg == null)
throw new CacheHandlerException("Not return value found. this should not happen", input);
return mesg;
}
/// <summary>
/// Should always be the first to execute on the boundary
/// </summary>
public int Order
{
get { return 1; }
set { ; }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Personally i believe that there is no need for the reactive framework in this scenario.\nTo handle the multithreaded nature of your problem i would first make sure that your RequestCache (Icache) uses the ConcurrentDictionary> and exposrts the <a href=\"http://msdn.microsoft.com/en-us/library/ee378677.aspx\" rel=\"nofollow\">method GetOrAdd</a></p>\n\n<p>With this your code will look like this:</p>\n\n<pre><code>/// <summary>\n/// Intercepts the calls and tries to retrieve from the cache\n/// </summary>\nclass CacheCallHandler : ICallHandler\n{\n\n [Dependency]\n public ICache RequestCache { get; set; }\n\n public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)\n {\n return InvokeAsync.Result;\n }\n\n public Task<IMethodReturn> InvokeAsync(IMethodInvocation input, GetNextHandlerDelegate getNext)\n {\n IMethodReturn mesg = null;\n\n string cacheKey = CacheKeyGenerator.GetCacheKey(input);\n\n //create the task to retrieve the data\n var task = RequestCache.GetOrAdd(\n cacheKey,\n key => new Task.Factory.StartNew(() => getNext()(input, getNext))\n );\n\n return task; \n }\n\n\n /// <summary>\n /// Should always be the first to execute on the boundary\n /// </summary>\n public int Order\n {\n get { return 1; }\n set { ; }\n }\n}\n</code></pre>\n\n<p>The asynchronous version offers the option of to blocking the calling thread when invoking it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-14T18:43:18.013",
"Id": "19622",
"ParentId": "16075",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T12:28:55.847",
"Id": "16075",
"Score": "11",
"Tags": [
"c#",
"optimization",
"cache",
"system.reactive"
],
"Title": "Improve Parallel Cache with Reactive Extensions & Unity Interception"
}
|
16075
|
<p>I started learning java a few days ago. I prefer C++ but since I'll need java this college semester I decided to learn a few things to ease myself in. Anyway in C++ I always used a foolproof input method for taking user input of primitive numeric types. I picked that method up from <a href="http://latedev.wordpress.com/2011/09/13/simple-input-bullet-proofing-in-c/" rel="nofollow">here</a>.</p>
<p>So I decided to somewhat transfer that to Java with perhaps an added functionality or two. However it turned out to be quite a bit messier than what I thought.</p>
<p>This is my current code:</p>
<p>FoolproofInput.java</p>
<pre><code>package mrplow.input;
import java.util.Scanner;
/*
----------------------------------------------------------------------
@by MrPlow
Class designed for bullet-proofing user input for Integer, Float and
Double primitive types
They check if the next item in the input stream is valid:
- if it is, the read value is returned
- if it is not, the prompt loops until the correct item is input
All of the methods are used in the same way:
ex.
myInt = FoolproofInput.readInt("Give me an int");
There are also read<T>Rng methods
They are used for range input and contain two additional parameters
which are the lower range bound "lowest" and upper range bound "highest"
ex.
myInt = FoolproofInput.readIntRng("Give me an int between 10 - 20", 11,19);
------------------------------------------------------------------------
*/
public class FoolproofInput
{
static private Scanner scan = new Scanner(System.in);
static private boolean isValid = false;
static private int intValue = 0;
static private float floatValue = 0;
static private double doubleValue = 0;
static public int readInt(String prompt)
{
intValue = 0;
do
{
System.out.print(prompt);
if(scan.hasNextInt())
{
intValue = scan.nextInt();
isValid = true;
scan.nextLine();
}
else
{
System.out.println("Invalid input! Requested an Int, recieved something else.");
isValid = false;
scan.nextLine();
}
}while(!isValid );
return intValue;
}
static public float readFloat(String prompt)
{
floatValue = 0;
do
{
System.out.print(prompt);
if(scan.hasNextFloat())
{
floatValue = scan.nextFloat();
isValid = true;
scan.nextLine();
}
else
{
System.out.println("Invalid input! Requested a Float, recieved something else.");
isValid = false;
scan.nextLine();
}
}while(!isValid );
return floatValue;
}
static public double readDouble(String prompt)
{
doubleValue = 0;
do
{
System.out.print(prompt);
if(scan.hasNextDouble())
{
doubleValue = scan.nextDouble();
isValid = true;
scan.nextLine();
}
else
{
System.out.println("Invalid input! Requested a Double, recieved something else.");
isValid = false;
scan.nextLine();
}
}while(!isValid );
return doubleValue;
}
static public int readIntRng(String prompt, int lowest, int highest)
{
int intValue = 0;
do
{
System.out.print(prompt);
if(!scan.hasNextInt())
{
System.out.println("Invalid input! Requested an Int, recieved something else.");
isValid = false;
scan.nextLine();
}
else
{
intValue = scan.nextInt();
if( intValue >= lowest && intValue <= highest )
{
isValid = true;
scan.nextLine();
}
else
{
System.out.println( "Invalid input! The input number is not in range:"
+ "(" + lowest + "-" + highest + ")." );
intValue = 0;
}
}
}while(!isValid );
return intValue;
}
static public float readFloatRng( String prompt, float lowest, float highest )
{
float floatValue = 0;
do
{
System.out.print(prompt);
if(!scan.hasNextFloat())
{
System.out.println("Invalid input! Requested a Float, recieved something else.");
isValid = false;
scan.nextLine();
}
else
{
floatValue = scan.nextFloat();
if(floatValue >= lowest && floatValue <= highest)
{
isValid = true;
scan.nextLine();
}
else
{
System.out.println( "Invalid input! The input number is not in range:"
+ "(" + lowest + "-" + highest + ")." );
floatValue = 0;
}
}
}while(!isValid );
return floatValue;
}
static public double readDoubleRng( String prompt, double lowest, double highest )
{
double doubleValue = 0;
do
{
System.out.print(prompt);
if(!scan.hasNextDouble())
{
System.out.println("Invalid input! Requested a Double, recieved something else.");
isValid = false;
scan.nextLine();
}
else
{
doubleValue = scan.nextDouble();
if(doubleValue >= lowest && doubleValue <= highest)
{
isValid = true;
scan.nextLine();
}
else
{
System.out.println( "Invalid input! The input number is not in range:"
+ "(" + lowest + "-" + highest + ")." );
doubleValue = 0;
}
}
}while(!isValid );
return doubleValue;
}
}
</code></pre>
<p>Basically this has too much repeat code and the only differences are the (hasNext() methods). </p>
<p>So is there any way this code can be shortened? And are there any possible bugs that I've missed?</p>
<p>P.S: Also why doesn't this place have a "user-input" or even "input" tag?</p>
|
[] |
[
{
"body": "<p>Among other things, you're relying on 'global' (class-level) variables <em>way</em> too much. This will cause you problems later, especially if you want to do any sort of multi-threaded programming. You also haven't separated your concerns as much as you probably should - actually doing so may help make it easier to test things.</p>\n\n<p>Java makes heavy use of classes and interfaces, which is what you really want here (potentially including <em>anonymous</em> classes). Here's what you'll need:</p>\n\n<p>1) An interface for your input: </p>\n\n<pre><code>package myplow.input;\n\nimport java.util.Scanner;\n\npublic interface InputGrabber<T> {\n\n boolean hasNextInput(Scanner scanner);\n\n T getNextInput(Scanner scanner);\n\n String getExpectedInputFormat();\n\n}\n</code></pre>\n\n<p>2) Something to control the input cycle:</p>\n\n<pre><code>package myplow.input;\n\nimport java.io.InputStream;\nimport java.io.PrintStream;\nimport java.util.Scanner;\n\npublic class PromptCycle {\n\n private final Scanner scanner;\n private final PrintStream output;\n\n public PromptCycle(InputStream in, PrintStream out) {\n scanner = new Scanner(in);\n output = out;\n }\n\n public <T> T getInput(String prompt, InputGrabber<T> grabber) {\n do {\n output.println(prompt);\n } while (needsProperInput(grabber));\n T value = grabber.getNextInput(scanner);\n return value;\n }\n\n private <T> boolean needsProperInput(InputGrabber<T> grabber) {\n if (grabber.hasNextInput(scanner)) {\n return false;\n }\n output.println(grabber.getExpectedInputFormat());\n scanner.nextLine();\n return true;\n }\n\n}\n</code></pre>\n\n<p>3) Implementations of the interface to allow validation/retrieval:</p>\n\n<pre><code>package myplow.input;\n\nimport java.util.Scanner;\n\npublic class IntegerInputGrabber implements InputGrabber<Integer> {\n\n public boolean hasNextInput(Scanner scanner) {\n return scanner.hasNextInt();\n }\n\n public Integer getNextInput(Scanner scanner) {\n return scanner.nextInt();\n }\n\n public String getExpectedInputFormat() {\n return \"Invalid input! Requested an Int, recieved something else.\";\n }\n\n}\n</code></pre>\n\n<p>4) You can then 'wire' up an application like this:</p>\n\n<pre><code>package myplow.input;\n\npublic class Application {\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n System.out.println(\"Application started\");\n PromptCycle cycle = new PromptCycle(System.in, System.out);\n Integer value = cycle.getInput(\"Needs an int\", new IntegerInputGrabber());\n System.out.println(\"Value retrieved: \" + value);\n System.out.println(\"Application ended\");\n }\n\n}\n</code></pre>\n\n<p>This has the benefits of not caring <em>where</em> the actual 'scanned' input comes from (ie it's trivial for me to use something other than standard input/output). Additionally, I can add <em>whatever</em> sort of input grabber I want - including non-primitives - simply by passing in a different implementation. The <code>getInput()</code> method is genericized, so the return type is based on whatever gets passed in.</p>\n\n<p>All code compiles and runs as expected. However, there should probably be better checks than what I have so far. The rest of the input grabber implementations I'm leaving as an exercise for the reader.</p>\n\n<hr />\n\n<p>I'm also including one for a range, because it's somewhat non-intuitive, given the way I have the cycles set up:</p>\n\n<pre><code>package myplow.input;\n\nimport java.util.Scanner;\n\npublic class IntegerRangeInputGrabber implements InputGrabber<Integer> {\n\n private final int minimum;\n private final int maximum;\n\n public IntegerRangeInputGrabber(int minimum, int maximum) {\n this.maximum = Math.max(maximum, minimum);\n this.minimum = Math.min(maximum, minimum);\n }\n\n public boolean hasNextInput(Scanner scanner) {\n if (!scanner.hasNextInt()) {\n return false;\n }\n int value = scanner.nextInt();\n return (value >= minimum && value < maximum);\n }\n\n public Integer getNextInput(Scanner scanner) {\n return Integer.valueOf(scanner.match().group());\n }\n\n public String getExpectedInputFormat() {\n return \"Invalid input! The input number is not in range:\" + \n \"(\" + minimum + \"-\" + maximum + \").\";\n }\n\n}\n</code></pre>\n\n<p>This can of course be wired up similarly to the other grabbers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T12:01:08.670",
"Id": "26178",
"Score": "0",
"body": "This will certainly help me in learning more about Java, thanks for taking your time to help me.\n\nOne question though.\n\nHow is `private <T> boolean needsProperInput(InputGrabber<T> grabber)` valid? Aren't you declaring multiple return types in one method? If `T` is Int wouldn't it be `int boolean` or does `boolean` work differently in Java than in C++?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T15:38:55.297",
"Id": "26205",
"Score": "0",
"body": "The `<T>` before the return-type definition is a type-parameter. That's what's allowing me to use the generic form of `InputGrabber` in the method parameter. It's not considered a 'multiple return type' (it's not returned, and the method could actually have a `void` return type), it's basically a compile-time-check parameter. Have a look at [Java's generics](http://docs.oracle.com/javase/tutorial/java/generics/) for more information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T20:51:52.457",
"Id": "16087",
"ParentId": "16076",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "16087",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T15:13:50.583",
"Id": "16076",
"Score": "2",
"Tags": [
"java"
],
"Title": "Java foolproof input class"
}
|
16076
|
<p>Ok so this works as is, and is not actually slow at all (from what I can see) - However I don't like the taste of nested while loops and was wondering if anyone could give some insight on a different approach? Or how to improve mine to take away the <code>while() { while() {}}</code></p>
<p>Here it is: </p>
<pre><code>/* takes a string and a maxWidth and splits the text into lines */
// ctx is available in the parent scope.
function fragmentText(text, maxWidth) {
var words = text.split(' '),
lines = [],
line = "";
if (ctx.measureText(text).width < maxWidth) {
return [text];
}
while (words.length > 0) {
while (ctx.measureText(words[0]).width >= maxWidth) {
var tmp = words[0];
words[0] = tmp.slice(0, -1);
if (words.length > 1) {
words[1] = tmp.slice(-1) + words[1];
} else {
words.push(tmp.slice(-1));
}
}
if (ctx.measureText(line + words[0]).width < maxWidth) {
line += words.shift() + " ";
} else {
lines.push(line);
line = "";
}
if (words.length === 0) {
lines.push(line);
}
}
return lines;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T22:44:36.983",
"Id": "26163",
"Score": "0",
"body": "What's the difference between `str.length` and `ctx.measureText(str)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T22:54:50.543",
"Id": "26164",
"Score": "2",
"body": "@LarryBattle `.length` gives you the number of characters in the string; `measureText` gives you the width in pixels of the string if it were to be drawn with the selected font. So: Big difference :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T22:57:58.977",
"Id": "26165",
"Score": "0",
"body": "@Flambino lol. I found that out before you left your comment."
}
] |
[
{
"body": "<p>The first thing I notice is an excessive use of measureText, which I am inclined to assume is a relatively expensive operation. At a minimum, every word is measured twice - once to verify it fits within the maxWidth constraint, and once again to verify it fits on the current line. Of course, as the line grows, all previous words are measured again by virtue of the current line being measured on each loop.</p>\n\n<p>Second, when a word doesn't fit on the current line, it must be processed again (it isn't shifted off the array in this condition).</p>\n\n<p>With this kind of problem, I prefer to separate tasks - that is, measure first (no need to measure twice), build second. I would prefer to loop through the word list a couple of times to minimize the calls to measureText. I have rewritten the function with this in mind. The function is much longer now, but I feel it is easier to follow and to maintain when edge cases arise.</p>\n\n<pre><code>var emmeasure = ctx.measureText(\"M\").width;\nvar spacemeasure = ctx.measureText(\" \").width;\n\n/* takes a string and a maxWidth and splits the text into lines */ \n // ctx is available in the parent scope. \nfunction fragmentText(text, maxWidth) { \n if (maxWidth < emmeasure) // To prevent weird looping anamolies farther on.\n throw \"Can't fragment less than one character.\";\n\n if (ctx.measureText(text).width < maxWidth) { \n return [text]; \n } \n\n var words = text.split(' '), \n metawords = [],\n lines = [];\n\n // measure first.\n for (var w in words) {\n var word = words[w];\n var measure = ctx.measureText(word).width;\n\n // Edge case - If the current word is too long for one line, break it into maximized pieces.\n if (measure > maxWidth) {\n // TODO - a divide and conquer method might be nicer.\n var edgewords = (function(word, maxWidth) {\n var wlen = word.length;\n if (wlen == 0) return [];\n if (wlen == 1) return [word];\n\n var awords = [], cword = \"\", cmeasure = 0, letters = [];\n\n // Measure each letter.\n for (var l = 0; l < wlen; l++)\n letters.push({\"letter\":word[l], \"measure\":ctx.measureText(word[l]).width});\n\n // Assemble the letters into words of maximized length.\n for (var ml in letters) {\n var metaletter = letters[ml];\n\n if (cmeasure + metaletter.measure > maxWidth) {\n awords.push({ \"word\":cword, \"len\":cword.length, \"measure\":cmeasure });\n cword = \"\";\n cmeasure = 0;\n }\n\n cword += metaletter.letter;\n cmeasure += metaletter.measure;\n }\n // there will always be one more word to push.\n awords.push({ \"word\":cword, \"len\":cword.length, \"measure\":cmeasure });\n return awords;\n })(word, maxWidth);\n\n // could use metawords = metawords.concat(edgwords)\n for (var ew in edgewords)\n metawords.push(edgewords[ew]);\n }\n else {\n metawords.push({ \"word\":word, \"len\":word.length, \"measure\":measure });\n }\n }\n\n // build array of lines second.\n var cline = \"\";\n var cmeasure = 0;\n for (var mw in metawords) {\n var metaword = metawords[mw];\n\n // If current word doesn't fit on current line, push the current line and start a new one.\n // Unless (edge-case): this is a new line and the current word is one character.\n if ((cmeasure + metaword.measure > maxWidth) && cmeasure > 0 && metaword.len > 1) {\n lines.push(cline)\n cline = \"\";\n cmeasure = 0;\n }\n\n cline += metaword.word;\n cmeasure += metaword.measure;\n\n // If there's room, append a space, else push the current line and start a new one.\n if (cmeasure + spacemeasure < maxWidth) {\n cline += \" \";\n cmeasure += spacemeasure;\n } else {\n lines.push(cline)\n cline = \"\";\n cmeasure = 0;\n }\n }\n if (cmeasure > 0)\n lines.push(cline);\n\n return lines;\n} \n</code></pre>\n\n<p>Performance:\nI executed this test on my machine in IE9. Note the assumption of a table called \"splittertest\" with the columns: Words, MaxWidth, New (ms), Old (ms). The original function is called fragmentText_old in this test.</p>\n\n<pre><code>var tests = [{\"twc\":50, \"tmw\":500},\n {\"twc\":50, \"tmw\":50},\n {\"twc\":500, \"tmw\":500},\n {\"twc\":500, \"tmw\":50},\n {\"twc\":5000, \"tmw\":500},\n {\"twc\":5000, \"tmw\":50},\n {\"twc\":10000, \"tmw\":500},\n {\"twc\":10000, \"tmw\":50}];\nvar results = [];\n\nfor (var tt in tests) {\n var test = tests[tt];\n\n var testline = (function(twc) {\n var testwords = [];\n for (var x = 0; x < twc; x++) {\n var len = 3 + Math.floor(Math.random()*11);\n var letters = [];\n for (var y = 0; y < len; y++)\n letters.push(String.fromCharCode(\"a\".charCodeAt() + y));\n testwords.push(letters.join(\"\"));\n }\n return testwords; \n })(test.twc).join(\" \");\n\n var st, dur1, dur2;\n\n st = new Date().getTime();\n var ss = fragmentText(testline, test.tmw);\n dur1 = new Date().getTime() - st;\n\n st = new Date().getTime();\n var sso = fragmentText_old(testline, test.tmw);\n dur2 = new Date().getTime() - st;\n\n results.push(\"<tr><td>\" + test.twc + \"</td><td>\" + test.tmw + \"</td><td>\" + dur1 + \"</td><td>\" + dur2 + \"</td></tr>\");\n}\n\n$(\"#splittertest\").append(results.join(\"\"));\n</code></pre>\n\n<p>The results show mine about twice as fast when there is no chance a word will exceed the maxWidth, and exponentially faster when words frequently exceed the maxWidth.</p>\n\n<pre><code>Words MaxWidth New (ms) Old (ms)\n50 500 1 1\n50 50 3 5\n500 500 3 7\n500 50 16 331\n5000 500 31 76\n5000 50 195 167820 (2.8 mins)\n10000 500 60 155\n10000 50 337 1121565 (18.7 mins)\n</code></pre>\n\n<p>It's worth noting that the results are significantly less on subsequent runs in the same browser because of some caching done - probably within the canvas context.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T14:24:38.890",
"Id": "26200",
"Score": "1",
"body": "My version behaves slighly differently in that it allows a line to reach maxWidth, where-as yours excludes maxWidth. Indeed, mine is a bit inconsistent where the space is concerned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T18:09:22.373",
"Id": "26212",
"Score": "0",
"body": "Not sure I would rely on a space character always having the same width. With proportional typefaces and proper kerning, I imagine spaces can vary in width. I'm not saying that that's the case, but I wouldn't be surprised."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T19:33:29.930",
"Id": "26221",
"Score": "0",
"body": "@Flambino - Indeed. Kerning and other font effects can mess up this entire algorithm, both mine and the original. To wit, the sum measure of words and spaces may not equal the meaure of the total string - likewise the sum measure of letters may not equal the total measure of the word. In that regard, the original is slightly better, since it is always measuring the proposed string in full. However, its performance drops faster than mine - I've added some performance metrics to my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T20:07:28.393",
"Id": "26225",
"Score": "0",
"body": "True, it's performance vs precision. However, my worries were unfounded: [jsfiddle test](http://jsfiddle.net/eEcng/). I tried a bunch of fonts, but the full-text width and the summed up letter width seems to be the same in all cases. Interestingly, Lucida Grande (which is highly optimized on OS X) was the only font I found that resulted in non-integer widths - but even then they were identical. I guess canvas just doesn't do any kerning (sadly)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T20:22:15.527",
"Id": "26226",
"Score": "0",
"body": "I think yours performs more than adequately as long as the case when a word exceeds the maxWidth is rare (which I imagine it generally would be). Even at 10K words with a maxWidth of 500, my test showed yours completing in 155ms. Now I have to chew over this some more. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T23:19:51.593",
"Id": "26232",
"Score": "0",
"body": "well for its given application http://rlemon.github.com/lememe/ and future versions of said project the lines will more often need to wrap :/ I have been reading over the script and do like it though. I will be trying to implement some of its insights into my own. :) thankyou."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T14:07:50.687",
"Id": "16112",
"ParentId": "16081",
"Score": "3"
}
},
{
"body": "<p>Here's a different tack to take, namely recursion. It's CoffeeScript (sorry - I find myself thinking better when I don't have to deal with curly braces).</p>\n\n<p>It's <strong>not</strong> perfect, and mostly here to hopefully give someone an idea for something better.</p>\n\n<pre><code># Called it \"wordWrap\" since that's the usual name for such a function\nwordWrap = (text, maxWidth) ->\n # Internal wrapping function\n wrap = (text, delim, hyphen = \"\") ->\n delimWidth = ctx.measureText delim\n\n parts = text.split delim\n chunks = []\n\n while parts.length\n line = \"\"\n i = 0\n\n while i < parts.length\n # Check if the next word/char will overflow\n tmp = line + parts[i] + hyphen + delim\n if ctx.measureText(tmp) > maxWidth + delimWidth\n # It overflowed!\n if i is 0\n # If this is the first checked for this line,\n # recursively wrap it letter-for-letter,\n # adding a hyphen where it breaks\n word = parts.shift()\n wrapped = wrap word, \"\", \"-\"\n # The first part of the hyphen-wrapped word\n # becomes our line, while the rest become the\n # the next part(s)\n line = wrapped[0]\n parts = wrapped.slice(1).concat parts\n\n # Add the hyphen string to the broken line\n line += hyphen\n break\n else\n # No overflow; add the part and move on\n line += parts[i] + delim\n i++\n\n # Loop broke, add the line, and remove\n # the parts we've processed\n chunks.push line.trim()\n parts = parts.slice i\n\n # Return chunks\n chunks\n\n # Call wrap with a space as the delimiter\n # and return the result\n wrap text, \" \"\n</code></pre>\n\n<p>Basically, it'll break words into lines, and - if a word is too long to fit on one line - it'll break that word with a hyphen.</p>\n\n<p><em>Limitations:</em> It will break a word with no regard for hyphenation rules, and might break a word to make room for the hyphen, even the word would fit without the hyphen. I.e. in the worst case the string <code>\"longword!\"</code> might break into <code>\"long-\", \"word-\", \"!\"</code></p>\n\n<p>So again, this is far from perfect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T21:18:55.960",
"Id": "16125",
"ParentId": "16081",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T18:33:13.580",
"Id": "16081",
"Score": "7",
"Tags": [
"javascript",
"canvas"
],
"Title": "Splitting text into lines from a max width value for CANVAS"
}
|
16081
|
<p>I'm interested in discussing string literals in Objective-C and would like to know 1. if there's a preferred paradigm / style and 2. what (if any) the performance implications might be.</p>
<p>There are parts of the Cocoa / CocoaTouch frameworks that use strings as identifiers. Some examples in Cocoa / CocoaTouch...</p>
<pre><code>-[NSNotificationCenter addObserver:selector:name:object:]
-[UITableView dequeueReusableCellWithIdentifier:]
-[UIViewController performSegueWithIdentifier:sender:]
</code></pre>
<p>I find myself most often declaring a global variable within the class like so...</p>
<pre><code>NSString * const kMySegueIdentifier = @"Awesome Segueueueueue";
</code></pre>
<p>For segue identifiers, I will often times expose the variable in the header file <code>extern NSString * const kMySegueIdentifier;</code> so that other modules can reuse it.</p>
<p>The same behaviors can be accomplished with preprocessor macros: <code>#define kMySegueIdentifier @"Awesome Segueueueueue"</code>. I believe this would also prevent the app from consuming memory to hold these globals. I cringe a little at this syntax however because it exposes the "implementation details" of my string literal constants.</p>
<p>Both of these lines accomplish an end goal of abstracting the string into being easy to remember, type correctly, and will generate compile warnings / errors, is one actually better then the other? What are the situations that would arise where one would be preferred over the other?</p>
|
[] |
[
{
"body": "<p>Actually, they are completely equal (obviously sans the <code>extern</code> keyword on the constant define). When literal strings are declared <code>@\"\"</code>, the compiler expands them out to a compile-time constant expression, which looks familiar to us all: <code>(static) NSString *const;</code> -albeit with a lot more compiler magic thrown in.</p>\n\n<p>Nearly the same process occurs with macros, but with one extra step: replacement. Macros are placeholders, which the compiler replaces with the value you <code>#define</code> at compile-time, which is why CLANG can show you errors and warnings.</p>\n\n<p>Where the difference lies is how much work the compiler has to do to replace your abstractions, not in the \"memory overhead\" they will incur (which means there is absolutely no speed or performance to squeeze out). Besides, NSString* is a brilliant class cluster that's been optimized over the years, especially with literal constants, where a sort of caching occurs in the binary itself. That way, literals used over and over again don't get reallocated over and over again. Though, to make one thing perfectly clear: <strong><em>#define'd literals do NOT reduce memory overhead</em></strong>!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-17T19:44:32.767",
"Id": "17651",
"ParentId": "16082",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "17651",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T19:09:18.337",
"Id": "16082",
"Score": "3",
"Tags": [
"objective-c"
],
"Title": "#define or NSString * const - Benefits and drawbacks of string literal constant syntax?"
}
|
16082
|
<p>I am wondering if the self invoking function as displayed below, mainly the part of using the same function twice <code>('foo')('bar')</code>, would ever be seen as a good practice?</p>
<p>And more important, is there a good reason to use this? Personally in this particular example I would rather go for multiple attributes and loop those.</p>
<p>The HTML is just filler.</p>
<pre><code><!DOCTYPE html>
<meta charset='utf-8'>
<title>Foo Bar Foobar</title>
<p id='foo'>Foo</p>
<p id='bar'>Bar</p>
<p>Foobar</p>
<script>
(function foobar(id) {
var element = document.getElementById(id);
element.style.color = 'red';
element.style.textIndent = '10px';
// Return self
return foobar;
})('foo')('bar');
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T00:24:38.227",
"Id": "26330",
"Score": "1",
"body": "Note that in IE (up to and including version 8 I think) named function expresssions became global variables regardless of the scope in which they were created."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T12:36:25.413",
"Id": "26358",
"Score": "0",
"body": "Confirmed that foobar in my code is global in IE8. But scope does seem to matter. Writing another function inside foobar will in no way of programming it become global. (tested with IE8 mode in IE9)"
}
] |
[
{
"body": "<p>Wow. Basically you wrote <code>Code A</code> but in a cool functional programming style.</p>\n\n<p>Code A:</p>\n\n<pre><code>(function(){\n function foobar(id) {\n var element = document.getElementById(id);\n element.style.color = 'red';\n element.style.textIndent = '10px';\n }\n for(var i = 0, len = arguments.length; i < len; i++){\n foobar(arguments[i]);\n }\n}('foo', 'bar'));\n</code></pre>\n\n<p>Self invoking functions are good for three situations.</p>\n\n<ol>\n<li>To perform some startup functions onload. (Most likely your case)</li>\n<li>To save results from a expensive operation into a loop up table.</li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>var primeTable = (function(){\n var primeObject = {}\n // calculates and stores primes from 100 to 1000 in primeObject\n return primeObject;\n})(); \n</code></pre>\n\n<p>3. To create private variables, which is normally called a <a href=\"http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth\" rel=\"nofollow\">Module Design Pattern</a>.</p>\n\n<p>Example:</p>\n\n<pre><code>var box = (function () {\n var key = Math.floor(Math.random() * 1e5).toString(16);\n return {\n open : function(val){\n return (val === key) ? \"Box has opened.\" : \"Wrong Key\";\n },\n setKey : function (oldKey, newKey) {\n if (oldKey === key) {\n key = newKey;\n }\n }\n }\n})();\n</code></pre>\n\n<p>Overall, if you want to follow <a href=\"http://www.youtube.com/watch?v=5P8qMJOg1co\" rel=\"nofollow\">KISS</a> philosophy then I think you should wrap everything in a closure and call the function traditionally. </p>\n\n<pre><code>(function(){\n function foobar(id) {\n var element = document.getElementById(id);\n element.style.color = 'red';\n element.style.textIndent = '10px';\n }\n foobar('foo'); \n foobar('bar'); \n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T06:33:11.243",
"Id": "26171",
"Score": "0",
"body": "Thank you for this very extensive explanation. Seems like we both think this is just another way of writing the same, but worse practice than some of the best practice alternatives. Nice to see how versatile programming languages can be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T00:26:36.663",
"Id": "26331",
"Score": "0",
"body": "+1 Good answer. I think the last example is best as it's very clear what the code is doing, so good for maintenance and easy for compilers to optimise if they can."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T03:34:32.147",
"Id": "16096",
"ParentId": "16084",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "16096",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T20:12:18.333",
"Id": "16084",
"Score": "7",
"Tags": [
"javascript"
],
"Title": "Any use for this kind of self invoking function?"
}
|
16084
|
<p>I have an object, <code>WorkflowGridBuilder</code>, which is responsible for building a <code>jqGrid</code> object and decorating it appropriately based on the type of grid being built.</p>
<p>Here is my builder:</p>
<pre><code>var WorkflowGridBuilder;
$(WorkflowGridBuilder = function () {
'use strict';
function buildGrid(data) {
var grid = $('#' + data.gridElementID);
var gridPager = $('#' + data.gridPagerElementID);
grid.jqGrid(
$.extend({
datatype: 'local',
gridview: true,
height: 'auto',
pager: gridPager,
viewrecords: true,
multiselect: true,
minHeight: 350,
caption: data.defaultCaption,
shrinkToFit: false,
loadError: function (error) {
console.error(error);
},
ondblClickRow: function (rowid) {
$(this).trigger('gridOnDblClickRow', $(this).getRowData(rowid));
}
}, data)
);
grid.getSelectedRows = function () {
var selectedRows = [];
$.each(grid.getGridParam('selarrrow'), function () {
selectedRows.push(grid.getRowData(this));
});
return selectedRows;
};
return grid;
}
return {
buildOrdersGrid: function () {
var ordersGrid = buildGrid({
gridElementID: 'OrdersGrid',
gridPagerElementID: 'OrdersGridPager',
colNames: ['Order ID', 'Project Subcode', 'Incident Number', 'Cost Center', 'Name', 'Customer'],
colModel: [
{ name: 'ID', hidden: true },
{ name: 'ProjectSubcode' },
{ name: 'IncidentNumber' },
{ name: 'CostCenter' },
{ name: 'Name' },
{ name: 'Customer' }
],
defaultCaption: 'Orders: no filter applied'
});
return ordersGrid;
},
buildTaskGrid: function () {
var tasksGrid = buildGrid({
gridElementID: 'TasksGrid',
gridPagerElementID: 'TasksGridPager',
colNames: ['Order', 'Task ID', 'Task #', 'Type', 'Status', 'Assignee', 'Current Location', 'Dest Location', 'Change No', 'Net Patched', 'SAN Patched'],
colModel: [
{ name: 'Order' },
{ name: 'ID', hidden: true },
{ name: 'TaskNo' },
{ name: 'Type' },
{ name: 'Status' },
{ name: 'Assignee' },
{ name: 'CurrentLocation' },
{ name: 'DestLocation' },
{ name: 'ChangeNo' },
{ name: 'NetPatched' },
{ name: 'SANPatched' }
],
defaultCaption: 'Tasks: no filter applied',
//Decorate with task-specific properties.
grouping: true,
groupingView: {
groupField: ['Order'],
groupColumnShow: [false]
}
});
return tasksGrid;
}
};
} ());
</code></pre>
<p>Each of the built objects are stored in their own, respective object. I noticed that the methods I am defining in these objects are being duplicated. I'm not sure if these methods can (or should) be moved down to the builder, or possibly out to another object altogether.</p>
<pre><code>function TasksGrid() {
'use strict';
var tasksGrid = WorkflowGridBuilder.buildTaskGrid();
//Public methods:
return {
setWidth: function (width) {
tasksGrid.setGridWidth(width, true);
},
reload: function (queueName, queueID) {
tasksGrid.clearGridData();
tasksGrid.setCaption(tasksGrid.defaultCaption);
$('#load_' + tasksGrid.prop('id')).show();
$.getJSON('../../csweb/Orders/GetTasks/?queueID=' + queueID, function (data) {
tasksGrid.setGridParam({
data: data
}).trigger('reloadGrid');
tasksGrid.setCaption(queueName + ' Tasks');
});
},
getSelectedTasks: tasksGrid.getSelectedRows,
setEventListener: function (eventName, onEvent) {
tasksGrid.bind(eventName, onEvent);
}
};
};
function OrdersGrid() {
'use strict';
var ordersGrid = WorkflowGridBuilder.buildOrdersGrid();
//Public methods:
return {
setWidth: function (width) {
ordersGrid.setGridWidth(width, true);
},
reload: function (queueName, queueID) {
ordersGrid.clearGridData();
ordersGrid.setCaption(ordersGrid.defaultCaption);
$('#load_' + ordersGrid.prop('id')).show();
$.getJSON('../../csweb/Orders/GetOrders/?queueID=' + queueID, function (data) {
ordersGrid.setGridParam({
data: data
}).trigger('reloadGrid');
ordersGrid.setCaption(queueName + ' Orders');
});
},
getSelectedOrders: ordersGrid.getSelectedRows,
setEventListener: function (eventName, onEvent) {
ordersGrid.bind(eventName, onEvent);
}
};
};
</code></pre>
<p>As you can see, TasksGrid and OrdersGrid both return the same methods.</p>
<p>I started by trying to move the 'setWidth' function down to WorkflowGridBuilder:</p>
<pre><code>//WorkflowGridBuilder's return:
return {
gridMethods: {
setWidth: function (width) {
//grid.setGridWidth(width, true);
}
},
buildOrdersGrid: ...
}
</code></pre>
<p>At this point I realized that my code would not work. There is no 'grid' object to call <code>setGridWidth</code> on. This object will not exist until one of my builder methods is called.</p>
<p>Does this mean that <code>TasksGrid</code> and <code>OrdersGrid</code> are forced to repeat their public methods in the way seen above? I don't see any good solutions.</p>
|
[] |
[
{
"body": "<p>You could try using the prototype design pattern.</p>\n\n<pre><code>function GridFactory(name, queueUrl, obj) {\n this.name = name;\n this.gridObj = obj;\n this.url = {\n queue : queueUrl\n };\n};\nGridFactory.prototype.setWidth = function(width){\n this.gridObj.setGridWidth(width, true);\n};\nGridFactory.prototype.setEventListener = function (eventName, onEvent) {\n this.gridObj.bind(eventName, onEvent);\n};\nGridFactory.prototype.reload = function (queueName, queueID) {\n this.gridObj.clearGridData();\n this.gridObj.setCaption(this.gridObj.defaultCaption);\n $('#load_' + this.gridObj.prop('id')).show();\n\n $.getJSON(this.url.queue + queueID, function (data) {\n this.gridObj.setGridParam({\n data : data\n }).trigger('reloadGrid');\n\n this.gridObj.setCaption(queueName + ' ' + this.name);\n });\n};\nGridFactory.prototype.getSelectedRows = function(){\n return this.gridObj.getSelectedRows;\n};\n\nfunction TasksGrid() {\n return new GridFactory('Task', \n '../../csweb/Orders/GetTasks/?queueID=', \n WorkflowGridBuilder.buildTaskGrid()\n );\n}\n\nfunction OrdersGrid() {\n return new GridFactory('Orders', \n '../../csweb/Orders/GetOrders/?queueID=', \n WorkflowGridBuilder.buildOrdersGrid()\n );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T04:02:38.370",
"Id": "16097",
"ParentId": "16088",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T21:06:21.410",
"Id": "16088",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Creating a jqGrid builder object"
}
|
16088
|
<p>I need to generate a Ruby hash that looks like this:</p>
<pre><code>{ "children" => [
{ "children" => [
{ "children" => [
{ "children" => [] }
]}
]}
]}
</code></pre>
<p>... for an arbitrary level of nesting. So far the best I've come up with is:</p>
<pre><code>def nested_hash(levels)
return {} if levels < 1
root = { 'children' => [] }
children = root['children']
(levels - 1).times { children = (children << { 'children' => [] }).first['children'] }
root
end
</code></pre>
<p>This doesn't seem particularly terse or elegant. Can anyone offer suggestions on making this more terse or elegant?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T07:48:16.100",
"Id": "26174",
"Score": "0",
"body": "why do you need arrays with a single element?"
}
] |
[
{
"body": "<p>Recursion perhaps?</p>\n\n<pre><code>def nested_hash(levels)\n return if levels <= 0\n { \"children\" => [ nested_hash(levels - 1) ].compact }\nend\n</code></pre>\n\n<p>Or it could be</p>\n\n<pre><code>def nested_hash(levels)\n return nil if levels <= 0\n array = nested_hash(levels - 1)\n { \"children\" => array.nil? ? [] : [array] }\nend\n</code></pre>\n\n<p>if you prefer handling the <code>nil</code> upfront, instead of removing it with <code>compact</code></p>\n\n<p>In either case, <code>nested_hash(3)</code> will get you</p>\n\n<pre><code>{\"children\"=>[\n {\"children\"=>[\n {\"children\"=>[]}\n ]}\n]}\n</code></pre>\n\n<p>Note that unlike yours, these ones will return <code>nil</code> when <code>levels</code> is zero or less. So you'll want to do the <code>{}</code> fallback elsewhere, e.g. <code>hsh = nested_hash(x) || {}</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T00:06:02.860",
"Id": "16091",
"ParentId": "16090",
"Score": "4"
}
},
{
"body": "<pre><code>def nested_hash(levels)\n return {} if levels < 1\n array = Array.new(levels, \"children\")\n array.reduce(nil) { |memo, item| { item => [memo].compact } }\nend\n</code></pre>\n\n<hr>\n\n<h2>Array.new</h2>\n\n<p><code>Array.new(levels, \"children\")</code> creates a levels-sized Array of \"children\" Strings.</p>\n\n<p><em>Example:</em></p>\n\n<pre><code>Array.new(3, \"foo\")\n#=> [\"foo\", \"foo\", \"foo\"]\n</code></pre>\n\n<hr>\n\n<h2>reduce</h2>\n\n<p><code>reduce</code> (which is an alias for <code>inject</code>) iterates over all elements of the Array, and accumulates the result in <code>memo</code>. We seed <code>memo</code>with <code>nil</code>.</p>\n\n<p><em>Example:</em></p>\n\n<p>The block passed to <code>reduce</code> looks like this in the first iteration:</p>\n\n<pre><code>{ \"children\" => [nil].compact }\n#=> { \"children\" => [] }\n</code></pre>\n\n<p><code>memo</code> now holds that result.</p>\n\n<p>The block in the second iteration:</p>\n\n<pre><code>{ \"children\" => [{ \"children\" => [] }].compact }\n#=> { \"children\" => [{ \"children\" => [] }] }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T01:06:30.777",
"Id": "26167",
"Score": "0",
"body": "I just realized that instead of doing `Array.new(levels, \"children\"` you could also simply do `array = [\"children\"] * levels`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T01:16:05.233",
"Id": "26168",
"Score": "0",
"body": "Clever. In super-terse mode: `def nested_hash(levels); levels < 1 ? nil : ([\"children\"] * levels).reduce(nil) { |memo, item| { item => [memo].compact } }; end`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T13:56:10.697",
"Id": "26199",
"Score": "0",
"body": "for me \"terse\" implies \"readability\" that's why I've expanded it a little bit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T18:04:52.453",
"Id": "26211",
"Score": "0",
"body": "Of course - by \"super-terse\" I meant \"waaay to compacted to actually be useful\"; wasn't being serious about writing code like that"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T00:30:06.220",
"Id": "16092",
"ParentId": "16090",
"Score": "3"
}
},
{
"body": "<pre><code>h = Hash.new { |hash, key| hash[key] = [Hash.new(&hash.default_proc)] }\n</code></pre>\n\n<p>Not sure if this fits your needs, but this creates a hash that if accessed with #[] and the key doesn't exist, automatically creates that key with the value being an array with 1 element: another hash which behaves identically.</p>\n\n<p>So initially the hash is empty:</p>\n\n<pre><code>>> h = Hash.new { |hash, key| hash[key] = [Hash.new(&hash.default_proc)] }\n=> {}</code></pre>\n\n<p>But will create the required structure when accessed.</p>\n\n<pre><code>>> h[:children][0][:children][0][:children]\n=> [{}]\n>> h\n=> {:children=>[{:children=>[{:children=>[{}]}]}]}</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T02:51:04.380",
"Id": "26655",
"Score": "0",
"body": "Thanks - that's a very neat implementation, but doesn't do what I want (when fed into a recursive parser, it would eventually cause a stack overflow)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-09T10:33:07.270",
"Id": "16348",
"ParentId": "16090",
"Score": "3"
}
},
{
"body": "<p>You can use the Ruby Gem <a href=\"https://rubygems.org/gems/xkeys\" rel=\"nofollow\">xkeys</a> which extends the hash to have nesting capabilities:</p>\n\n<pre><code>require 'xkeys'\n\nh = {}.extend XKeys::Auto\nh['children', 0, 'children', 0, 'children', 0, 'children'] = []\n</code></pre>\n\n<p>OR, maybe you have something like this...</p>\n\n<pre><code>path = ['children', 0, 'children', 0, 'children', 0, 'children']\nh[*path] = []\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T00:03:22.770",
"Id": "46687",
"ParentId": "16090",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "16091",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T23:09:22.470",
"Id": "16090",
"Score": "5",
"Tags": [
"ruby"
],
"Title": "Terser way of generating deeply nested hash"
}
|
16090
|
<p>In getting accustomed to Clojure syntax, I wrote the following <code>stutter</code> function:</p>
<pre><code>(defn doublelist [coll]
(flatten (map (fn [x] [x x]) coll)))
(defn stutter [s]
(clojure.string/join
" " (doublelist (clojure.string/split s #" "))))
</code></pre>
<p>This duplicates every word in an input string:</p>
<pre><code>(stutter "how are you?")
"how how are are you? you?"
</code></pre>
<p>The <code>doublelist</code> function bugs me. It seems that repeating items in a list should be possible without a call to <code>flatten</code>.</p>
<p>Any thoughts?</p>
|
[] |
[
{
"body": "<p>You may use <code>mapcat</code> to omit <code>flatten</code>:</p>\n\n<pre><code>user> (defn doublelist [coll]\n (mapcat #(repeat 2 %) coll))\n#'user/doublelist\nuser> (doublelist [:a :b :c :d])\n(:a :a :b :b :c :c :d :d)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T06:28:12.660",
"Id": "16098",
"ParentId": "16094",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "16098",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T01:44:10.717",
"Id": "16094",
"Score": "2",
"Tags": [
"clojure"
],
"Title": "Idiomatic text munging in Clojure"
}
|
16094
|
<p>I'm working alone on my code, trying to learn Ruby as I go.</p>
<p>Class <code>Robot</code> is supposed to be instantiated with the position on a map, and whether it is facing toward a side of the map. It has a couple of moves: left or right, where the face of the robot changes direction, and a move action, one step forward.</p>
<pre><code>class Robot
def initialize(pos_X, pos_Y, facing)
@pos_X, @pos_Y, @facing = pos_X, pos_Y, facing
end
def move
world_switch(Proc.new { @pos_X += 1}, Proc.new { @pos_X -= 1},
Proc.new { @pos_Y += 1}, Proc.new { @pos_Y -= 1})
end
def left
world_switch(Proc.new {@facing = 'WEST'}, Proc.new {@facing = 'EAST'},
Proc.new {@facing = 'NORTH'}, Proc.new {@facing = 'SOUTH'})
end
def right
world_switch(Proc.new {@facing = 'EAST'}, Proc.new {@facing = 'WEST'},
Proc.new {@facing = 'SOUTH'}, Proc.new {@facing = 'NORTH'})
end
def report
puts "Output: " << @pos_X.to_s << ',' << @pos_Y.to_s << ',' << @facing
end
def world_switch(do_on_north, do_on_south, do_on_east, do_on_west)
case @facing
when 'NORTH'
do_on_north.call
when 'SOUTH'
do_on_south.call
when 'EAST'
do_on_east.call
when 'WEST'
do_on_west.call
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Looks like you over-thought it a little bit. Callbacks are indeed a powerful abstraction, but it looks overkill in this case. Some notes:</p>\n\n<ul>\n<li>Use symbols to codify <code>@facing</code>: :east, :north, ...</li>\n<li><p>a hint to write <code>move</code> without callbacks:</p>\n\n<pre><code>increments = {:north => [0, +1], :east => [+1, 0], :south => [0, -1], :west => [-1, 0]}\n</code></pre></li>\n<li><p>A hint to write <code>left</code> without callbacks:</p>\n\n<pre><code>new_facing = {:north => :west, :east => :north, :south => :east, :west => :south}\n</code></pre></li>\n</ul>\n\n<p>This way you describe what the robot does not with code (callbacks) but with data structures (which can be as simple as a hash).</p>\n\n<p>As requested: the complete implementation of <code>left</code>:</p>\n\n<pre><code>def left\n new_facing = {:north => :west, :east => :north, :south => :east, :west => :south}\n @facing = new_facing[@facing]\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T08:51:01.020",
"Id": "26243",
"Score": "0",
"body": "+1 to write the code without callbacks (in this case def)\n\nBut can't understand how 'new_facing' will be implemented, please look at the implementation file posted later: http://codereview.stackexchange.com/questions/16109/needs-code-review-for-class-implementation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T08:34:39.950",
"Id": "16140",
"ParentId": "16107",
"Score": "3"
}
},
{
"body": "<p>You should definitely apply tokland's suggestions. Additionally:</p>\n\n<ul>\n<li><p>Don't use String concatenation (<code><<</code>, <code>+</code>, <code>+=</code>), use interpolation (<code>\"the value is: #{value}\"</code>) it's more readable, and faster</p></li>\n<li><p>Make private methods private, in this case <code>world_switch</code>, but after the refactor, it should already be gone :)</p></li>\n<li><p>I'd rename <code>report</code> to <code>to_s</code> this has two advantages:</p>\n\n<ul>\n<li>it's the 'natural' method to call when you want a String representation of something</li>\n<li>it is implicitly called when using String interpolation: <code>\"my robot: #{@robot}\" # no need for @robot.to_s</code></li>\n</ul></li>\n<li><p>You could also replace <code>report</code> by using <code>@robot.inspect</code>, this will give you the standard String representation for your Robot</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T00:46:40.593",
"Id": "17906",
"ParentId": "16107",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16140",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T12:38:45.600",
"Id": "16107",
"Score": "1",
"Tags": [
"ruby",
"object-oriented"
],
"Title": "General review of Robot class"
}
|
16107
|
<p>could you please review the code for the implementation of the class (link: <a href="https://codereview.stackexchange.com/questions/16107/ruby-code-review-working-alone-on-the-code">General review of Robot class</a>)</p>
<pre><code>require_relative 'robot'
class Game
def initialize
# initialize values
@commands = %w{PLACE MOVE LEFT RIGHT REPORT}
@facings = %w{NORTH SOUTH EAST WEST}
@pos_X, @pos_Y = nil, nil
@facing, @robot, @r = nil, nil, nil
command = get_initial_command
setup(command)
end
def setup(command)
params = command.gsub(/[PLACE]/, '').split(',')
if (params[0] != nil && params[1] != nil && params[2] != nil)
@pos_X = params[0].to_i
@pos_Y = params[1].to_i
@facing = params[2]
@r = Robot.new(@pos_X, @pos_Y, @facing)
if is_valid_position
@robot = @r
else
Game.new
end
command = get_commands
else
Game.new
end
end
def get_initial_command
command = gets.strip
if command.include?("PLACE")
return command
else
command = get_initial_command
end
end
def get_commands
is_command = false
command = gets.strip
@commands.each do |c|
if command.include?(c)
is_command = true
break
end
end
if is_command
translate_command(command)
command = get_commands
return command
else
command = get_commands
end
end
def translate_command(command)
case command
when command.include?('PLACE')
puts 'place the command'
setup(command)
when 'MOVE'
@robot.move if is_valid_move
when 'RIGHT'
@robot.right
when 'LEFT'
@robot.left
when 'REPORT'
@robot.report
when 'EXIT'
Kernel.abort(false)
end
end
def is_valid_move
if ((@robot.instance_variable_get("@pos_X") == 0 && @robot.instance_variable_get("@facing") == 'SOUTH') ||
(@robot.instance_variable_get("@pos_X") == 5 && @robot.instance_variable_get("@facing") == 'NORTH') ||
(@robot.instance_variable_get("@pos_Y") == 0 && @robot.instance_variable_get("@facing") == 'WEST') ||
(@robot.instance_variable_get("@pos_Y") == 5 && @robot.instance_variable_get("@facing") == 'EAST'))
return false
else
return true
end
end
def is_valid_position
is_proper_facing = false
@facings.each do |f|
if f.include?(@r.instance_variable_get("@facing"))
is_proper_facing = true
break
end
end
if (@r.instance_variable_get("@pos_X") < 0 || @r.instance_variable_get("@pos_X") > 5 ||
@r.instance_variable_get("@pos_Y") < 0 || @r.instance_variable_get("@pos_Y") > 5 || !is_proper_facing)
return false
else
return true
end
end
end
a = Game.new
</code></pre>
|
[] |
[
{
"body": "<p>A couple of issues I found or suggestions I have:</p>\n\n<ul>\n<li>avoid unnecessary or redundant comments (like <code># initialize values</code> within <code>initialize</code>)</li>\n<li>use symbols for your commands and facings</li>\n<li>don't use upper case letters in your variable names (<code>pos_x</code> or just <code>x</code> instead of <code>pos_X</code>)</li>\n<li>no need to check for <code>!= nil</code>, you can simply do <code>params[0] && params[1] &&params[2]</code></li>\n<li>I'd convert simple <code>if</code>s to use the ternary operator instead: <code>is_valid_position ? @robot = @r : Game.new</code></li>\n<li>find a better name for <code>@r</code></li>\n<li>I'm not sure why you're using <code>instance_variable_get</code> instead of just <code>@robot.pos_X</code></li>\n</ul>\n\n<p>Try to refactor your longer methods. Take <code>setup</code> as example, personally, I'd like it to look somewhat like this:</p>\n\n<pre><code>def setup(command)\n begin\n params = get_params(command)\n rescue ParamsInvalidError\n restart\n end\n\n new_robot(params)\n restart unless is_valid_position?\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T00:26:22.257",
"Id": "28502",
"Score": "0",
"body": "Good stuff, look at that one as well, please\n\nhttp://codereview.stackexchange.com/questions/16107/ruby-code-review-working-alone-on-the-code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T15:59:47.113",
"Id": "17887",
"ParentId": "16109",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "17887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T13:08:06.057",
"Id": "16109",
"Score": "2",
"Tags": [
"ruby",
"object-oriented"
],
"Title": "Needs code review for class implementation"
}
|
16109
|
<p>I wrote the following code for a Dynamic Programming problem but the online judge gives me a 'Time Limit Exceeded' error. How can I optimize this code to make it more efficient, especially the part of initializing the DP array to 0.0 (I am using <code>memset()</code> right now)?</p>
<p>Problem:</p>
<ol>
<li>There are N values in an array. Two players take turn by turn to play the game.</li>
<li>Player1, with 50% probability can pick the left most value or the right most value.
3.If there is only one value left in the array, the player, having no more choice, will just pick up that value.</li>
<li>Question is to calculate the expected sum of values that First player can obtain.</li>
<li>\$T <= 500\$ and \$N <= 2000\$</li>
</ol>
<p></p>
<pre><code>#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstring>
using namespace std;
#define max 2000
int main(){
int T;
double **dp = new double*[max];
for(int i=0; i<max; ++i)
dp[i] = new double[max];
cin >> T;
while(T--){
int N;
cin >> N;
int V[N];
for(int i=0; i<N; ++i)
cin >> V[i] ;
for(int i=0; i<N; ++i)
memset(dp[i], 0.0, sizeof(dp[0][0])*N);
for(int i=0; i<N; ++i)
dp[i][i] = V[i];
for(int j=1; j<N; ++j)
for(int i=j-1; i>=0; --i){
dp[j][i] = 0.5 * ( dp[i][i] + dp[j][j] + dp[j-1][i+1] );
if( (i+2)<N )
dp[j][i] += (0.250 * dp[j][i+2]);
if( (j-2)>=0 )
dp[j][i] += (0.250 * dp[j-2][i]);
}
cout << setprecision (5) << dp[N-1][0] << endl;
}
for(int i=0; i<max; ++i)
delete[] dp[i];
delete dp;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T12:15:15.433",
"Id": "26269",
"Score": "0",
"body": "Is there a public url that you could point us to for information on the problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T13:39:51.543",
"Id": "26271",
"Score": "0",
"body": "Glenn: I've updated the Question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T18:04:48.503",
"Id": "26297",
"Score": "0",
"body": "What is the time limit? Do you have any idea how much you're failing it by? That should help indicate if another approach is required."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T18:34:48.657",
"Id": "26300",
"Score": "0",
"body": "sadly, I don't get to know the time when my code gets interuppted but for this question they give 4sec on their servers for K<=500 and N<=2000. I too guess theres' nothing much left to optimize so I've to come up with something better than O(N^2). like- O(NlogN) or O(N). Thanks for all your help guys."
}
] |
[
{
"body": "<p>It looks like the nested loops of your algorithm are using only three rows of the <code>dp</code> matrix:</p>\n\n<pre><code>dp[j]\ndp[j-1]\ndp[j-2]\n</code></pre>\n\n<p>You can use this observation to transform your solution from one requiring <code>O(N^2)</code> space to one requiring <code>O(N)</code> space by changing</p>\n\n<pre><code>double **dp = new double*[max];\n</code></pre>\n\n<p>to</p>\n\n<pre><code>double dp[3][max]; // Now your matrix has a chance of fitting on the stack\n</code></pre>\n\n<p>and adding <code>%3</code> to all operations that touch the first index of the <code>dp</code> matrix.</p>\n\n<p>This may or may not eliminate the timeout, but it will make your program better by reducing the amount of resources that it needs to operate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:09:22.513",
"Id": "26288",
"Score": "0",
"body": "Thanks for suggesting a memory efficient approach. I've updated my code but it still goes over the allowed Time Limit!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:11:06.733",
"Id": "26289",
"Score": "0",
"body": "@srbh.kmr Does it produce the correct output? Can you switch from `double` to `float`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:15:02.977",
"Id": "26291",
"Score": "0",
"body": "I think so. Yes, it never gives me a 'Wrong answer' just runs out of time when submitted. and yes, I can change double to float but what difference would it make specifically? i wonder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:26:50.303",
"Id": "26292",
"Score": "0",
"body": "@srbh.kmr Changing `double`s to `float`s will reduce the amount of data needed for computation in half, improving the chance of hitting the cache more often."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:33:34.430",
"Id": "26294",
"Score": "0",
"body": "Oh. Right. I was under the wrong impression that both double and float are 4Bytes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:45:50.997",
"Id": "26295",
"Score": "0",
"body": "I tried using float instead of double, still No luck getting accepted. 'Time Limit Exceeded'."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T14:31:37.650",
"Id": "16155",
"ParentId": "16111",
"Score": "2"
}
},
{
"body": "<p>There are some things that I can think of:</p>\n\n<ol>\n<li>Is it quicker to deal with one blob of size max*max, and replacing dp[i][j] with dp[i+j*N]?</li>\n<li>Are you sure that your values are doubles, or could they be 32, 16, or even 8-bit integers? - less space to alloc/memset. Similarly, is your 2000 limit a specified one or one \"large enough\"?</li>\n<li>I'm not convinced that you <em>actually</em> need memset at all (You'll need to guard the <code>dp[j-1][i+1]</code> term which reaches below the diagonal for the first cells)! Because you're always refering to values to the 'bottom left' of the current cell, you never access values generated by the previous run...</li>\n<li>Also, because you \"shouldn't\" access values below the diagonal, all the dp[i] lines are actually (N - i) in length, so less to alloc/zero. You will though need to make other changes to the indices in the loops (and especially guard the <code>dp[j-1][i+1]</code> term).</li>\n</ol>\n\n<p>And although it won't actually save any time, you can 'squash' a couple of loops together.</p>\n\n<pre><code>for(int i=0; i<N; ++i) {\n int V;\n cin >> V;\n memset( dp[i], 0, sizeof(dp[0][0])*N );\n dp[i][i] = V;\n}\n</code></pre>\n\n<p>And don't forget that the final delete should be <code>delete[] dp;</code>!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:12:25.190",
"Id": "26290",
"Score": "0",
"body": "Thanks for your review. Points noted but yes, result has to be a double. and T<=500 and N<=2000 is specified.\nand I need to do memset in order to zero out the dp[][] array for every new testcases. I know I'm allocating almost twice as many elements as I need to, but please take a look at my updated code. It still gives me 'Time Limit Exceeded' error!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:30:39.287",
"Id": "26293",
"Score": "0",
"body": "Actually, yes I can see I don't need that memset at all. Thanks,"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T15:43:20.387",
"Id": "16157",
"ParentId": "16111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T13:50:49.517",
"Id": "16111",
"Score": "6",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Efficient implementation of a Dynamic Programming challenge"
}
|
16111
|
<p>I was trying to figure out how to make a breakable foreach macro for STL containers and I came up with this method that uses templates to recognize the container type automatically. Are there any performance / code-wise improvements you can think of?</p>
<pre><code>// polymorphic break-able foreach test that works with nested calls on the same type of container
#include <vector>
#include <list>
#include <iostream>
#include <unordered_map>
std::unordered_map<void *, bool> _advance_iterator__instances_done;
template <class Tc, class Ti>
bool advance_iterator(Tc &container, Ti &iterator)
{
static typename Tc::iterator it;
if (_advance_iterator__instances_done[&container])
{
it = container.begin();
_advance_iterator__instances_done[&container] = false;
}
if (it == container.end())
{
_advance_iterator__instances_done[&container] = true;
return false;
}
iterator = *it;
it++;
return true;
}
#define foreach(value_type, iterator, container) \
_advance_iterator__instances_done[&container] = true; \
for (value_type iterator; advance_iterator(container, iterator); )
int main(int argc, char *argv[])
{
std::vector<int> vec;
std::list<int> lis;
std::list<std::list<int>> matrix;
// populate containers
for (int i = 0; i < 10; i++)
{
static std::list<int> row;
vec.push_back(i);
lis.push_back(i + 10);
for (int j = 1; j <= 10; j++)
row.push_back(j * i);
matrix.push_back(row);
row.clear();
}
// regular foreach test
std::cout << "vec:" << std::endl;
foreach(int, value, vec)
std::cout << value << std::endl;
std::cout << std::endl << "half of lis:" << std::endl;
// breaking test
foreach(int, value, lis)
{
std::cout << value << std::endl;
if (value == 14)
break;
}
// regular again
std::cout << std::endl << "full lis:" << std::endl;
foreach(int, value, lis)
std::cout << value << std::endl;
// nested test
std::cout << std::endl << "matrix:" << std::endl;
foreach(std::list<int>, row, matrix)
{
foreach(int, value, row)
std::cout << value << " ";
std::cout << std::endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T15:11:11.290",
"Id": "26203",
"Score": "1",
"body": "Have you seen [boost's FOREACH](http://www.boost.org/doc/libs/1_51_0/doc/html/foreach.html)?"
}
] |
[
{
"body": "<p>This line gives my nightmares:</p>\n\n<pre><code>std::unordered_map<void *, bool> _advance_iterator__instances_done;\n</code></pre>\n\n<p>First up the name is <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797\">reserved</a>. Prefer not to use identifiers without a leading underscore (the rules are not trivial and everybody gets them wrong so just avoid them).</p>\n\n<p>Secondly the size of the map is unbound. If you have a really large application (runs a long time) this is going to continuously grow.</p>\n\n<p>This construct</p>\n\n<pre><code>bool advance_iterator(Tc &container, Ti &iterator)\n{\n static typename Tc::iterator it;\n</code></pre>\n\n<p>makes the whole thing not thread safe.</p>\n\n<p>Your naming convention makes it confusing to read:</p>\n\n<pre><code>#define foreach(value_type, iterator, container) \\\n ^^^^^^^^^^^\n This is never the iterator it is the value.\n</code></pre>\n\n<p>Overall I think the <a href=\"http://www.boost.org/doc/libs/1_51_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\">boost FOREACH</a> is a better choice for C++03 and C++11 now has a <a href=\"https://stackoverflow.com/questions/5032435/new-c11-range-for-foreach-syntax-which-compilers-support-it\">built in version</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T15:38:40.880",
"Id": "26204",
"Score": "0",
"body": "Thanks for the review, I added a cleanup to avoid the map growing in size, fixed the wrong naming for the value in the macro and wrapped everything in a namespace. How's it now? By the way, boost foreach requires you to pass the container type so I made this mainly for fun and also to shorten code :)\n\nEDIT: oh yeah boost foreach doesnt require container type, but still, I made this for fun and for learning purposes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T15:43:01.610",
"Id": "26206",
"Score": "0",
"body": "@FrancescoNoferi: No boost for each only requires you to pass the type of the value you want to see inside your loop. If the value_type of the container is convertible to this it will compile and convert otherwise not. `std::vector<float> vec; BOOST_FOREACH(int loop, vec) { std::cout << loop << \"\\n\";}` Each value of `vec` is converted to the integer during assignment to `loop`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T15:45:33.417",
"Id": "26207",
"Score": "0",
"body": "Yeah, my bad, but yeah making my own is a good learning experience and I don't need to have boost libraries just to use foreach for a project that doesn't use anything else of the boost libraries"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T15:48:38.810",
"Id": "26208",
"Score": "1",
"body": "Any developer that does not already have boost installed is probably not doing real C++ development. Boost is now so ubiquitous that not having boost is the exception to the rule and as soon as you need it the first time you install it and always have it. It comes standard in most Linux development distributions now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T15:23:59.650",
"Id": "16114",
"ParentId": "16113",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T14:23:29.227",
"Id": "16113",
"Score": "2",
"Tags": [
"c++",
"template",
"iterator"
],
"Title": "Polymorphic STL foreach without passing the container type"
}
|
16113
|
<p>How can I simplify this jQuery code? I feel like I should be able to do this with one click function.</p>
<p><strong>jQuery</strong></p>
<pre><code>$('.btn').eq(0).click(function () { $('.carousel').css({ 'left': '0%' }); });
$('.btn').eq(1).click(function () { $('.carousel').css({ 'left': '-100%' }); });
$('.btn').eq(2).click(function () { $('.carousel').css({ 'left': '-200%' }); });
$('.btn').eq(3).click(function () { $('.carousel').css({ 'left': '-300%' }); });
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><ul>
<li><a href="" class="btn">Button 1</a></li>
<li><a href="" class="btn">Button 2</a></li>
<li><a href="" class="btn">Button 3</a></li>
<li><a href="" class="btn">Button 4</a></li>
</ul>
</code></pre>
|
[] |
[
{
"body": "<p>You are correct, you can <a href=\"https://stackoverflow.com/q/1188760/352449\">have one function</a> binding <code>click</code> events to all of your <code>.btn</code> elements.</p>\n<p>Working <a href=\"http://jsfiddle.net/zuul/zxSD3/\" rel=\"nofollow noreferrer\">Fiddle Example</a>:</p>\n<pre><code>$('.btn').bind("click", function(event) {\n event.preventDefault();\n var index = $(this).parent().index();\n $('.carousel').css({ 'left': '-' + (index*100) + '%' });\n});\n</code></pre>\n<p><sup>jQuery documentation about <a href=\"http://api.jquery.com/index/\" rel=\"nofollow noreferrer\">index()</a>.</sup></p>\n<p><strong>Describing what's being suggested:</strong></p>\n<ol>\n<li><p>Bind the <code>click</code> to the <code>.btn</code> class and within the click event you ascertain the index position:</p>\n<p>I've opted to use <code>bind()</code> since it's performance efficient when compared with <code>click()</code>.<br />\nAnother reason is the fact that all your elements share the same class, so, you only need to bind a click event to the class instead of attaching a click handler to each <code>.btn</code>.</p>\n</li>\n<li><p>Use the index and multiply it by 100 as to get the desired <code>left</code> value:</p>\n<p>This way you can easily ascertain the correct value since you have a direct relation between the anchor's parent index and the desired <code>left</code> value.</p>\n</li>\n<li><p>Using <code>event.preventDefault();</code> to prevent the browser from following the <code>href</code>:</p>\n<p>With this, you tell the browser to leave the <code>href</code> attribute alone, thus preventing it to bubble up.</p>\n</li>\n<li><p>Safe to use the minus signal all the time, since <code>0</code> and <code>-0</code> is the same thing.</p>\n</li>\n</ol>\n<hr />\n<p>In order to further improve the function, and if using the lastest jQuery, I would give an <code>id</code> to the <code>ul</code> element, thus losing the <code>.btn</code> class, having the click event binded to a single DOM element thru delegation:</p>\n<pre><code>$('#myUL').on("click", "a", function(event) {\n event.preventDefault();\n var index = $(this).parent().index();\n $('.carousel').css({ 'left': '-' + (index*100) + '%' });\n});\n</code></pre>\n<p><sup>jQuery documentation about <a href=\"http://api.jquery.com/on/\" rel=\"nofollow noreferrer\">on()</a>.</sup></p>\n<p>Useful reading: <a href=\"https://stackoverflow.com/q/10082031/352449\">Why use jQuery on() instead of click()</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T19:38:55.323",
"Id": "26222",
"Score": "0",
"body": "This is perfect. Thanks for the extra information as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T19:52:36.563",
"Id": "26223",
"Score": "0",
"body": "Why not use `.on()` directly in your first example? Also, I would bind to the anchor and not to the li."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T20:02:40.200",
"Id": "26224",
"Score": "0",
"body": "@ANeves Thank you, I've updated the answer as I should have placed the bind over the anchor in the first place... (distracted). About both suggestions, the first one is to cover an old jQuery version as I don't know what version is OP using."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T19:13:58.623",
"Id": "16116",
"ParentId": "16115",
"Score": "3"
}
},
{
"body": "<p>Some problems you have to be aware of:</p>\n\n<pre><code>var index = $(this).index();\n</code></pre>\n\n<p>...constructs a singleton jQuery set, so index() will be a constant 0.</p>\n\n<pre><code>var index = $(this).parent().index();\n</code></pre>\n\n<p>...coincidentally does the trick here. But it's not the index from the selected jQuery set, but rather the index of the selected DOM node within the parent node's children. It will not yield the desired result anymore if you f.ex. insert an additional <code><li>Buttons</li></code> as the first item in the <code><ul></code>.</p>\n\n<pre><code>var set = $('.btn');\nset.click(function() {\n console.log('via set: ' + set.index(this));\n});\n</code></pre>\n\n<p>β...will always yield the desired result, no matter what other nodes are around.</p>\n\n<p>I created a fiddle <a href=\"http://jsfiddle.net/4jxvZ/1/\" rel=\"nofollow\">http://jsfiddle.net/4jxvZ/1/</a> that shows the three different behaviors (open your browser's js console, it logs the different index values).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T20:22:57.600",
"Id": "16122",
"ParentId": "16115",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16116",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T18:52:01.003",
"Id": "16115",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Simplify multiple jQuery click functions"
}
|
16115
|
<p>I have two lists with ca. 4000 elements where each each element have two columns. These are being fed into a function. Besides the function they are being fed into, is it possible to speed it up somehow? At this rate, it will take ca. 6-7 days to complete.</p>
<pre><code>results=rep(0, length(as.numeric(unlist(coors))))
for(i in names(coors)){
print(i)
for( j in names(pols)){
results[i]=point.in.polygon(coors[[i]][,1], coors[[i]][,2], pols[[j]][,1], pols[[j]][,2])
}}
</code></pre>
<p>EDIT: further description, I have the polygons for each ind in year 1 and the coordinates for year 2. I want to see how many of the locations from year 2 that falls within the polygon from year 1 for each individual.</p>
<p>EDIT 2: the structure of <code>coors</code> </p>
<pre><code> str(coors)
List of 4052
$ 2225 :'data.frame': 48 obs. of 2 variables:
..$ cor.x: num [1:48] 635184 635215 635394 635431 635430 ...
..$ cor.y: num [1:48] 7151002 7151201 7151175 7151110 7151118 ...
$ 2226 :'data.frame': 56 obs. of 2 variables:
..$ cor.x: num [1:56] 635945 635936 635944 635969 635947 ...
..$ cor.y: num [1:56] 7152813 7152847 7152834 7152785 7152810 ...
$ 2227 :'data.frame': 56 obs. of 2 variables:
..$ cor.x: num [1:56] 636244 636245 636317 636450 636386 ...
..$ cor.y: num [1:56] 7151503 7151505 7151628 7151693 7151799 ...
$ 2228 :'data.frame': 56 obs. of 2 variables:
..$ cor.x: num [1:56] 636451 636418 636408 636467 636495 ...
..$ cor.y: num [1:56] 7152610 7152605 7152634 7152572 7152537 ...
</code></pre>
<p>There are always either 48 or 56 obs per element level. <code>Pols</code> have similar structure, but more variable lengths as the number of observations depends on the shape of the polygon.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T08:07:03.060",
"Id": "26214",
"Score": "0",
"body": "I suggest you describe the task that you are trying to accomplish so that we can help you rethink the design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T08:07:46.553",
"Id": "26215",
"Score": "0",
"body": "Are these polygons mutually distinct? If so, you might save time by not checking further after a match is found. Any other constraints might help as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T09:30:54.240",
"Id": "26216",
"Score": "0",
"body": "I have updated with some more description that I hope might help. @DWin they are not necessarily distinct and they don't need to be."
}
] |
[
{
"body": "<p>What you have here is a nested loop. Since the inner loop is executed 4000 times for each iteration of the outer loop, the total number of calls to point.in.polygon is 4000^2 so 16 million times. </p>\n\n<p>The problem lies in how often the method is called and there is usually no direct way of speeding this up. <strong>Loop execution is only the tiniest fraction of the runtime spend here</strong>, the major amount of time will most likely be lost inside point.in.polygon. You can prove this by removing the function call to <code>point.in.polygon</code> and calling a dummy method instead.</p>\n\n<p>Your best bet is finding a better algorithmic solution to your problem instead of trying to improve the brute force version you have here. As I understand it, you also overwrite the results[i] array for each inner call to point.in.polygon which basically means that only the last j-value's result will be saved anyway.</p>\n\n<p>If you can not come up with a better algorithm, an alternative would be to execute the code in a multithreaded way. Maybe <a href=\"https://stackoverflow.com/questions/1395309/how-to-make-r-use-all-processors\">https://stackoverflow.com/questions/1395309/how-to-make-r-use-all-processors</a> is a good starting point for that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T09:31:23.397",
"Id": "26217",
"Score": "0",
"body": "Thank you, I have tried to look at multiprocessing. I thought I was adding the results of the function to the results-vector. The function results is simply a vector with 1s and 0s (are the coordinate inside or outside the polygon) as long as the vector for coordinates."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T07:59:53.463",
"Id": "16119",
"ParentId": "16118",
"Score": "2"
}
},
{
"body": "<p>I assume you are using <code>point.in.polygon</code> from the <code>sp</code> package. The function can take any number of points, so you should rewrite your algorithm as a single loop: for each polygon in <code>pols</code>, make a single call to <code>point.in.polygon</code> to check if <strong>all</strong> the points in <code>coords</code> are inside or not. This should save you a lot of time. Then you'll only have to do a little work reformatting the output. I can help with the code if you can please clarify what <code>coors</code> looks like.</p>\n\n<p><strong>Edit</strong>: Here is now an example of how you could code this into a single loop. It is possible you will have to work it a bit as you have not really shown us how you want to store your output.</p>\n\n<p>First, some sample data:</p>\n\n<pre><code>coors <- replicate(5, {n <- sample(5:10, 1);\n data.frame(x = runif(n), y = runif(n))},\n simplify = FALSE)\n\npols <- replicate(3, {n <- sample(5:10, 1)\n data.frame(x = runif(n), y = runif(n))},\n simplify = FALSE)\n</code></pre>\n\n<p>Here, we concatenate all the points in <code>coors</code> together, but keep a vector of group indices which we will use later for splitting by group:</p>\n\n<pre><code>all.coors <- do.call(rbind, coors)\nnum.points <- sapply(coors, nrow)\ngroup.idx <- rep(seq_along(coors), num.points)\n</code></pre>\n\n<p>Now the single loop:</p>\n\n<pre><code>results <- vector(\"list\", length(pols)) \nfor (j in seq_along(pols)) {\n print(j)\n results[[j]] <- split(point.in.polygon(all.coors[,1], all.coors[,2],\n pols[[j]][,1], pols[[j]][,2]),\n group.idx)\n}\n</code></pre>\n\n<p>I am confident this will significantly speed up your computations. However, if this is still too slow, I agree you'll have to consider parallelization. Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T12:57:06.167",
"Id": "26218",
"Score": "0",
"body": "I have now added more description :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T06:48:27.357",
"Id": "26219",
"Score": "0",
"body": "Wow! Thank you for the time and effort! :) I have the coors also as a dataframe, so I was thinking about storing it as a new column there and then just use `ave()` to count number of 1's for each id."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T11:18:00.137",
"Id": "16120",
"ParentId": "16118",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T07:51:08.563",
"Id": "16118",
"Score": "3",
"Tags": [
"performance",
"r"
],
"Title": "Speeding up for-loop over a list"
}
|
16118
|
<p>I want to implement numbering scheme like Microsoft Word uses for numbering.
first one gets = A,next is B, next is C, .... then AA, then AB,....and so on.
as shown below</p>
<pre><code> A
B
C
.
.
AA
AB
AC
.
.
AAA
AAB
....
</code></pre>
<p>'=>' here means converted to.</p>
<p>some examples: </p>
<pre><code>1 => A
26 => Z
27 => AA
52 => AZ
53 => BA
</code></pre>
<p>and heres the code for it:</p>
<pre><code> var convertToNumberingScheme = function(n){
var x = n-1,
r26 = x.toString(26),
baseCharCode = "A".charCodeAt(0);
var arr = r26.split(''),
len = arr.length;
var newArr =arr.map(function(val,i){
val = parseInt(val,26);
if( (i === 0) && ( len > 1)){
val = val-1;
}
return String.fromCharCode(baseCharCode + val);
});
return newArr.join('');
}
</code></pre>
<p>It seems to work fine, but any ideas if there are some potential bugs or ways to optimize this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T21:30:52.340",
"Id": "26227",
"Score": "1",
"body": "If you're using HTML then just place `ul` or `ol`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T21:34:24.703",
"Id": "26228",
"Score": "0",
"body": "@LarryBattle Thanks. But it is a custom canvas app, can't use ul,li but good pointer nonetheless ."
}
] |
[
{
"body": "<p>The function in the question converts to base 26, then splits the resulting string, and converts each digit back to decimal - and then to a letter. That seems roundabout.</p>\n\n<p>Here's a simpler one:</p>\n\n<pre><code>function convertToNumberingScheme(number) {\n var baseChar = (\"A\").charCodeAt(0),\n letters = \"\";\n\n do {\n number -= 1;\n letters = String.fromCharCode(baseChar + (number % 26)) + letters;\n number = (number / 26) >> 0; // quick `floor`\n } while(number > 0);\n\n return letters;\n}\n</code></pre>\n\n<p>This function basically does a repeated \"divmod\" of the input number; getting the modulus 26 and the quotient (floor of n divided by 26). The modulus is converted to a A-Z character that's prepended to the output string, and the quotient is used as the input for the next iteration of the loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T22:26:34.290",
"Id": "16129",
"ParentId": "16124",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "16129",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T21:16:56.910",
"Id": "16124",
"Score": "10",
"Tags": [
"javascript",
"strings",
"array",
"number-systems"
],
"Title": "Implement numbering scheme like A,B,C... AA,AB,... AAA..., similar to converting a number to radix26"
}
|
16124
|
<p>I quite like this extra credit assignment I did for Zed Shaw's Learn Python The Hard Way. Its a neat little text adventure game that uses stats. I would like to eventually expand this, but let me know how the code looks so far! </p>
<pre><code># Legend Of Doobieus
import random
from sys import exit
#rolls 3d6
def roll_3d6():
a = random.randint(1, 6)
b = random.randint(1, 6)
c = random.randint(1, 6)
list = [a, b, c,]
list.sort()
add = sum(list[0:3])
return add
#stats
def display_stats():
global pow, cun, per
pow = roll_3d6()
print "Power: ", pow
cun = roll_3d6()
print "Cunning: ", cun
per = roll_3d6()
print "Personality: ", per
# Check Random Encounter
def chk_rn():
x = random.randint(1, 6)
if x == 1:
rn_ec1()
# First Encounter (main program really)
def fi_en():
global pow, cun, per
print"""
It smells of damp vegetation, and the air is particularly thick. You can
hear some small animals in the distance. This was a nice place to sleep.
1. Stay close, find some cover, and wait for food to show up.
2. Explore the nearby marsh & find the nearest river, following it downstream.
3. Walk towards the large mysterious mountain in the distance.
"""
answer = int(raw_input(prompt))
if answer == 1:
cun_one = roll_3d6()
if cun_one <= cun - 2:
print"""
Time passes as eventually you capture some varmints. You feel slightly more
roguish.
"""
cun = cun + 1
chk_rn()
fi_en()
else:
print """
Time passes and a group of slavers marches into right where you are hiding in
the woods. They locate you, capture you, and haul you away for a lifetime of
servitude in the main city.
Goodbye %s
""" % name
elif answer == 2:
power = roll_3d6()
if power <= pow - 4:
print"""
You trudge through the marshes until you eventually reach a large river.
Downstream from the river is a large temple covered in vines, you walk towards
it. You feel more powerful."""
pow = pow + 2
chk_rn()
te_en()
else:
print """
The vegetation here wraps itself around your legs making it impossible to move.
You will most likely die here in the vegetation.
Goodbye %s.
""" % name
elif answer == 3:
cun_two = roll_3d6()
if cun_two <= cun:
print """
You make your way towards the mountain and you encounter a really large group of
devil dogs guarding the entrance to the mountain.
"""
chk_rn()
dd_en()
else:
print"You have gotten lost and ended up right where you started."
fi_en()
# Devil Dog Encounter
def dd_en():
global pow, cun, per
print"""
You have encountered a massive group of Devildogs.
1. Fight off the whole group, like a true hero
2. Try to sneak very quietly around them.
3. Attempt to tame them like domestic animals.
4. Accept the Devildog curse and walk through unmolested, sort of.
"""
answer = int(raw_input(prompt))
if answer == 1:
power = roll_3d6()
if power <= pow - 6:
print """
You are a God among men and have defeated all of the surrounding Devildogs.
Beyond the entrance to the mountain is a temple covered in vines. You
feel more powerful.
"""
power = power + 3
chk_rn()
te_en()
else:
print """
You are easily overwhelmed by the devildogs and you are continuously eaten
by devildogs for all eternity.
Goodbye %s.
""" % name
elif answer == 2:
sneak = roll_3d6()
if sneak <= cun - 4:
print """
You stealthily evade the Devildogs. Beyond the entrance to the mountain is a
temple covered in vines. You feel more roguish.
"""
cun = cun + 2
chk_rn()
te_en()
else:
print """
The devildogs pick up on your scent. You are easily overwhelmed by the
devildogs and you are continuously eaten by devildogs for all eternity.
Goodbye %s.
""" % name
elif answer == 3:
charm = roll_3d6()
if charm <= per - 4:
print """
The Devildogs are thrilled and have accepted you as their leader, they allow
you to pass and will sing your praises for all eternity. Beyond the entrance
to the mountain is a temple covered in vines. You feel more charming.
"""
per = per + 2
chk_rn()
te_en()
else:
print """
The Devildogs have no idea what you are trying to do.You are easily
overwhelmed by the devildogs and you are continuously eaten by devildogs
for all eternity.
Goodbye %s.
""" % name
elif answer == 4:
print"""
The Devildogs circle around you and start howling in unison. You feel your
life forces draining away as they howl their awful song. Beyond the entrance
to the mountain is a temple covered in vines.
"""
pow = pow - 3
cun = cun - 3
per = per - 3
chk_rn()
te_en()
else:
print """
You stumble as the Devildogs take notice. You are easily overwhelmed by the
devildogs and you are continuously eaten by devildogs for all eternity.
Goodbye %s.
""" % name
# Temple Encounter
def te_en():
global pow, cun, per
print """
You are now standing right in front of a large temple with many vines
covering its cobblestone exterior. An archway precedes a small and
peaceful garden with a main road leading to the temple.
Next to the archway is a small gargoyle that is moving and staring at you
with a friendly smile. It is now sundown and the area starts to gleam a reddish
glow. In the glow you can see faint white whips in the distance beyond the
archway. It smells like fresh produce. In your head you are instantly reminded
of a heartwarming song you remembered as a kid.
1. Walk through the archway normally towards the temple.
2. Run through the archway trying to get to the door as quickly as possible.
3. Have a conversation with the gargoyle staring at you.
"""
answer = int(raw_input(prompt))
if answer == 1:
power = roll_3d6()
if power <= pow - 5:
print"""
As you walk through you immediately feel what feels like hundreds of hands
groping at you pulling you into the ground. You stand your ground and make
it to the door. You enter the temple. You feel more powerful.
"""
pow = pow + 2
in_te()
else:
print """
As you walk through, you are taken off guard as hundreds of hands grope you and
pull you straight down to hell for the rest of eternity.
Goodbye %s.
""" % name
elif answer == 2:
run = roll_3d6()
if run <= cun - 6:
print """
You sprint through and notice nothing as you quickly arrive at and enter the
temple. You feel more roguish.
"""
cun = cun + 2
in_te()
else:
print """
You trip and fall as you are running. What feels like 100 hands grabs you and
pulls you straight down to hell for the rest of eternity.
Goodbye %s.""" % name
elif answer == 3:
charm = roll_3d6()
if charm <= per - 3:
print """
You ask the gargoyle where you are, and he cheerfully
tells you that you've arrived at the halls of destiny, and that you should
walk down the driveway. The sky returns to its normal color. You walk down
the passageway and enter the temple. You feel more charming.
"""
per = per + 1
in_te()
else:
print """
You ask the gargoyle where you are, right as the
expression changes on his face and tells you, 'Hell.' Right as he
says that 100 hands come up from the ground and pull you straight to hell.
Goodbye %s.
""" % name
elif answer == "sing" or "sing song" or "Sing" or "Sing Song":
print """
The gargoyle rejoices as you sing and exclaims he was
just thinking about that song as he saw you. He says you are allowed
to enter the temple of destiny. The sky turns back to its normal color. You
walk down the passageway and enter the temple. You feel charming.
"""
cun = cun + 2
in_te()
else:
print"""
You stumble as the gargoyle scowls you and screams an awful
noise. Immediately, 100 hands appear from the ground and drag you down to
hell as the gargoyle cackles above you.
Goodbye %s.
""" % name
# Inside The Temple
def in_te():
global pow, cun, per
print"""
Inside the temple, Cobblestone lines the walls. There is one large room
leading to another. It smells of mold, and you can hear both water dripping,
and gears shifting. In the middle of a room stands a large minotaur with his
head looking down carrying a massive axe.
1. Engage the minotaur in combat.
2. Sneak along the edges of the walls to the next room.
3. Attempt to speak the the minotaur.
"""
answer = int(raw_input(prompt))
if answer == 1:
fight = roll_3d6()
if fight <= pow - 6:
print """
You destroy the foul beast without taking injury. It screams as it dissolves
into the ground. Several torches light up and signal safe entry into the next
room. You feel more powerful.
"""
pow = pow + 2
you_win()
else:
print """
You find yourself unable to best to minotaur in combat and he decapitates you.
Goodbye %s""" % name
elif answer == 2:
sneak = roll_3d6()
if sneak <= cun - 5:
print """
You successfully sneak around the minotaur and enter the next room.
You feel more roguish.
"""
cun = cun + 2
you_win()
else:
print """
You step on a pressure plate and a blade emerges from the wall
decapitating you.
Goodbye %s
""" % name
elif answer == 3:
charm = roll_3d6()
if charm <= per - 5:
print """
You ask the minotaur what his purpose is, and he exclaims to welcome you to
your destiny. And allows you to pass. You feel more charming.
"""
per = per + 2
you_win()
else:
print"""
You ask the minotaur what his purpose is, and he exclaims to prevent you from
stealing the hero's destiny. He swings his axe and decapitates you.
Goodbye %s.
""" % name
else:
print"""
You stumble and trip right in front of the minotaur, who takes this opportunity
to decapitate you with his axe.
Goodbye %s
""" % name
exit
# You Win!
def you_win():
print """
You have entered a room covered in jewels & a large crown sits on a pedestal.
Behind the crown is a plaque that reads:
~CoNgRaTuLaTiOnS HeRo~
You have found the crown of destiny
This crown lays here to be worn
By the hero of this land
Who has proved himself capable
Of surviving much hardship, &
Having both a sharp mind & Spirit
Take the crown, and henceforth
Your rightful place as the ruler
Of Calgaria.
You pick up the crown and place it on your head. You are now the king of
Calgaria. Congratulations %s you beat the legend of doobieus!
""" % name
print"Your final stats were: \n", display_stats()
print "\nThanks for playing, goodbye!"
#random encounter 1
def rn_ec1():
global pow, cun, per
print """
You have randomly encountered a colony of large ants
They are about your size but have pincers the size of your arms.
Their clicking noises now envelop you...
1. Fight off the ants to the best of your ability.
2. Run away as quickly as possible.
3. Sing 'The Song of Insect Charm.'
"""
answer = int(raw_input(prompt))
if answer == 1:
fight = roll_3d6()
if fight <= pow - 4:
print """With an amazing display of strength, you defeat all
of your foes. You feel stronger after your victory."""
pow = pow + 2
else:
print """You are eaten alive by ants and die.
Goodbye %s.""" % name
elif answer == 2:
trick = roll_3d6()
if trick <= cun - 2:
print """You outrun the giant ants and have survived.
You feel a little bit more roguish"""
cun = cun + 1
else:
print """You fail to outrun the ants and are eaten alive.
Goodbye %s""" % name
elif answer == 3:
charm = roll_3d6()
if charm <= per - 2:
print """The giant ants thank you for your lovely rendition &
allow you to pass. You feel charming."""
per = per + 1
else:
print """The giant ants are horrified by your awful rendition of
their sacred anthem. They tear you apart mercilessly."
Goodbye %s.""" % name
else:
print """You stumble as the clicking gets closer and closer until
you are painfully eaten alive by ants.
Goodbye %s""" % name
######################## MAIN PROGRAM ###################################################
prompt = "> "
print "\n\t\tWelcome to LeGeNeD oF DoObIeUs..."
print "\n\t\tProgrammed using Python 2.7 by Ray Weiss"
name = raw_input("\nWhat is your name brave rogue? > ")
print "\nOk %s, lets roll up some character stats." % name
print "\nPress enter to roll 3D6 for each stat."
raw_input()
display_stats()
print "\nThese are your stats. They can be changed by things in game."
print "\nThese stats will have an effect on the outcomes that you choose."
print "\nYou will be presented with many choices, type in a number."
print "\nOr risk typing something different."
print "\nPress enter to start the game"
raw_input()
print"""You are %s, you are but a wandering rogue in the vast,
mysterious, and deadly land of Calgaria. Your goal is to survive.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You have just woken up in the woods, its really cold, and you are hungry.
""" % name
fi_en()
</code></pre>
|
[] |
[
{
"body": "<p>It's difficult to know what advice to give, since some of it is beyond what you've learnt so far (exercise 31?), but...</p>\n\n<p><strong>roll_3d6</strong> - there's no need for the sort or list. For the number of items you have, it could just be:</p>\n\n<pre><code>def roll_3d6():\n return random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)\n</code></pre>\n\n<p>or use a loop:</p>\n\n<pre><code>def roll_3d6():\n add = 0\n for _ in range(3):\n add += random.randint(1, 6) # add = add + random.randint(1, 6)\n return add\n</code></pre>\n\n<p>As a point to be aware of - you do <em>not</em> want to use existing function names as variable names - like <code>list</code>. Using them will cause you a lot of trouble.</p>\n\n<p><strong>display_stats</strong> - avoid the use of <code>global</code> if possible. You'll learn about classes, tuples, lists and dictionaries, all of which can be used and passed as parameters/returned as values. </p>\n\n<p>This should, btw, be split into two parts, <code>create_stats</code> and <code>display_stats</code>. At the end, you call <code>display_stats</code> which resets everything and doesn't display your current stats.</p>\n\n<p>In this case, since you seem to know about lists:</p>\n\n<pre><code>POWER = 0\nCUNNING = 1\nPERSONALITY = 2\n\ndef create_stats():\n power = roll_3d6()\n cun = roll_3d6()\n per = roll_3d6() \n stats = [ power, cunning, personality ]\n return stats\n\ndef display_stats( stats ):\n print \"Power: \", stats[POWER]\n print \"Cunning: \", stats[CUNNING]\n print \"Personality: \", stats[PERSONALITY]\n</code></pre>\n\n<p>called as:</p>\n\n<pre><code>stats = create_stats()\ndisplay_stats( stats )\n</code></pre>\n\n<p>This is then used as a parameter to all your functions.</p>\n\n<pre><code>def fi_en( stats ): # etc\n</code></pre>\n\n<p>and individual parts can be used:</p>\n\n<pre><code>stats[ POWER ] += 2 # stats[POWER] = stats[POWER] + 2\n</code></pre>\n\n<p><strong>chk_rn</strong> - don't abbreviate names, it becomes a lot harder to read (and reading it will become far important than writing it). <code>check_random_encounter</code> is just fine as a name.</p>\n\n<p><strong>fi_en</strong> - whenever you accept input from the user, always validate it. calling int(raw_input(..)) will cause an exception if the user enters text (or even just presses return). The best way in this instance is to test against '1', '2' etc or even have a function to do so.</p>\n\n<pre><code>def ask_question( question, allowed_answers ):\n # repeat forever until a valid answer is given\n while True: \n print question\n answer = raw_input( prompt ).lower() # test against lower case strings for simplicity\n if answer in allowed_answers:\n return answer\n</code></pre>\n\n<p><strong>te_en</strong> - <code>answer == \"sing\" or \"sing song\" or \"Sing\" or \"Sing Song\"</code> The expression doesn't work that way. It should read (with brackets for emphasis):</p>\n\n<pre><code>( answer == \"sing\" ) or ( answer == \"sing song\" ) or ( answer == \"Sing\" ) or ( answer == \"Sing Song\" )\n</code></pre>\n\n<p>Also, you have the wrong stat advance. You feel charming, but cunning increases, not personality :)</p>\n\n<p><strong>in_te</strong> - <code>exit</code> should be <code>exit()</code> - calling the function, not using the value. And it isn't even needed. Try also to avoid using the <code>from x import y</code> form. There are occasions when it's useful, but having to write <code>sys.exit()</code> on one occasion instead of <code>exit()</code> isn't one of them :)</p>\n\n<p><strong>you_win</strong> - <code>print(\"Your final stats were: \\n\", display_stats())</code>. <code>display_stats</code> doesn't return anything, so you'll get <code>None</code> written.</p>\n\n<pre><code>print(\"Your final stats were: \\n\")\ndisplay_stats()\n</code></pre>\n\n<p><strong>main</strong> - don't have significant code outside of a function, it's customary to put that (the main program bit) in a <code>main</code> function and guard it against being run when imported with, e.g.:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main_program()\n</code></pre>\n\n<p>It's not significant here, but in the future with larger projects, it will be.</p>\n\n<p>With regards to the whole structure of the program, I might suggest the following things which should be more or less straightforward:</p>\n\n<ol>\n<li><p>Define a series of global constants (variables) <code>DEAD</code>, <code>FIRST_ENCOUNTER</code>, <code>DEVILDOG_ENCOUNTER</code> etc.</p></li>\n<li><p>For each of your answer options, separate out the code into a separate function, which returns DEAD or the next encounter as appropriate. This will give you options to simplify the code a bit and make it more readable. You may end up with something like:</p>\n\n<pre><code>def first_encounter():\n answer = ask_question(\"...etc...\", ['1', '2', '3'] )\n status = DEAD\n if answer == '1':\n status = first_encounter_1()\n elif answer == '2': \n status = first_encounter_2()\n elif answer == '3':\n status = first_encounter_3()\n if status != DEAD:\n if chk_rn() == DEAD:\n status = DEAD\n if status == FIRST_ENCOUNTER:\n first_encounter()\n elif status == TEMPLE_ENCOUNTER:\n temple_encounter()\n elif status == DEVILDOG_ENCOUNTER:\n devildog_encounter()\n</code></pre></li>\n<li><p>After you've learnt about while loops, again rewrite your encounter functions, so that instead of calling the next encounter function directly, return the <code>status</code> and call the next encounter from the loop, e.g.</p>\n\n<pre><code>def first_encounter():\n answer = ask_question(\"...etc...\", ['1', '2', '3'] )\n status = DEAD\n if answer == '1':\n status = first_encounter_1()\n elif answer == '2': \n status = first_encounter_2()\n elif answer == '3':\n status = first_encounter_3()\n if status != DEAD:\n if chk_rn() == DEAD:\n status = DEAD\n return status\n\n....\nstatus = FIRST_ENCOUNTER\nwhile status != DEAD:\n if status == FIRST_ENCOUNTER:\n status = first_encounter()\n elif status == TEMPLE_ENCOUNTER:\n status = temple_encounter()\n elif status == DEVILDOG_ENCOUNTER:\n status = devildog_encounter()\n # etc\n</code></pre></li>\n<li><p>After you've learnt about classes, revisit again and see what new changes you can make!</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T15:38:59.683",
"Id": "26273",
"Score": "0",
"body": "This is really a wonderful answer, lots to mess with here but thats all the fun! Thanks so much @GlennRogers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T10:23:37.020",
"Id": "16146",
"ParentId": "16126",
"Score": "5"
}
},
{
"body": "<p>Glenn Rogers' answer is well-aimed at your level of expertise, so you should pay attention to his advice rather than mine, but I think you might be interested to peep ahead to see a more sophisticated approach to this kind of application.</p>\n\n<p>In your program (a multiple-choice adventure game), the set of operations is highly stereotyped. There are a small number of common operations:</p>\n\n<ol>\n<li>printing a paragraph of text;</li>\n<li>presenting a numbered sequence of choices and getting the player to choose one;</li>\n<li>rolling dice and comparing the total to a statistic;</li>\n</ol>\n\n<p>and so on. Coding up each of these operations every time makes your code repetitious, hard to follow, and hard to change (because the rules for, say, testing a statistic are distributed all over the code).</p>\n\n<p>In this kind of situation, one way to make the code easier to read and follow is to use a <a href=\"http://en.wikipedia.org/wiki/Domain-specific_language\" rel=\"nofollow\"><strong>domain-specific language</strong></a> to separate the implementation of the operations from their expression. (You'll sometimes see the phrase \"<a href=\"http://en.wikipedia.org/wiki/Language-oriented_programming\" rel=\"nofollow\">language-oriented programming</a>\" used for this approach.)</p>\n\n<p>Here's an example implementation of a domain-specific language for this kind of application:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>GWYDIONS_CASTLE = '''\n\nPAGE 1\n\nIt is only the autumn night that makes you shiver, you tell yourself, but you\nknow better.\n\nThe castle stands on the hill in the gathering dusk. Wrapped in your grey cloak\nagainst the cold, you crouch on the edge of the counterscarp. Eyes peer down\nfrom the battlements, but you need not fear discovery: they are only the empty\nsockets in the skulls of the adventurers who have come before you to harrow the\nfortress of the wizard Gwydion.\n\nSoon it will be dark enough to make your move.\n\nYou have boots.\n\nYou have a cloak.\n\nYou have a dagger.\n\nTo scale the wall, turn to page 27.\n\nTo swim the moat, turn to page 24.\n\n\nPAGE 2\n\nThe dagger makes no impression on the chain. \"Ah, you wish to free me,\" says\nthe monk. \"You have a good heart, but no blade forged of iron can cut a chain\nforged with magic.\"\n\nSuddenly he stands up. \"Only Gwidion's death can undo his magic. But if you\nwish to defeat him, take this.\" He selects a tattered scroll from the shelf\nabove the desk and hands it to you.\n\nDefeat Gwydion? You only meant to rob him. But you nod and take the scroll.\n\nYou have a tattered scroll.\n\nTo leave the monk and follow the stone passageway, turn to page 13.\n\n\nPAGE 3\n\nYou are in a long stone passageway.\n\nTo go through the doorway on the right, turn to page 33.\n\nTo follow the passageway, turn to page 13.\n\n\nPAGE 4\n\nYou push the door. It opens noiselessly on well-oiled hinges and you peer\nthrough the gap. What you see inside takes your breath away. Golden coins in\nheaps! Tapestries in silk and damask! Kingly crowns studded with polished\nstones. This is what you came for.\n\nTo fill your pockets and make a run for it, turn to page 34.\n\nTo try the other door instead, turn to page 10.\n\n\nPAGE 5\n\nTo tag onto the back of the troop, turn to page 6.\n\nTo stay hidden until they pass, and then try your key in the door of the keep,\nturn to page 40.\n\n\nPAGE 6\n\nYou follow the troop, imitating their shambolic walk as best you can. No one\nseems to notice your presence. The door to the keep swings open, squealing on\nits rusty hinges like a stuck pig, and you pass through one by one. The massive\ndoor swings shut behind you.\n\nIf you have a cloak, turn to page 36.\n\nTest your luck. If you succeed, turn to page 23.\n\nOtherwise, turn to page 21.\n\n\nPAGE 7\n\nThe courtyard is quiet in the moonlight, but you remain on your guard. Who\nknows what traps Gwydion has set for unwary intruders?\n\nTo approach the keep, turn to page 41.\n\n\nPAGE 8\n\nYour boots echo loudly on the tiles. Too loud. You freeze, but the sound of\nfootsteps does not stop. You turn to see an armoured knight step emerging from\nan alcove. Its visor is down, but somehow you doubt that there is a face behind\nit.\n\n suit of armour (the, its) SKILL 10 STAMINA 10\n\nIf you win, turn to page 30.\n\n\nPAGE 9\n\nIt looks as if the goblin dropped a key in the struggle. You pick it up.\n\nYou gained a key.\n\nTo leave the scullery by the door, turn to page 7.\n\n\nPAGE 10\n\nYou push the door. It opens noiselessly on well-oiled hinges and you peer\nthrough the gap. Inside is a study lined with tapestries, and at a desk sits a\ntall white-haired man, bent in concentration over a grimoire. It is the wizard\nGwydion. His staff rests at his side.\n\nIf you have a tattered scroll, turn to page 47.\n\nTo attack Gwydion, turn to page 45.\n\nTo try the other door instead, turn to page 4.\n\n\nPAGE 11\n\nYou leap through the window.\n\nTest your luck. If you succeed, turn to page 12.\n\nOtherwise, turn to page 32.\n\n\nPAGE 12\n\nIt is a long fall, but the moat is deep. You pull yourself out and slink away\nempty-handed into the night. Is that distant laughter you can hear? No\nmatter. You will be back.\n\n\nPAGE 13\n\nThe dark passageway enters a large hall lit by a candelabra. Suits of armour\nstand silently in alcoves. The floor is tiled in a black and white checkerboard\npattern, and at the far side a wide staircase ascends. Something about the room\nmakes you suspicious.\n\nTo cross the hall, stepping only on the white tiles, turn to page 20.\n\nTo cross the hall, stepping only on the black tiles, turn to page 20.\n\n\nPAGE 14\n\nYou dart into the room and snatch the staff from the wizard's side. He snaps\nawake, and makes a grab for it, but you draw back from his reach.\n\n\"Very good, {player.name}!\" he says. \"But with or without my staff, I am still\nthe wizard Gwydion!\"\n\nTo fight him, turn to page 29.\n\nTo run away, turn to page 25.\n\n\nPAGE 15\n\nTwo steps are all it takes to cover the distance, and then your dagger goes in\nbetween his cervical vertebrae. The monk barely make a sound as he collapses\nforward onto the desk, bleeding onto his half-copied page.\n\nYou search his cassock efficiently but find nothing. It is only then that you\nnotice the heavy iron chain from his leg to the desk. He was a prisoner here,\nnot an enemy.\n\nTo go back and follow the stone passageway, turn to page 13.\n\n\nPAGE 16\n\nYou place your foot on a loose cobble and it gives way. For a moment you hang\nfrom your fingertips, but with lightning speed you find a new foothold. Soon\nyou swing up through a machicolation and onto the parapet walk.\n\nTo quickly descend the stairs to the courtyard, turn to page 37.\n\n\nPAGE 17\n\nYou take a ladleful and sip. Pfaughh! This isn't soup, it's laundry! There are\nunderclothes boiling here... and not overly clean ones.\n\nA scraping from behind you makes you drop the ladle in alarm. Someone is\ncoming through the door.\n\nTo try to sneak out past the newcomer, turn to page 22.\n\nTo stand your ground, turn to page 26.\n\nTo hide, turn to page 49.\n\n\nPAGE 18\n\nYou cough. The monk turns his head. \"It's nearly done,\" he says, \"I'm writing\nas fast as I can. But with this light...\" He turns back to his work. It is only\nthen you notice the heavy iron chain linking his leg to the desk. He is a\nprisoner here!\n\nTo cut the chain with your dagger, turn to page 2.\n\nTo leave the monk to his fate and follow the stone passageway, turn to page 13.\n\n\nPAGE 19\n\nYou place your foot on a loose cobble and it gives way. For a moment you hang\nfrom your fingertips, cursing the mason. And then you are gone.\n\n\nPAGE 20\n\nIf you have boots, turn to page 8.\n\nOtherwise, turn to page 30.\n\n\nPAGE 21\n\nYou are still wet with water from your swim, and in the silence a drip echoes\nin the stone passageway. The three shambling figures turn to look at you. You\nwish that you had never seen the rotting flesh beneath their hoods.\n\n first zombie (the, its) SKILL 4 STAMINA 6\n\nThe second zombie is even more hideous than the first. It reaches for you with\nthe claws on its one good hand.\n\n second zombie (the, its) SKILL 5 STAMINA 6\n\nThe third zombie is more horrible than the first two put together. It glares\nat you with one eye dangling from its socket.\n\n third zombie (the, its) SKILL 6 STAMINA 6\n\nIf you win, turn to page 3.\n\n\nPAGE 22\n\nTest your luck. If you succeed, turn to page 42.\n\nOtherwise, turn to page 26.\n\n\nPAGE 23\n\nThe troop continues down a long stone passageway, but you scuttle through a\ndoorway on the right, glad to be rid of their unsettling company.\n\nTurn to page 33.\n\n\nPAGE 24\n\nYou wrap your boots in your cloak and slip silently into the water. There is a\nwater gate, barred with iron, but the iron is rusted and crumbling below the\nwaterline. You take a deep breath and squeeze through into a dark underwater\npassage.\n\nTest your stamina. If you succeed, turn to page 35.\n\nOtherwise, turn to page 46.\n\n\nPAGE 25\n\nClutching the wizard's staff, you run out onto the landing. Gwydion\nfollows. You run down the stairs. Gwydion follows. You run across the tiled\nfloor. Gwydion follows, his hobnailed boots ringing on the stone.\n\nA suit of armour steps down from an alcove and swings its sword at Gwydion. He\nshatters it with a blast of lightning, but a second suit of armour is at the\nwizard's back, swinging its sword. A third and a fourth step into the fray\nuntil you can no longer see the wizard. Caught in his own trap!\n\nTurn to page 50.\n\n\nPAGE 26\n\nThe newcomer is green-skinned and ugly as sin. He lunges at you with a\nstaff. You have no choice but to defend yourself.\n\n goblin (the, his) SKILL 7 STAMINA 6\n\nIf you win, turn to page 9.\n\n\nPAGE 27\n\nThe masonry has not been pointed in many years, and the stones are rough. You\nclimb swiftly and silently: an owl, perched in an arrow slit, is not disturbed\nas you pass. But the wall is high.\n\nTest your skill. If you succeed, turn to page 16.\n\nOtherwise, turn to page 19.\n\n\nPAGE 28\n\nYou flourish your dagger, but Gwydion taps you with his staff and you find\nyourself unable to move.\n\nTurn to page 44.\n\n\nPAGE 29\n\nGwydion raises his hands, lightning flickering from his fingers.\n\n Gwydion (-, his) SKILL 10 STAMINA 12\n\nIf you win, turn to page 50.\n\n\nPAGE 30\n\nYou cross the hall and ascend the stairs. On the landing there are two\ndoors. One has a stuffed owl on the lintel, the other a lizard in a jar.\n\nTo enter the door with the stuffed owl, turn to page 4.\n\nTo enter the door with the lizard, turn to page 10.\n\n\nPAGE 31\n\nThis page intentionally left blank.\n\n\nPAGE 32\n\nIt is a long fall, and the ground is hard.\n\n\nPAGE 33\n\nThis is a scriptorium, with shelves stacked haphazardly with scrolls and\ncodices. By the light of a candle, a tonsured man sits at a writing desk,\ncopying a manuscript. His back is turned to you and he does not appear to have\nheard him enter.\n\nTo slip back out again and follow the stone passageway, turn to page 13.\n\nTo kill the monk, turn to page 15.\n\nTo talk to the monk, turn to page 18.\n\n\nPAGE 34\n\nJust one of the crowns would set you up for life. But you close your fingers on\nit and it vanishes.\n\nYou hear a mocking laugh behind you, and whirl around to see the wizard Gwydion\nstanding there.\n\n\"Your head will make a fair adornment for my battlements, {player.name},\" he\nsays.\n\nIf you have a tattered scroll, turn to page 48.\n\nTo jump out of the window, turn to page 11.\n\nTo attack Gwydion, turn to page 28.\n\n\nPAGE 35\n\nYou feel your way along the passage in the dark. Nothing but cold stone. Your\nlungs are bursting: you must find a way out or drown. With a last desperate\nburst of energy you kick upwards and surface. Blessed air! You breathe it deep\ninto your lungs. You seem to have left your cloak and boots in the passage, but\nat least you are alive.\n\nYou lost your boots.\n\nYou lost your cloak.\n\nTo haul yourself out of the water and look around, turn to page 38.\n\n\nPAGE 36\n\nAre you scrutinized by unseen eyes as you pass the threshold? With your grey\ncloak pulled over your head, you cannot tell.\n\nYour luck went up by 1.\n\nTurn to page 23.\n\n\nPAGE 37\n\nThe courtyard is quiet in the moonlight, but you remain on your guard. Who\nknows what traps Gwydion has set for unwary intruders?\n\nTo enter a low stone building in a corner of the curtain wall, turn to page 38.\n\nTo approach the keep, turn to page 41.\n\n\nPAGE 38\n\nBy the flickering light of a fire, you can see that this is a scullery. Buckets\nof dirty dishes stand by the water's edge, and a giant cauldron bubbles over\nthe flame. There is a door in the west wall.\n\nTo drink from the cauldron, turn to page 17.\n\nTo leave the scullery by the door, turn to page 7.\n\n\nPAGE 39\n\nYou start to unroll the scroll, but Gwydion dashes it out of your hand with his\nstaff.\n\nTurn to page 28.\n\n\nPAGE 40\n\nThe unsettling shambolic figures disappear into the keep and the door swings\nshut behind them. You stay hidden for a quarter of an hour. Nothing moves. You\nstep silently across the drawbridge and approach the door.\n\nThe key grates in the lock but turns. You pull on the massive brass ring, and\nthe door opens, squealing on its rusty hinges like a stuck pig. You freeze, but\nno one seems to have heard: or maybe they are used to the noise. You step\nthrough and leave the door ajar.\n\nTurn to page 3.\n\n\nPAGE 41\n\nMassive blocks of well-fitted grey stone make up the walls of the keep: you can\nsee no way to scale the walls. Nor is there a moat with unguarded water gate:\njust a ditch filled with chevaux de frise.\n\nBut what's this? You crouch behind a pigsty as a troop of guards marches\ntowards the keep. Though maybe \"marches\" is the wrong word: the first one is\nlimping, the second has a hunched back, and the third drags his foot along the\nground.\n\nIf you have a key, turn to page 5.\n\nThis could be your only chance. To tag onto the back of the troop, turn to page\n6.\n\n\nPAGE 42\n\nYou flatten yourself against the wall beside the door, and hold your breath as\nthe newcomer enters. He is green-skinned, ugly as sin, and carrying a staff. He\napproaches the cauldron and gives it a stir, sniffing the fumes.\n\nTo sneak out while his back is turned, turn to page 7.\n\n\nPAGE 43\n\nQuietly, so as not to disturb the wizard, you unroll the scroll and whisper the\nwords. Gradually the wizard's head nods forward until his beard is on the desk\nand you can hear him snoring.\n\nTo run in and stab him, turn to page 45.\n\nTo steal his staff, turn to page 14.\n\n\nPAGE 44\n\nThe wizard studies your face as you stand there paralyzed. \"A most respectable\nvisage. I think it will look best on the western wall.\"\n\n\nPAGE 45\n\nTwo swift steps and you plunge your dagger into his back, only for it to\nshatter into pieces. Gwydion jumps up from the desk with staff in hand and taps\nyou with it. Suddenly you find yourself unable to move.\n\nTurn to page 44.\n\n\nPAGE 46\n\nYou feel your way along the passage in the dark. Nothing but cold stone as far\nas you can swim. Your lungs are bursting: you must turn back or drown. Back to\nthe water gate. Where is the gap? In panic you wrench at the bars, but it is\ntoo late....\n\n\nPAGE 47\n\nTo read your scroll, turn to page 43.\n\nTo attack Gwydion, turn to page 45.\n\nTo try the other door instead, turn to page 4.\n\n\nPAGE 48\n\nTo read your scroll, turn to page 39.\n\nTo jump out of the window, turn to page 11.\n\nTo attack Gwydion, turn to page 28.\n\n\nPAGE 49\n\nYou crouch down behind the cauldron and watch as a goblin enters the laundry\nroom. He is green-skinned, ugly as sin, and carrying a staff. He approaches the\ncauldron and gives it a stir, sniffing the fumes.\n\nYou leap up from your hiding place and push the goblin into the cauldron, where\nhe expires horribly in the boiling water and a tangle of dirty clothing.\n\nTurn to page 9.\n\n\nPAGE 50\n\nGwydion is dead. His staff and his books are in your hands. All you have to do\nnow is find his gold, subdue his minions, free his slaves, and get the treasure\nsafely away. It should be easy now...\n\n'''\n\nimport re\nimport random\nimport textwrap\n\nclass GameOver(Exception):\n pass\n\nclass Roll(object):\n \"\"\"\n The object `Roll(n, bonus = 0, k = 6)` represents a roll of `n`\n `k`-sided dice, plus `bonus`. When converted to a string it\n describes the roll in English.\n \"\"\"\n def __init__(self, n, bonus = 0, k = 6):\n self.roll = [random.randint(1, k) for _ in range(n)]\n self.bonus = bonus\n self.total = sum(self.roll) + self.bonus\n\n def __str__(self):\n if len(self.roll) == 1:\n s = '{}'.format(self.roll[0])\n elif len(self.roll) == 2:\n s = '{} and {}'.format(*self.roll)\n else:\n s = '{}, and {}'.format(', '.join(self.roll[:-1]), self.roll[-1])\n if self.bonus:\n s += ', plus {}'.format(self.bonus)\n if len(self.roll) > 1 or self.bonus:\n s += ', making {}'.format(self.total)\n return s\n\nclass Player(object):\n STATS = [('skill', 1, 6), ('stamina', 1, 6), ('luck', 1, 6)]\n\n def __init__(self, game):\n self.game = game\n self.name = self.game.input(\"What is your name? \")\n self.equipment = set()\n self.initial_stats = dict()\n self.w = lambda s: game.write(s, 4)\n\n def rollup(self):\n self.w(\"Welcome, {player.name}. Let's roll up your character.\")\n for stat, dice, bonus in self.STATS:\n r = Roll(dice, bonus)\n self.initial_stats[stat] = r.total\n setattr(self, stat, r.total)\n self.w(\"{}: you rolled {}.\".format(stat.capitalize(), r))\n\n def test_stat(self, stat):\n w = self.w\n value = getattr(self, stat)\n w(\"Testing your {} ({}).\".format(stat, value))\n r = Roll(2)\n if r.total > value:\n w(\"You rolled {}. You failed the test.\".format(r))\n return False\n elif r.total == value:\n w(\"You rolled {}. You just made it.\".format(r))\n else:\n w(\"You rolled {}. You passed the test.\".format(r))\n if stat == 'luck':\n self.adjust_stat(stat, -1)\n return True\n\n def adjust_stat(self, stat, change, report = True):\n old_value = getattr(self, stat)\n new_value = max(0, min(self.initial_stats[stat], old_value + change))\n change = new_value - old_value\n setattr(self, stat, new_value)\n if report and change != 0:\n self.w(\"Your {} just went {} by {}. It is now {}.\"\n .format(stat, 'down' if change < 0 else 'up',\n abs(change), new_value))\n\nclass Paragraph(object):\n \"\"\"\n `Paragraph(game, **kwargs)` represents a paragraph of instructions\n on a page. Call it to execute the instructions. The class property\n `re` is a regular expression matching all paragraphs of this\n type. The `kwargs` dictionary passed to the constructor must\n contain all the named groups in `re`.\n \"\"\"\n\n def __init__(self, game, **kwargs):\n self.game = game\n self.w = lambda s: self.game.write(s, 4)\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n\n group_re = re.compile(r'\\(?P<(\\w+)>')\n\n @classmethod\n def group(cls):\n \"Return the name of the first named group in the `re` property.\"\n return cls.group_re.search(cls.re).group(1)\n\nclass Fight(Paragraph):\n re = (r'(?P<monster_name>\\S.*\\S) \\((?P<monster_article>the|an?|-),'\n r' (?P<monster_pronoun>their|his|her|its)\\)'\n r' +SKILL +(?P<monster_skill>\\d+) +STAMINA +(?P<monster_stamina>\\d+)')\n\n def __call__(self):\n w = self.w\n player = self.game.player\n name = self.monster_name\n article = self.monster_article\n if self.monster_article == '-':\n fullname = name\n else:\n fullname = '{} {}'.format(self.monster_article, name)\n pronoun = self.monster_pronoun\n skill = int(self.monster_skill)\n stamina = int(self.monster_stamina)\n w('{0.name}: SKILL {0.skill} STAMINA {0.stamina}'.format(player))\n w('{}: SKILL {} STAMINA {}'.format(name.capitalize(), skill, stamina))\n while True:\n player_roll = Roll(2, player.skill)\n w(\"You rolled {}.\".format(player_roll))\n monster_roll = Roll(2, skill)\n w(\"{} rolled {}.\".format(fullname.capitalize(), monster_roll))\n if monster_roll.total == player_roll.total:\n w(\"You skirmish without damage on either side.\")\n continue\n luck_adjustment = 0\n if self.game.input(\"Test your luck? \").lower() in ('y', 'yes'):\n luck_adjustment = 1 if player.test_stat('luck') else -1\n if monster_roll.total > player_roll.total:\n player.adjust_stat('stamina', -2 + luck_adjustment, False)\n w(\"{} hits you! Your stamina is now {}.\"\n .format(fullname.capitalize(), player.stamina))\n if player.stamina <= 0:\n w(\"You die.\")\n raise GameOver()\n else:\n stamina = max(0, stamina - (2 ** (luck_adjustment + 1)))\n w(\"You hit {}! {} stamina is now {}.\"\n .format(fullname, pronoun.capitalize(), stamina))\n if stamina <= 0:\n w(\"You killed {}.\".format(fullname))\n return\n\nclass NextPage(Paragraph):\n re = r'(?:If you win, t|Otherwise, t|T)urn to page (?P<next_page>\\S+)\\.'\n\n def __call__(self):\n return self.next_page\n\nclass TestEquipment(Paragraph):\n re = (r'If you have(?: (?:an?|your|the|some))? (?P<equip_test>\\S.*\\S),'\n r' turn to page (?P<equip_page>\\S+)\\.')\n\n def __call__(self):\n if self.equip_test in self.game.player.equipment:\n return self.equip_page\n\nclass TestStat(Paragraph):\n re = (r'Test your (?P<test_stat>\\S+)\\. If you succeed,'\n r' turn to page (?P<test_page>\\S+)\\.')\n\n def __call__(self):\n if self.game.player.test_stat(self.test_stat):\n return self.test_page\n\nclass ChangeStat(Paragraph):\n re = (r'Your (?P<stat_change>\\S+) went (?P<stat_dir>up|down) by'\n r' (?P<stat_amount>\\d+)\\.')\n\n def __call__(self):\n amount = int(self.stat_amount) * (-1 if self.stat_dir == 'down' else 1)\n self.game.player.adjust_stat(self.stat_change, amount)\n\nclass GainEquipment(Paragraph):\n re = (r'You (?:gained|have)(?: (?:an?|your|the|some))?'\n r' (?P<gain_equipment>\\S.*\\S)\\.')\n\n def __call__(self):\n self.game.player.equipment.add(self.gain_equipment)\n\nclass LoseEquipment(Paragraph):\n re = r'You lost(?: (?:an?|your|the|some))? (?P<lose_equipment>\\S.*\\S)\\.'\n\n def __call__(self):\n self.game.player.equipment.remove(self.lose_equipment)\n\nclass Choice(Paragraph):\n re = r'(?P<choice>\\S.*\\S), turn to page (?P<choice_page>\\S+)\\.'\n\n def __call__(self):\n n_choices = len(self.choices)\n if n_choices == 1:\n self.w(\"{}, press return.\".format(self.choices[0]['choice']))\n else:\n for i, c in enumerate(self.choices):\n self.w(\"{}, choose {}.\".format(c['choice'], i + 1))\n prompt = \"? \"\n while True:\n inp = self.game.input(prompt)\n if n_choices == 1:\n return self.choices[0]['choice_page']\n try:\n choice = int(inp)\n if 1 <= choice and choice <= n_choices:\n return self.choices[choice - 1]['choice_page']\n except ValueError:\n pass\n prompt = \"Please enter a choice from 1 to {}> \".format(n_choices)\n\nclass Description(Paragraph):\n re = r'(?P<description>\\S.*\\S)'\n\n def __call__(self):\n self.game.write(self.description)\n\nclass Page(object):\n def __init__(self, game):\n self.game = game\n self.paras = []\n self.choice = None\n\n def add(self, cls, **kwargs):\n if cls == Choice:\n if not self.choice:\n self.choice = Choice(self.game, choices = [])\n self.paras.append(self.choice)\n self.choice.choices.append(kwargs)\n else:\n self.paras.append(cls(self.game, **kwargs))\n\n def visit(self):\n for para in self.paras:\n page = para()\n if page:\n return page\n raise GameOver()\n\nclass Game(object):\n width = 72\n para_re = re.compile(\n r'^(?:PAGE (?P<page>\\S+)|{})$'\n .format('|'.join(cls.re for cls in Paragraph.__subclasses__())))\n\n def __init__(self, text):\n self.pages = dict()\n page = None\n for para in re.split(r'\\n(?:[ \\t]*\\n)+', text.strip()):\n para = textwrap.dedent(para).strip().replace('\\n', ' ')\n m = self.para_re.match(para).groupdict()\n if m['page']:\n if page is None: self.initial_page = m['page']\n page = self.pages[m['page']] = Page(self)\n continue\n for cls in Paragraph.__subclasses__():\n if m[cls.group()]:\n page.add(cls, **m)\n break\n\n def input(self, prompt):\n answer = raw_input(prompt)\n print('')\n if answer.lower() in ('q', 'quit'):\n raise GameOver()\n return answer\n\n def write(self, para, left_margin = 0):\n indent = ' ' * left_margin\n for line in textwrap.wrap(para.format(player = self.player),\n self.width, initial_indent = indent,\n subsequent_indent = indent):\n print(line)\n print('')\n\n def centre(self, text):\n self.write(text, (self.width - len(text)) // 2)\n\n def play(self):\n self.player = Player(self)\n self.player.rollup()\n self.centre('*')\n page = self.initial_page\n try:\n while True:\n page = self.pages[page].visit()\n except GameOver:\n pass\n\nif __name__ == '__main__':\n Game(GWYDIONS_CASTLE).play()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T15:39:43.770",
"Id": "26403",
"Score": "0",
"body": "Just managed to squeeze that into the 30,000-character limit!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T14:55:16.727",
"Id": "16228",
"ParentId": "16126",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "16146",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T21:21:14.380",
"Id": "16126",
"Score": "8",
"Tags": [
"python"
],
"Title": "LPTHW extra credit game"
}
|
16126
|
<p>I have the following Ruby code in an RSpec file:</p>
<pre><code> describe "order" do
before do
LIST_LENGTH ||= 10
@skills = FactoryGirl.create_list(:skill, LIST_LENGTH)
@developer = FactoryGirl.create(:user)
@requests = FactoryGirl.create_list(:request, LIST_LENGTH)
LIST_LENGTH.times { |i| @requests[i].skills = @skills[0..i] }
end
describe "#order_by_interestingness_for" do
it "orders by interestingness" do
@developer.add_interested_skills(@skills)
Request.all.shuffle.map {
|r| r.interestingness_for(@developer)
}.should_not be_in_order
Request.order_by_interestingness_for(@developer).map {
|r| r.interestingness_for(@developer)
}.should be_in_order
end
end
describe "#order_by_qualifiedness_for" do
it "orders by interestingness" do
@developer.add_proficient_skills(@skills)
Request.all.shuffle.map {
|r| r.qualifiedness_for(@developer)
}.should_not be_in_order
Request.order(:interestingness, :developer => @developer).map {
|r| r.qualifiedness_for(@developer)
}.should be_in_order
end
end
end
</code></pre>
<p>Obviously, this is not very DRY. I don't really know how to make it more DRY, though, since the the unique parts are so deeply ingrained in the code. I'm guessing I have a deeper design problem. I'm not really sure, though. Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-13T08:49:47.340",
"Id": "26826",
"Score": "2",
"body": "I'm unsure of what you're accomplishing with the first repeated bit; you call `Request.all.shuffle`, so yes, the resulting list should not be in order. Ruby's code has been tested, so no reason for you to do it. Moreover, `shuffle` is random, so the shuffled list may in fact be in order, and your test will randomly fail. But fail or pass, what does it prove exactly?"
}
] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>There's no need for the negative assertion. You're testing Ruby more than you're testing your own code and in the end, we don't actually care. It only matters that our attempt to order the results behaves as expected. Assuming they're un-ordered otherwise (or at least order isn't guaranteed).</li>\n<li>Favor RSpec's 'let' over instance variables and constants in your tests.</li>\n<li>RSpec's 'should' syntax will be deprecated in the next release. Favor using the new 'expect' syntax instead.</li>\n<li>Use string literals when you can.</li>\n<li>Use a shared example to DRY up your tests a bit.</li>\n<li>Modify the underlying implementation and the public API in your code for better symmetry between ordering by 'interestingness' and 'qualifiedness'. I suspect there's some code duplication in there given the current API that could also be eliminated.</li>\n</ul>\n\n<p>Do all that, and you could end up with a test that looks something like this:</p>\n\n<pre><code>shared_examples_for 'a ordered request' do |order_type, dev|\n it \"orders by #{order_type}\" do\n result = Request.call(:order, { order_type, :developer => dev })\n result.map! { |r| r.send(\"#{order_type}_for\", dev) }\n expect(result).to be_in_order\n end\nend\n\ndescribe Request do\n let(:list_length) { 10 }\n let(:skills) { FactoryGirl.create_list(:skill, list_length) }\n let(:developer) { FactoryGirl.create(:user) }\n let(:requests) { FactoryGirl.create_list(:request, list_length) }\n\n before { list_length.times { |i| requests[i].skills = skills[0..i] } }\n\n describe '#order' do\n context 'when ordering by interestingness'\n before { developer.add_interested_skills(skills) }\n it_behaves_like 'a ordered request', 'interestingness', developer\n do\n\n context 'when ordering by qualifiedness' do\n before { developer.add_proficient_skills(skills) }\n it_behaves_like 'a ordered request', 'qualifiedness', developer\n end\n end\nend\n</code></pre>\n\n<p>I'd also recommend checking out <a href=\"http://betterspecs.org/\" rel=\"nofollow\">this site</a> which is a pretty good, but still growing style guide for writing behavior tests in RSpec.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T23:50:40.307",
"Id": "30055",
"ParentId": "16127",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T21:26:06.293",
"Id": "16127",
"Score": "3",
"Tags": [
"ruby",
"rspec"
],
"Title": "How might I make this code more DRY?"
}
|
16127
|
<p>This method receives an array of data and does some stuff in a database. I need to get some reviews on it if possible.</p>
<pre><code>public function doSomeStuff($arr = array())
{
$id = $arr['Employee']['id'];
$name = $arr['Employee']['name'];
$status = $arr['Employee']['status'] == 'Disabled' ? 0 : 1;
$user_id = $arr['Employee']['user_id'];
$query = "update `mytable` set `status` = $status, `name`=$name WHERE `user_id` = ?";
self::_runthis($query, array($user_id));
}
</code></pre>
<p>I am looking to see if this is fool-proof for the data it will receive and will process it.</p>
|
[] |
[
{
"body": "<ul>\n<li>Instead of accessing the employee key every time, just pass in the array rooted at the Employee key</li>\n<li>What happens if all of the array indexes are not set? You should either check for that or use an object on which you know they all exist\n<ul>\n<li>Important mostly for data integrity (what if you create an Employee array somewhere and forget a status or something?)</li>\n<li>But also accessing non-set array keys issues a notice</li>\n</ul></li>\n<li>I suspect there's something wrong with your class design as a whole. In particular, the same class should probably not have a method to update an employee and a method to run a query (you don't happen to have something extending some vague DB class do you...?)</li>\n<li>Why is <code>name</code> not a place holder like the user_id?</li>\n<li>Use real names when posting code here -- doSomeStuff is very vague, and that hampers our ability to review</li>\n<li>A text status should probably not be being passed into this since it seems like you're dealing with a low level record here</li>\n<li>Don't quote entity names unless you need to. It breaks compatibility across SQL-dialects for no reason</li>\n<li>What if <code>$name</code> has spaces? What if it has a <code>'</code> in it? Look into SQL injection and prepared statements. (They're not just about security. There also about correctness. In it's current form, your code has a very major bug.)</li>\n<li>A default value for the parameter shouldn't be provided. Would you want someone to call <code>$obj->doSomeStuff();</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T05:03:58.227",
"Id": "16133",
"ParentId": "16132",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "16133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T04:54:50.437",
"Id": "16132",
"Score": "3",
"Tags": [
"php",
"php5"
],
"Title": "Receive array of data and access employee info fields"
}
|
16132
|
<p>Below is my implementation of a stack in <code>C</code>. Is it correct? And/or is there anything that I should fix to make it better in any way?</p>
<p><strong>stack.h</strong></p>
<pre><code>#ifndef STACK_H
#define STACK_H
#define EMPTY_STACK -1
typedef struct stack
{
char ch;
struct stack* prev;
} Stack;
extern Stack* init_stack(void);
extern char pop(Stack*);
extern void push(Stack*, char);
#endif
</code></pre>
<p><strong>stack.c</strong></p>
<pre><code>#include "stack.h"
#include "stdlib.h"
Stack* init_stack()
{
Stack* ret = (struct stack*)malloc(sizeof(struct stack));
ret->prev = NULL;
return ret;
}
char pop (Stack* stck)
{
char ret;
if (stck->prev)
{
ret = stck->ch;
Stack* prv = stck->prev;
stck->prev = prv->prev;
stck->ch = prv->ch;
free(prv);
return ret;
}
else
return EMPTY_STACK;
}
void push (Stack* stck, char ch)
{
Stack* new_nd = (struct stack*)malloc(sizeof(struct stack));
new_nd->prev = stck->prev;
new_nd->ch = stck->ch;
stck->prev = new_nd;
stck->ch = ch;
}
</code></pre>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T23:04:54.283",
"Id": "26325",
"Score": "0",
"body": "Too lazy to retype a tailored response, but some of this might be useful: http://codereview.stackexchange.com/questions/15819/dynamic-array-written-in-c/15823#15823"
}
] |
[
{
"body": "<p>I would advise you not implementing stacks with a linked list because for each <code>char</code> of info you consume <code>2 * sizeof(void*)</code> because of memory alignment in your struct. </p>\n\n<p>Because of this you won't be able to handle a big amount of data.</p>\n\n<p>What happens if you <code>push</code> EMPTY_STACK ? Your pop will return a false EMPTY_STACK when going through the if. Isn't there a better way to handle this ?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T07:29:14.420",
"Id": "16137",
"ParentId": "16134",
"Score": "6"
}
},
{
"body": "<p>Because your init_struct returns a struct that has no data, I think you need to set the data value:</p>\n\n<pre><code>ret->ch = EMPTY_STACK;\n</code></pre>\n\n<p>push() should then be modified to see if the char is currently EMPTY_STACK and if so, that should be updated, with no new struct allocated.</p>\n\n<pre><code>void push (Stack* stck, char ch)\n{\n if ( stck->ch == EMPTY_STACK )\n {\n stck->ch = ch;\n return;\n } \n</code></pre>\n\n<p>pop() should also deal with a struct that has no data:</p>\n\n<pre><code>char pop (Stack* stck)\n{\n char ret = stck->ch;\n if (stck->prev)\n {\n Stack* prv = stck->prev;\n stck->prev = prv->prev;\n stck->ch = prv->ch;\n free(prv);\n }\n else\n /* set the stack to empty */\n stck->ch = EMPTY_STACK;\n return ret;\n}\n</code></pre>\n\n<p>You might want to add a check for a NULL pointer passing in to push() and pop() as well. </p>\n\n<p>I think the easiest way to do a stack is to have a struct that contains a pointer to your data, which gets the output of malloc() from stack_init() and realloc(), if necessary from push(). You also keep an int in the struct that keeps track of the current size of the stack, and probably the current allocated size.</p>\n\n<pre><code>struct stack {\n char *data;\n int items;\n int allocated_size;\n}\n</code></pre>\n\n<p>Alternatively, there can be two structs. One for the base of the stack, and another to hold the data of the stack.</p>\n\n<pre><code>struct stack_node {\n char ch;\n struct stack_node* prev;\n}\n\nstruct stack {\n struct stack_node* top;\n int size;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T09:32:25.503",
"Id": "16144",
"ParentId": "16134",
"Score": "3"
}
},
{
"body": "<pre><code>#define EMPTY_STACK -1\n</code></pre>\n\n<p>This is weird. Maybe instead of returning a magic value, your pop function should have a different interface. For example, maybe your pop function has an output parameter (pointer) which receives the popped value, and returns a boolean indicating whether or not a value was popped.</p>\n\n<pre><code>Stack* ret = (struct stack*)malloc(sizeof(struct stack));\n</code></pre>\n\n<p>You are speaking C with a C++ accent. You do not need to cast from <code>void *</code> to <code>struct stack*</code>. Leave out the cast.</p>\n\n<pre><code>Stack* ret = (struct stack*)malloc(sizeof(struct stack));\nret->prev = NULL;\n</code></pre>\n\n<p><code>malloc</code> can return <code>NULL</code>. In this case the next line will dereference a <code>NULL</code> pointer and crash. You should check for errors, then return some kind of failure status to the caller, which the caller should also react to.</p>\n\n<p>You also have a <code>init_stack</code> which does allocations but no corresponding <code>free_stack</code> which frees it.</p>\n\n<p>Come to think of it... Does <code>init_stack</code> really need to allocate? Maybe it should take a caller-allocated buffer. For example an interface like:</p>\n\n<pre><code>struct stack stack;\n\ninit_stack(&stack);\n\npush(&stack, 1); // XXX - there should be a way to check for errors here.\n</code></pre>\n\n<p>This also brings to mind... Why a vague name like <code>push</code>? C does not have namespaces and this is a name that could clash with others. Maybe it should be <code>stack_push</code>. Also more consistent with some of your other function names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T06:14:31.573",
"Id": "16217",
"ParentId": "16134",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T05:47:56.730",
"Id": "16134",
"Score": "6",
"Tags": [
"c",
"stack"
],
"Title": "implementation of a stack in C"
}
|
16134
|
<p>I have this code that basically reads the DOM and sends the values to the server. I am looking for any possible flaws that I may have in this JavaScript code and any advice to make it better and bug-free!</p>
<pre><code>$(document).ready(function () {
$('.editButton').click(function () {
var postData = {};
var cData = {};
cData.Balance = $(this).parent().children('.balance').text().replace("$", "");
cData.desiredStatus = $(this).parent().children('.status').text() == "Disbled" ? "enable" : "disable";
$('#currentBalance').html($(this).parent().children('.balance').text());
$('#currentStatus').html($(this).parent().children('.status').text());
$('#desiredStatus').html(cData);
//set post view
postData.code = $(this).parent().children('.code').text();
postData.giftcardaccount_id = $(this).parent().children('.giftcardaccount_id').text();
$("#dialog").dialog({
title:"test box",
modal:true,
width:700,
buttons:{
'Confirm':function () {
postData.status = $('#currentStatus').html();
var balanceInqury = parseFloat($('#desiredBlance').val());
postData.balance = (balanceInqury == 'NaN') ? cData.Balance : balanceInqury;
$.ajax({
url:'/url/to/postto',
type:'POST',
data:{
postData:postData
},
success:function (data) {
console.log(data);
$("#dialog").dialog("close");
},
error:function () {
}
});
},
Cancel:function () {
$(this).dialog("close");
}
}
});//dialog
});
$('#changeStatus').click(function () {
var c = $('#currentStatus').html() == 'Disabled' ? 'Enabled' : 'Disabled';
var d = $('#desiredStatus').html() == 'disable' ? 'enable' : 'disable';
$('#currentStatus').html(c);
$('#desiredStatus').html(d);
});
});
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>You're creating a <em>lot</em> of jQuery objects in there. It would be much more efficient to just create them once. For example:</p>\n\n<pre><code>var postData = {},\n cData = {},\n $this = $(this),\n $parent = $this.parent(),\n $balance = $parent.children(\".balance\");\n</code></pre></li>\n</ul>\n\n<p>As a general rule, I try to avoid calling any method on the same object more than once. For any methods you need to call repeatedly, just call it once and store the result.</p>\n\n<ul>\n<li><p>The following line seems to be incorrect. You're passing an object to the <code>.html()</code> method (which it <a href=\"http://api.jquery.com/html/#html2\" rel=\"nofollow\">doesn't accept</a>):</p>\n\n<pre><code>$('#desiredStatus').html(cData);\n\n//Did you mean to do this instead?\n$('#desiredStatus').html(cData.desiredStatus);\n</code></pre></li>\n<li><p>You are creating a new modal dialog every time a <code>.editButton</code> element is clicked. You could move the creation of the dialog outside of the event handler and just call <code>$(\"#dialog\").dialog(\"open\")</code> when you want it to appear.</p></li>\n<li><p>The comparison <code>balanceInqury == 'NaN'</code> will <em>never</em> be <code>true</code>. JavaScript is funny like that, <code>NaN !== NaN</code>. There is a built-in <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/isNaN\" rel=\"nofollow\"><code>isNaN</code> function</a> you can use though:</p>\n\n<pre><code>postData.balance = isNaN(balanceInqury) ? cData.Balance : balanceInqury;\n</code></pre></li>\n<li><p>For shorter code you could replace your call to <code>$.ajax</code> with a call to the shorthand <code>$.post</code> method. If you'd rather not do that, you can at least remove the <code>error</code> property from the options object, since it doesn't do anything in your case:</p>\n\n<pre><code>$.post('/url/to/postto', { postData: postData}, function (data) {\n //You make another unnecessary jQuery object in here. Cache the #dialog object!\n});\n</code></pre></li>\n<li><p>Finally, you could change the code in the <code>#changeStatus</code> click event handler by passing a function to the <code>.html</code> method, which in my opinion is a bit neater:</p>\n\n<pre><code>$('#currentStatus').html(function () {\n return $(this).html() === \"Disabled\" ? \"Enabled\" : \"Disabled\"\n});\n$('#desiredStatus').html(function () {\n return $(this).html() === \"disable\" ? \"enable\" : \"disable\";\n});\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:02:55.940",
"Id": "26276",
"Score": "0",
"body": "I am not sure what do you mean by creating the dialog box before click...how would I get the values in which are not there until the button is clicked. thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:29:49.233",
"Id": "26279",
"Score": "0",
"body": "@Autolycus - You could use the [`.option()`](http://jqueryui.com/demos/dialog/#method-option) method to set the buttons in the event handler. Not sure if it would be any quicker or not... you can run benchmarks at http://jsperf.com."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T07:32:20.923",
"Id": "16138",
"ParentId": "16135",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T05:58:47.317",
"Id": "16135",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Read DOM and send values to server"
}
|
16135
|
<p>I'm a bit novice/moderate at JS. To my surprise I managed to put this together and it <em>does</em> work for what I intended. </p>
<p>The objective is to convert an object into a format that is more conducive to being used with a treegrid. I'm using the underscore library to grab object keys at various points.</p>
<p>I just wanted to know if maybe there's a better or perhaps more performant way of looping through these deeply nested objects that I may be overlooking. Something that's capable of handling hundreds, or even a thousand, of these nodes without potentially locking up a browser? </p>
<p>I found a hint about storing the length variables separately in a similar question that displayed looping through things in this manner, I just wanted to know if there may be any other tips?</p>
<p><a href="http://jsbin.com/uwudaw/3/edit" rel="nofollow noreferrer">JSBin</a></p>
<pre><code>var data_source = {"sprint":{"children":{"country":{"us":{"clicks":26}},"device":{"iphone":{"clicks":26}},"isp":{"comcast cable":{"clicks":26}},"os":{"ios":{"clicks":15},"android":{"clicks":10}},"referer":{"unknown":{"clicks":26}}},"clicks":26},"verizon":{"children":{"country":{"us":{"clicks":10,"conversions":5,"earned":0.5,"spent":0.2}},"device":{"galaxy s":{"clicks":1}},"isp":{"comcast cable":{"clicks":1}},"os":{"android":{"clicks":1}},"referer":{"unknown":{"clicks":1}}},"clicks":1,"conversions":1}};
var object = [];
function convert(data){
var keys = _.keys(data);
var keyslength = keys.length;
for (var i = 0; i < keyslength; i++){
var me = data[keys[i]];
var rootleaf = buildLeaf(me);
rootleaf.name = keys[i];
rootleaf.children = [];
var childkeys = _.keys(me.children);
var childkeyslength = childkeys.length;
for (var i2 = 0; i2 < childkeyslength; i2++){
var childme = me.children[childkeys[i2]];
var childleaf = {};
childleaf.name = childkeys[i2];
childleaf.children = [];
var grandchildkeys = _.keys(childme);
var grandchildkeyslength = grandchildkeys.length;
for (var i3 = 0; i3 < grandchildkeyslength; i3++){
var grandchildme = childme[grandchildkeys[i3]];
var grandchildleaf = buildLeaf(grandchildme);
grandchildleaf.name = grandchildkeys[i3];
childleaf.children.push(grandchildleaf);
}
rootleaf.children.push(childleaf);
}
object.push(rootleaf);
}
}
convert(data_source);
console.log(object);
function buildLeaf(node){
var tempnode = {};
var clicks = ((node.clicks) ? node.clicks : 0);
var conversions = ((node.conversions) ? node.conversions : 0);
var earned = ((node.earned) ? node.earned : 0);
var spent = ((node.spent) ? node.spent : 0);
tempnode.clicks = clicks;
tempnode.conversions = conversions;
tempnode.earned = '$' + earned.toFixed(2);
tempnode.spent = '$' + spent.toFixed(2);
tempnode.conversion_rate = conversionRate(conversions,clicks);
tempnode.net_earned = netEarned(earned,spent);
tempnode.epc = epc(clicks,earned,spent);
tempnode.roi = roi(earned,spent);
return tempnode;
}
// calculation functions
function conversionRate(cv, cl) {
if (cl === 0) return '0%';
return ((cv/cl)*100).toFixed(1) + '%';
}
function epc(cl, e, s) {
if (cl === 0 || e === 0) return '$0.000';
return '$' + ((e - (cl * s)) / cl).toFixed(3);
}
function netEarned(e, s) {
if (e === 0) return '$0.00';
return '$' + (e - s).toFixed(2);
}
function roi(e, s) {
if (e === 0) return '0%';
return (((e - s) / s) * 100).toFixed(0) + '%';
}
</code></pre>
|
[] |
[
{
"body": "<p>I believe this does the same as yours, except it uses <code>buildLeaf</code> on each step (your function skips it in the \"middle\" loop, and just makes an empty object).</p>\n\n<pre><code>// Recursive convertion function\nfunction convert(obj) {\n var item, leaf, key, leaves = [];\n for( key in obj ) {\n if( !obj.hasOwnProperty(key) ) continue;\n item = obj[key];\n leaf = buildLeaf(key, item)\n leaves.push(leaf);\n if( typeof item.children === 'object' ) {\n leaf.children = convert(item.children);\n }\n }\n return leaves;\n}\n\n// I also refactored buildLeaf slightly to accept both\n// name and content, and to make use of JavaScript's\n// `||`-style fallbacks\n\nfunction buildLeaf(name, node) {\n var leaf = { name: name, children: [] },\n clicks = node.clicks || 0,\n conversions = node.conversions || 0,\n earned = node.earned || 0,\n spent = node.spent || 0;\n\n leaf.clicks = clicks;\n leaf.conversions = conversions;\n leaf.earned = '$' + earned.toFixed(2);\n leaf.spent = '$' + spent.toFixed(2);\n leaf.conversion_rate = conversionRate(conversions,clicks);\n leaf.net_earned = netEarned(earned,spent);\n leaf.epc = epc(clicks,earned,spent);\n leaf.roi = roi(earned,spent);\n\n return leaf;\n}\n\n// In the calculation functions, I made the value checking\n// less strict. Generally, strong checking is encouraged,\n// but in this case other useless values would slip through,\n// when only strongly checking for zero (since that allows\n// `false`, empty strings, etc. to pass through).\n\nfunction conversionRate(cv, cl) {\n if( !cl ) return '0%';\n return ((cv/cl)*100).toFixed(1) + '%';\n}\n\nfunction epc(cl, e, s) {\n if( !cl || !e ) return '$0.000';\n return '$' + ((e - (cl * s)) / cl).toFixed(3);\n}\n\nfunction netEarned(e, s) {\n if( !e ) return '$0.00';\n return '$' + (e - s).toFixed(2);\n}\n\nfunction roi(e, s) {\n if( !e ) return '0%';\n return (((e - s) / s) * 100).toFixed(0) + '%';\n}\n</code></pre>\n\n<hr>\n\n<h2>Addendum</h2>\n\n<p>If you need to handle the conversion differently for different levels of nesting (re: the comments), you could do something like this</p>\n\n<pre><code>function convert(obj) {\n // get the extra, optional, argument.\n // It defaults to 1, and increments otherwise\n var level = (arguments[1] || 0) + 1;\n\n var item, leaf, key, leaves = [];\n for( key in obj ) {\n if( !obj.hasOwnProperty(key) ) continue;\n item = obj[key];\n // Check the level here\n if( level === 2 ) {\n // 2nd level will only be converted to a simpler, non-leaf object\n leaf = { name: key, children: [] };\n } else {\n // Other levels will become \"leaves\"\n leaf = buildLeaf(key, item);\n }\n leaves.push(leaf);\n if( typeof item.children === 'object' ) {\n // remember to pass the level on\n leaf.children = convert(item.children, level);\n }\n }\n return leaves;\n}\n</code></pre>\n\n<p>I don't know if there's a system in the data you're converting, but you could also check for <code>level % 2 === 0</code> to handle every second (i.e. even-numbered) level differently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T21:01:59.477",
"Id": "26318",
"Score": "0",
"body": "Hey thanks for this! There's some good stuff here to take away. The only thing is that the blank 'middle' object is intentional as it's just to serve as a 'folder' row that has no values. I'm just trying to figure out how to break in to the function to determine when it hits the middle bit so that I can return a leaf with only a name for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T21:24:11.457",
"Id": "26320",
"Score": "0",
"body": "@Ataraxy Well, I figured there was a reason for the way you were doing it, but I also figured that the extra values in the \"middle leaves\" would do no harm by being there. But if it's a problem, you could for instance use a counter; increment it for each \"level\", and check what level you're on before making a leaf. I'll add some code for that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:49:28.613",
"Id": "16169",
"ParentId": "16136",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-10-03T06:04:27.480",
"Id": "16136",
"Score": "5",
"Tags": [
"javascript",
"performance"
],
"Title": "Converting an object to be used with a treegrid"
}
|
16136
|
<p>I wrote a wrapper library for a REST API in Perl using the Moose library. I would like to gather some feedback on it (mainly on the OOP part since I am new to moose), before pushing it out.</p>
<p>Base class:</p>
<pre><code>has 'debug' => (is => 'rw', isa => 'Bool', default => 0);
has 'api_key' => (is => 'ro', isa => 'Str', required => 1);
has 'api_secret' => (is => 'ro', isa => 'Str', required => 1);
has 'api_base' => (is => 'ro', isa => 'Str', lazy_build => 1);
has 'oauth_client' => (is => 'ro', isa => 'Object', lazy_build => 1);
# Helper methods
method _get {
my $path = shift;
my $json_params = shift;
return $self->_make_request('GET',$path,$json_params);
}
method _make_request {
my $req_type = shift;
my $req_path = shift;
my $req_params_json = shift;
my $url = $self->api_base . '/' . $req_path;
#$req->header( Authorization =>
# "Basic " . encode_base64($self->api_key . ':'));
my $resp;
my $e = eval{
$resp = $self->oauth_client->request(
method => $req_type,
url => $url,
params => {q => $req_params_json}
);
};
if($@) {
$self->_req_error_msg("Request could not be made","","");
}
if ($resp->code == 200) {
my $hash = decode_json($resp->content);
return hash_to_object($hash) if $hash->{object};
if (my $data = $hash->{data}) {
return [ map { hash_to_object($_) } @$data ];
}
return $hash;
}
else {
$self->_req_error_msg("Request failed",$resp->status_line,$resp->content);
}
$e = eval { decode_json($resp->content) };
if ($@) {
$self->_req_error_msg("Could not decode HTTP response",$resp->status_line,$resp->content);
};
#warn "$e\n" if $self->debug;
die "Error occured\n";
}
method _req_error_msg {
my $msg =shift;
my $status_line = shift;
my $content = shift;
print STDERR "Message: $msg\n";
print STDERR "Status Line: $status_line\n";
print STDERR "Content: $content\n";
}
sub hash_to_object {
my $hash = shift;
my $class = 'Net::Semantics3::' . ucfirst($hash->{object});
return $class->new($hash);
}
method _build_api_base { 'https://api.semantics3.com/v1' }
method _build_oauth_client {
my $ua = LWP::UserAgent->new;
$ua->agent("Semantics3 Perl Lib/$VERSION");
my $oauth_client = OAuth::Lite::Consumer->new(
ua => $ua,
consumer_key => $self->api_key,
consumer_secret => $self->api_secret,
);
return $oauth_client;
}
</code></pre>
<p>Products.pm</p>
<pre><code>extends 'Net::Semantics3';
use constant MAX_LIMIT => 10;
has 'products_query' => (isa => 'HashRef', is => 'rw', default => sub { my %hash; return \%hash; } );
has 'categories_query' => (isa => 'HashRef', is => 'rw', default => sub { my %hash; return \%hash; } );
has 'query_result' => (isa => 'HashRef', is => 'rw', default => sub { my %hash; return \%hash; } );
has 'sem3_endpoint' => (isa => 'Str', is => 'ro', writer => 'private_set_endpoint', default => "products");
Products: {
#stupid hack to enforce method overloading
method field {
my $field_name = shift || die "A Field Name is required";
my $field_value1 = shift;
my $field_value2 = shift;
if(!defined($field_value1) && !defined($field_value2)) {
die "A Field value is required";
}
if(defined($field_value2)) {
if(!defined($self->products_query->{$field_name})) {
$self->products_query->{$field_name} = {};
}
$self->products_query->{$field_name}->{$field_value1} = $field_value2;
} else {
$self->products_query->{$field_name} = $field_value1;
}
}
method get_products {
$self->_run_query("products",$self->products_query);
return $self->query_result();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>In Net::Semantics3 _make_request I wasn't too sure about the error handling. It looks like _req_error_msg doesn't die if any part of the request process fails. Also 200 may not be the only valid HTTP status code, it's safer to use the is_success method</p>\n\n<pre><code>if ($resp->is_success) { #handle response...\n</code></pre>\n\n<p>You could also clean up the eval calls and use <a href=\"http://search.cpan.org/~doy/Try-Tiny-0.11/lib/Try/Tiny.pm\" rel=\"nofollow\">Try::Tiny</a> instead, which I think looks a bit neater.</p>\n\n<p>My Moose is a bit rusty, but I believe you can use class names in type definitions (feel free to correct if this isn't the case)</p>\n\n<pre><code>has 'oauth_client' => (is => 'ro', isa => 'OAuth::Lite::Consumer', lazy_build => 1); \n</code></pre>\n\n<p>As for the general structure OO structure I would probably have preferred separate classes for representing queries, results and the Net::Semantics3 user agent. Almost analogous to HTTP::Request, LWP::UserAgent and HTTP::Response. If I was using your code I'd like to be able to do something like this:</p>\n\n<pre><code>my $product_query = Net::Semantics3::ProductsQuery->new({brand => \"Toshiba television\"});\nmy $net_semantics3_ua = Net::Semantics->new();\nmy $prod_resultset = $net_semantics3_ua->execute_query($product_query);\nforeach my $prod($prod_resultset->all){\n say $prod->field_name;\n}\n</code></pre>\n\n<p>There's nothing really wrong with the approach you've taken, but if I read the example code in your test.pl script it doesn't feel like the interface is very perlish. I think you could make it a bit more intuitive for programmers using your API</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T20:34:24.907",
"Id": "16172",
"ParentId": "16139",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16172",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-10-03T07:44:43.613",
"Id": "16139",
"Score": "3",
"Tags": [
"api",
"perl",
"meta-programming",
"rest"
],
"Title": "Perl wrapper library (written using Moose) for a REST API"
}
|
16139
|
<p>I'm creating some age-verification functionality for an iOS app. The user is presented with a <code>UIDatePicker</code> object, and the latest selectable date should be today minus 18 years. How vulnerable to inaccuracy is my code? How could it be leaner?</p>
<pre><code>-(void)validateAge {
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [today day];
NSInteger month = [today month];
NSInteger year = [today year];
int correctYear = year - 18;
NSDateComponents *correctAge = [[NSDateComponents alloc] init];
[correctAge setDay:day];
[correctAge setMonth:month];
[correctAge setYear:correctYear];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
UIDatePicker *agePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 240, 320, 200)];
[agePicker setDatePickerMode:UIDatePickerModeDate];
[agePicker setMaximumDate:[calendar dateFromComponents:correctAge]];
[self.view addSubview:agePicker];
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T13:21:40.377",
"Id": "28579",
"Score": "0",
"body": "Well, first of all, what about leap years ? If someone uses it on the 29th of february on a leap year, february 18 years earlier will always be 28 days long. I don't know what will happen with your code though, but I'd suggest to set up a test scenario for this situation.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T13:23:28.237",
"Id": "28580",
"Score": "0",
"body": "I think *[calendar dateFromComponents:correctAge]* (third line from bottom) may crash.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:17:44.870",
"Id": "28587",
"Score": "0",
"body": "That's an interesting point. I tested it by setting my system date to 29/02/2012. My datepicker set the maximum date to 01/03/1994. I think that's acceptable from a legal standpoint, as 'leaplings' can either have their birthdays on February 28th or March 1st. The app I implemented this in has been tested fairly extensively on a number of devices; no crashes yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T08:44:27.423",
"Id": "28730",
"Score": "0",
"body": "Well, I think you're good then !"
}
] |
[
{
"body": "<p>Check this method. Pass value as minus 18 (-18)</p>\n\n<pre><code>-(NSDate *)offsetYear:(int)numOfYears date:(NSDate*)date {\n NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];\n [offsetComponents setYear:numOfYears];\n\n return [gregorian dateByAddingComponents:offsetComponents\n toDate:date options:0];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T21:43:17.077",
"Id": "48326",
"Score": "1",
"body": "Can you give a brief description of what this method is doing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-12T08:10:58.530",
"Id": "49577",
"Score": "0",
"body": "@JeffVanzella It offsets the the specific date by `numYears` in the Gregorian calendar. For example if you will pass `-18` it will go back 18 years (and deal with leap years correctly)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-12T08:13:43.323",
"Id": "49578",
"Score": "0",
"body": "It would be better to `NSInteger` for the `numYears` argument to better deal with 32bit/64bit differences (iPhone 5S was just announced to be 64 bit). Also, `numYears` is passed to `setYear:` which takes an `NSInteger`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T21:20:08.683",
"Id": "30399",
"ParentId": "16145",
"Score": "2"
}
},
{
"body": "<p>One basic idea about human-computer interaction is that a user should always be able to select something on the interface and go forward <em>somewhere</em>. You don't want to just leave them 'on hold'.</p>\n\n<p>In your implementation, if the user is under 18, the interface will force them to lie about their birth date.</p>\n\n<p>A much better idea would be to <strong>allow the user to select any date</strong>, but compute the difference in years to perform different operations depending upon the difference. You do this using </p>\n\n<pre><code>NSDateComponents *components = [calendar components:NSYearCalendarUnit\n fromDate:enteredDate\n toDate:[Date new] // today\n options:0];\n</code></pre>\n\n<p>After that, for people under 18, you can e.g. display an alert and redirect them to a different app.</p>\n\n<p>It would still be possible for users to lie about their birth dates, of course, but the interface will not encourage it as much.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T10:40:20.547",
"Id": "32457",
"ParentId": "16145",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T10:12:49.687",
"Id": "16145",
"Score": "4",
"Tags": [
"objective-c",
"ios"
],
"Title": "Age verification in Objective-C"
}
|
16145
|
<p>I know about the "little bobby tables" scenario and was just wondering if this code is vulnerable to such SQL injections.</p>
<p><sup>I am fairly new to PHP and am curious about this.</sup></p>
<p><strong>My code for a login script:</strong></p>
<pre><code><?php
# session
session_start();
# get the variables from login.php
$userid = $_POST["userid"];
$pword = $_POST["pword"];
mysql_real_escape_string($userid);
mysql_real_escape_string($pword);
# query the DB
$query = mysql_query ("
SELECT username
FROM login
WHERE username = '$userid'
AND pword = '$pword';
");
if ($query === FALSE) {
die('There has been an error.<br><br> Please re-enter your Login Details on the <b><a href="login.php">Login</a></b> Page.<br><br>');
}
$result = mysql_fetch_assoc($query);
$record = $result['username'] ;
# valid login
# check if session is operational, if so redirect the user
# to the correct page
if ($record != null) {
$_SESSION['login'] = true;
header( 'Location: index.php' ) ;
}
# invalid login
else if ($record == null) {
echo "
We cant find you on the system.
<br/>
Please return to the <b><a href='login.php'>Login</a></b> page and ensure that
<br/>
you have entered your details correctly.
<br><br>
<b>Warning</b>: You willl be redirected back to the Login Page
<br> in <b> <span id='counter'>10</span> Second(s)</b>";
}
?>
</code></pre>
<p>The main reason for asking this is that when I login inputting:</p>
<pre><code>'user'); DROP TABLE Login;--'
</code></pre>
<p>it doesnβt drop the table.</p>
<p><br/>
<strong>My question is:</strong> Am I typing in the right SQL injection?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T09:55:22.513",
"Id": "26246",
"Score": "0",
"body": "the single quotes around the sql are not used, theyre only there for the purpose of this question"
}
] |
[
{
"body": "<p>This is vulnerable:</p>\n\n<pre><code>mysql_real_escape_string($userid);\nmysql_real_escape_string($pword);\n</code></pre>\n\n<p>does not return the variable. Use:</p>\n\n<pre><code>$userid = mysql_real_escape_string($userid);\n$pword = mysql_real_escape_string($pword);\n</code></pre>\n\n<p>If you really want to take care of all vulnerable SQL injections try to move to PDO. <a href=\"http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers\">Here is a nice tutorial</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T09:58:48.887",
"Id": "26247",
"Score": "1",
"body": "Oops, I didn't notice this in my answer. To add to this one though, you are not dropping the table because the `mysql_*` family of functions only execute a single statement, not multiple ones, so anything after the `;` in your statement (e.g. the `DROP TABLE`) is ignored."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:02:59.967",
"Id": "26248",
"Score": "0",
"body": "@slugonamission so I was not wrong"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:04:01.727",
"Id": "26249",
"Score": "0",
"body": "yes, but to get to last `;` it will have to pass `$userid` and `$pword` right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:04:20.963",
"Id": "26250",
"Score": "0",
"body": "@EaterOfCorpses - I never said you were?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:05:58.980",
"Id": "26251",
"Score": "0",
"body": "@slugonamission See my answer I posted just at the same time as you lol"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:06:15.357",
"Id": "26252",
"Score": "0",
"body": "@MihaiIorga Yep,"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:06:21.323",
"Id": "26253",
"Score": "0",
"body": "@MihaiIorga - oh yes, it is still very much vulnerable, but the OP was was asking why his `user'); DROP TABLE Login;--` didn't drop the table. Something along the lines of `' OR ''='` for both the username and password would allow for passwordless login."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:06:51.333",
"Id": "26254",
"Score": "0",
"body": "Exactly what was in my mind :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:07:03.010",
"Id": "26255",
"Score": "0",
"body": "@EaterOfCorpses - but...mine was about a minute earlier. I still upvoted yours since it's still technically correct :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:07:52.657",
"Id": "26256",
"Score": "0",
"body": "You answered at 09:57:15 :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:08:39.807",
"Id": "26257",
"Score": "0",
"body": "My browser says 9:58 vs 9:59 ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T10:10:48.780",
"Id": "26258",
"Score": "0",
"body": "@slugonamission my at the same time = time +/- `new DateInterval('PT30S')`"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T09:56:41.000",
"Id": "16148",
"ParentId": "16147",
"Score": "6"
}
},
{
"body": "<p>The injection doesn't work because <code>mysql_query</code> only does the first query till the <code>;</code> then it stops so its not possible that way, correct me if I'm wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-22T16:09:54.170",
"Id": "148005",
"Score": "0",
"body": "That's right, but the code is vulnerable to to other SQL injection attacks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T09:59:29.790",
"Id": "16149",
"ParentId": "16147",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T09:54:10.483",
"Id": "16147",
"Score": "1",
"Tags": [
"php",
"mysql",
"security"
],
"Title": "How can I ascertain and test SQL injection vunerabilities on this login code?"
}
|
16147
|
<p>My app saves data to a file - I obviously don't want the app to write to the file from multiple locations on disk. What I want is a generic "utility" class that will know how to run a piece of code (let's call it SingletonTask) with the following rules:</p>
<ol>
<li>Only one SingletonTask will run at any given moment in the system - <strong>EDIT:</strong> note that this singleton task may be asynchronous in nature and may require execution on the UI thread.</li>
<li>When multiple calls are made to run the SingletonTask, the first one will immediately run the SingletonTask and every subsequent call that happens before SingletonTask runs will "queue up".</li>
<li>All calls that are "queued up" during the run of SingletonTask will cause only a single new SingletonTask to execute (and all of them will complete when that one SingletonTask completes)</li>
<li>Obviously, if during the SingletonTask executed in (3), more calls come in, they will follow rule (2) and so on.</li>
</ol>
<p>I could not find anything like this in .NET (looking for something that works on Win8) - but maybe I don't know what the correct keywords are.</p>
<p>In any case - here's my attempt at doing this.. I have a utility class called SigletonTask you inherit from. That class has a protected abstract method called <code>RunProcessAsync()</code>. The method users call is <code>RunAsync()</code> and it behaves as described in the above rules.</p>
<p>I tested this and it seems to work, however, there is an issue with it: It's currently limiting usage to from within the UI thread. This makes the solution simpler, but means you cannot use it from arbitrary threads. I looked into locking inside the method, but could not come up with something elegant that does not deadlock.</p>
<p>My questions are:</p>
<ol>
<li>Can you see any issues with the code?</li>
<li>Can you make the code better?</li>
</ol>
<p>Here's the SingletonTask class:</p>
<p>(<strong>EDIT: This is a new version. Old version at the bottom.</strong>)</p>
<p>(Also - it's based on <a href="http://socialeboladev.wordpress.com/2012/10/15/coldtask-implementation-for-windows-8/" rel="nofollow">cold tasks</a>)</p>
<pre><code>public abstract class SingletonTask
{
private Task m_runningTask = null;
private Task m_nextTask = null;
private object m_lock = new object();
public SingletonTask()
{
}
public Task RunAsync()
{
return RunAsync(() => RunProcessAsync());
}
public async Task RunAsync(Func<Task> taskGetter)
{
Task task1 = null;
Task task2 = null;
ColdTask start1 = null;
ColdTask start2 = null;
lock (m_lock)
{
if (m_runningTask == null)
{
start1 = new ColdTask(taskGetter);
Task innerTask = start1.GetTask();
m_runningTask = innerTask.ContinueWith(x => { lock (m_lock) { m_runningTask = null; } });
task1 = m_runningTask;
}
else
{
task1 = m_runningTask;
if (m_nextTask == null)
{
start2 = new ColdTask(taskGetter);
Task innerTask = start2.GetTask();
m_nextTask = innerTask.ContinueWith(x => { lock (m_lock) { m_nextTask = null; } });
}
task2 = m_nextTask;
}
}
if (start1 != null)
{
start1.Start().RunWithoutWarning();
}
if (task1 != null)
{
await task1;
}
if (start2 != null)
{
start2.Start().RunWithoutWarning();
}
if (task2 != null)
{
await task2;
}
}
protected virtual Task RunProcessAsync()
{
return null;
}
}
</code></pre>
<p>And here's how you inherit from it:</p>
<pre><code>class MySing : SingletonTask
{
private int m_id = 1000;
Action<string> log;
public MySing(Action<string> log, CoreDispatcher dispatcher) : base(dispatcher)
{
this.log = log;
}
protected override async Task RunProcessAsync()
{
int id = m_id++;
log("Before delay for " + id.ToString());
await Task.Delay(4000);
log("After delay for " + id.ToString());
}
}
</code></pre>
<p>My test app is fairly simple - there's a button that calls into an instance of <code>MySing</code> and awaits the result, logging before awaiting and after awaiting:</p>
<pre><code>private void Button_Click_1(object sender, RoutedEventArgs e)
{
int id = m_id++;
Log("Running with id=" + id.ToString());
await m_sing.RunAsync();
Log("Run returned with id=" + id.ToString());
}
</code></pre>
<p>Tap the button 3 times quickly, for example, and you should see:</p>
<blockquote>
<p>Running with id=0</p>
<p>Before delay for 1000</p>
<p>runnjng with id=1</p>
<p>Running with id=2</p>
<p>After delay for 1000</p>
<p>Run returned with id=0</p>
<p>Before delay for 1001</p>
<p>After delay for 1001</p>
<p>Run returned with id=1</p>
<p>Run returned with id=2</p>
</blockquote>
<p>(I hope asking such a question is kosher here)</p>
<p>------------------------- OLD -------------------------------</p>
<p>(This is the code for my original question, before the edit.)</p>
<pre><code>public abstract class SingletonTask
{
private Task m_runningTask = null;
private Task m_nextTask = null;
private object m_lock = new object();
private CoreDispatcher m_dispatcher = null;
public SingletonTask(CoreDispatcher dispatcher)
{
m_dispatcher = dispatcher;
}
public async Task RunAsync()
{
if (!m_dispatcher.HasThreadAccess)
{
throw new UnauthorizedAccessException("Unauthorized thread access");
}
Task firstRun = null;
if (m_runningTask == null)
{
Task innerRun = RunProcessAsync();
m_runningTask = innerRun.ContinueWith(x => m_runningTask = null);
firstRun = innerRun;
}
else if (m_nextTask == null)
{
await m_runningTask;
if (m_runningTask == null)
{
Task innerRun = RunProcessAsync();
m_runningTask = innerRun.ContinueWith(x => m_runningTask = null);
}
firstRun = m_runningTask;
}
if (firstRun != null)
{
await firstRun;
}
}
protected abstract Task RunProcessAsync();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-18T13:58:34.260",
"Id": "28120",
"Score": "0",
"body": "Found anything neater?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-18T14:13:02.977",
"Id": "28124",
"Score": "0",
"body": "Updated. I think I found something I am happy with. Had to implement Cold tasks for it (link just above the new code). This seems to work great and works from any thread."
}
] |
[
{
"body": "<p>I made something like this before but I don't claim that it's better.<br>\nAlthough it's much simpler:</p>\n\n<pre><code>public sealed class SingleTask\n{\n private Task _Task;\n private readonly object _Lock = new object();\n\n // You can overload this with TaskCreationOptions, TaskScheduler etc.\n public SingleTask() { _Task = Task<object>.FromResult(null); }\n\n // You can overload Queue methods with TaskContinuationOptions,\n // TaskScheduler, CancellationToken etc.\n public Task Queue(Action action)\n {\n lock (_Lock)\n return _Task = _Task.ContinueWith(t => action.Invoke());\n }\n public Task<T> Queue<T>(Func<T> function)\n {\n lock (_Lock)\n {\n _Task = _Task.ContinueWith<T>(t => function.Invoke());\n return _Task as Task<T>;\n }\n }\n}\n</code></pre>\n\n<p>You can use <code>ContinueWith</code> methods for queuing actions so I don't think you need a custom approach here. Here the <code>Queue</code> methods also return task objects so you can wait them individually.</p>\n\n<p>You can make this class static if you want it to behave like a singleton.<br>\nBut I can't see a reason for doing so.</p>\n\n<p>As for your code, I don't see any issues with it.</p>\n\n<p><strong>Edit (Usage)</strong></p>\n\n<p>Let's say you have these methods you want to run asynchronously:</p>\n\n<pre><code>private void LongInitialization() { /* Some operation */ }\nprivate int LongCalculation() { /* Some operation */ }\n</code></pre>\n\n<p>You can:</p>\n\n<pre><code>// Creates a completed task.\nvar single = new SingleTask();\n\n// Starts initialization and returns its task.\nTask initializeTask = single.Queue(LongInitialization);\n\n// Queues LongCalculation to run after LongInitialization is completed.\nTask<int> calculateTask = task.Queue(LongCalculation);\n</code></pre>\n\n<p>In these samples however, you can't interact with UI controls because you can't <em>access a control from a thread other than the one the control was created on</em>. So if you have a method like this:</p>\n\n<pre><code>private void UpdateText() { txtStatus.Text = GetStatusFromDB(); }\n</code></pre>\n\n<p>...which interacts with a <code>TextBox</code>, and if you call <code>single.Queue(UpdateText)</code>, you'll see an exception is thrown with the message: \"Cross-thread operation not valid\".</p>\n\n<p>What you can do here to prevent this, is providing an overload to the <code>SingleTask</code>'s <code>Queue(Action)</code> method that takes a <code>TaskScheduler</code> as a parameter:</p>\n\n<pre><code>public Task Queue(Action action, TaskScheduler scheduler)\n{\n lock (_Lock)\n return _Task = _Task.ContinueWith(t => action.Invoke(), scheduler);\n}\n</code></pre>\n\n<p>Then you can call it like this:</p>\n\n<pre><code>single.Queue(UpdateText, TaskScheduler.FromCurrentSynchronizationContext());\n</code></pre>\n\n<p>By calling <code>Queue</code> like this on a UI thread you say \"Hey! Here is the UI's synchronization context, call its Post method so it won't break my program\".</p>\n\n<p>You also can provide overloads to <code>Queue</code> so it can take <code>TaskContinuationOptions</code> (if you want to specify <code>LongRunning</code> and make it run on a different thread, etc.) and/or <code>CancellationToken</code> parameters (if you want to provide cancellation). For example:</p>\n\n<pre><code>public Task Queue(Action<CancellationToken> action,\n TaskScheduler scheduler,\n TaskContinuationOptions options,\n CancellationToken token)\n{\n lock (_Lock)\n return _Task = _Task\n .ContinueWith(t => action.Invoke(token), token, options, scheduler);\n}\n</code></pre>\n\n<p>You can share the same <code>SingleTask</code> insance anywhere you want to do things asynchronously but <em>in an order</em> so, I hope this will satisfy your goals. Again, if you want to have only one instance of this, you can always make this class static.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T12:07:54.693",
"Id": "26261",
"Score": "0",
"body": "So in this solution dead locking could occur if somebody were to `await` on the returned `Task` forever, though a bug, still a realistic scenario right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:09:13.640",
"Id": "26302",
"Score": "0",
"body": "Hey! Thanks for the reply. So - the issue I am seeing here is that your functions are not async themselves - you are going to run them on a separate thread but if, say, they need the UI thread, or if your task is simply of an asynchronous nature you need to wrap it in a Func<> or Action and do .Wait() on it right? Updated my original question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T07:43:53.993",
"Id": "26341",
"Score": "0",
"body": "@ΕafakGΓΌr That's great - but again - what I meant is that the action you are scheduling is not async by itself. You could, for example, in the action, type the following: () => DoSomethingAsync.Wait(), however, that means you have a whole thread that's \"taken\" waiting for the operation to complete. I want the action you execute itself to be Asynchronous - not the method that executes the action. Note how in my implementation, RunProcessAsync() is itself an async operation)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T07:49:45.810",
"Id": "26344",
"Score": "0",
"body": "@Shahar: So you want to queue operations that are already asynchronous I guess? Alright then, let me look that again :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T08:16:31.830",
"Id": "26347",
"Score": "0",
"body": "Yeah - exactly - notice how the example I gave the operation is actually async - I can do a bunch of operations in there that are async in nature (using 4.5's await mechanism)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T08:33:43.710",
"Id": "26349",
"Score": "1",
"body": "@Shahar: I see your point; async/await thingy already does it by sending the rest of the method as a delegate to the *awaitable* to invoke when its job is done and provide synchronization to asynchronous operations. I don't think I can add much to your wrapper in this case. You may want to change `m_id++` to `Interlocked.Increment(ref m_id)` but other than that, your approach seems solid enough to me. I may need something like this, too so I'll look more into it when I can. Hope you'll end up with something neater."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:28:54.803",
"Id": "16151",
"ParentId": "16150",
"Score": "7"
}
},
{
"body": "<p>Okay, after much updating I effectively have two approaches. Both of them use a <code>Queue</code>, but one uses the new <code>ConcurrentQueue</code>.</p>\n\n<h2>Old Fashioned Queue</h2>\n\n<pre><code>public class Scheduler\n{\n private BackgroundWorker _processor = new BackgroundWorker();\n\n private Queue<Action> ScheduledTasks { get; set; }\n\n public Scheduler()\n {\n _processor.WorkerSupportsCancellation = true;\n _processor.DoWork += (s, args) =>\n {\n while (!_processor.CancellationPending)\n {\n Queue.Synchronized(this.ScheduledTasks).Dequeue()();\n }\n }\n\n _processor.RunWorkerAsync();\n }\n\n public void ScheduleTask(Action task)\n {\n Queue.Synchronized(this.ScheduledTasks).Enqueue(task);\n }\n}\n</code></pre>\n\n<h2>New Concurrent Queue</h2>\n\n<pre><code>public class Scheduler\n{\n private BackgroundWorker _processor = new BackgroundWorker();\n\n private ConcurrentQueue<Action> ScheduledTasks { get; set; }\n\n public Scheduler()\n {\n _processor.WorkerSupportsCancellation = true;\n _processor.DoWork += (s, args) =>\n {\n while (!_processor.CancellationPending)\n {\n Action task = null;\n if (this.ScheduledTasks.TryDequeue(out task))\n {\n task();\n }\n }\n }\n\n _processor.RunWorkerAsync();\n }\n\n public void ScheduleTask(Action task)\n {\n this.ScheduledTasks.Enqueue(task);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:48:02.050",
"Id": "26262",
"Score": "0",
"body": "Is there a particular reason why you don't use a ConcurrentQueue?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:51:19.037",
"Id": "26263",
"Score": "0",
"body": "@ΕafakGΓΌr, nope. I've just never used that class before and didn't even know it existed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:59:10.703",
"Id": "26264",
"Score": "0",
"body": "@ΕafakGΓΌr, I have updated my answer to show use with the `ConcurrentQueue(T)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:59:53.690",
"Id": "26265",
"Score": "0",
"body": "It's part of the thread-safe collections that came with the .NET 4 (They're in System.Collections.Concurrent namespace). They are lock-free and highly suited for concurrent operations like this. Might perform better (I'm not sure though). **Edit**: Just saw your edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T12:04:34.287",
"Id": "26266",
"Score": "1",
"body": "@ΕafakGΓΌr, and this is why I use Stack Overflow. I don't know __everything__, and so it's great when I learn new things like this!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:12:26.803",
"Id": "26303",
"Score": "0",
"body": "Thanks for the reply! I updated the rules (unfair! :)) above - I wanted the task execute to itself be asynchronous (which is what my example shows). Sorry for being unclear. Great answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-02T14:43:39.137",
"Id": "313431",
"Score": "0",
"body": "https://stackoverflow.com/questions/148078/how-to-make-a-method-exclusive-in-a-multithreaded-context"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T11:42:05.407",
"Id": "16152",
"ParentId": "16150",
"Score": "3"
}
},
{
"body": "<p>Wow, there's a lot of complex answers here.</p>\n\n<p>First, if you accept the restriction of UI-thread only, this is quite simple:</p>\n\n<pre><code>public abstract class SingletonTask\n{\n private Task _runningTask = null;\n\n // Must be called from UI thread.\n public Task RunAsync()\n {\n if (_runningTask != null)\n return _runningTask;\n _runningTask = StartNewRunAsync();\n return _runningTask;\n }\n\n private async Task StartNewRunAsync()\n {\n try { await RunProcessAsync(); }\n finally { _runningTask = null; }\n }\n\n protected abstract Task RunProcessAsync();\n}\n</code></pre>\n\n<p>The code above uses the UI thread as a synchronization mechanism. So, <code>_runningTask</code> is always written to from the UI thread (and read from there as well). The coalescing of tasks is handled by just keeping a single \"current\" instance.</p>\n\n<p>Extending this to be multithreaded is a bit trickier:</p>\n\n<pre><code>public abstract class SingletonTask\n{\n private Task _runningTask = null;\n private object _mutex = new object();\n\n public Task RunAsync()\n {\n Task result;\n TaskCompletionSource<object> tcs = null;\n lock (_mutex)\n {\n if (_runningTask != null)\n return _runningTask;\n tcs = new TaskCompletionSource<object>();\n _runningTask = result = StartNewRunAsync(tcs.Task);\n }\n tcs.SetResult(null);\n return result;\n }\n\n private async Task StartNewRunAsync(Task start)\n {\n await start;\n try { await RunProcessAsync(); }\n finally { lock (_mutex) _runningTask = null; }\n }\n\n protected abstract Task RunProcessAsync();\n}\n</code></pre>\n\n<p>In this case, we need a <code>_mutex</code> for mutual exclusion. The other tricky part is that we don't want to call <code>RunProcessAsync</code> while holding a lock (as a general rule, you should never invoke arbitrary code while holding a lock). So, I use a \"signal\" (<code>tcs</code>) to get the <code>Task</code> from <code>StartNewRunAsync</code> before it actually invokes <code>RunProcessAsync</code>. That way I can update <code>_runningTask</code> still within the lock and then tell it to <em>really</em> start running at the <code>tcs.SetResult(null)</code> line. When it completes, it just sets <code>_runningTask</code> to <code>null</code>, so the next time <code>RunAsync</code> takes the lock, it'll start a new one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-01T13:02:18.957",
"Id": "164683",
"ParentId": "16150",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T08:45:23.970",
"Id": "16150",
"Score": "5",
"Tags": [
"c#",
"asynchronous"
],
"Title": "\"Singleton\" task running - using Tasks/await - peer review/challenge"
}
|
16150
|
<p>I have got such 2d jagged array (row is 1st dimension, column is 2nd dimension, bottom to up, left to right)</p>
<pre><code>0 0 b b b c
0 0 h g g c
0 0 h a a c
0 0 f f d d
0 0 i j e e
0 0 i j 0 0
</code></pre>
<p>I would like to get a 2d jagged array summarize the positions of consecutive elements for each row, and ignore all <code>0</code> or single elements (assume that things like <code>x x x y x x</code> would not occur, so there won't be 2 blocks of same chars in a row)</p>
<p>the ideal outcome would be</p>
<pre><code>{(b,3,5,2)} // char, length, rowID, columnID
{(g,2,4,3)}
{(a,2,3,3)}
{(f,2,2,2), (d,2,2,4)}
{(e,2,1,4)}
{}
</code></pre>
<p>this is my code, i feel it is not that readable, so I appreciate any suggestion in C# or F# (Linq extension method is welcomed as well)</p>
<pre><code> Tuple<char, int, int, int>[][] GetHorizontalBricks()
{
List<Tuple<char, int, int, int>[]> ret = new List<Tuple<char, int, int, int>[]>();
for (int rowID = 0; rowID < rowNum; rowID++)
{
List<Tuple<char, int, int, int>> rowBricks = new List<Tuple<char, int, int, int>>();
var row = myBoard[rowID];
int recentCount = 1;
int columnID = 0;
while (columnID < columnNum)
{
char recent = row[columnID];
int next = columnID + 1;
for (; next < columnNum; next++)
{
if (row[next] == recent)
{
recentCount++;
}
else
{
break;
}
}
if (recentCount > 1 && recent != '0')
{
rowBricks.Add(Tuple.Create(recent, recentCount, rowID, columnID));
}
columnID = next;
recentCount = 1;
}
ret.Add(rowBricks.ToArray());
}
return ret.ToArray();
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all get rid of these tuples. After one week you will forget what each int represents. Define simple struct/class for your brick.</p>\n\n<p>Second thing, small performance suggestion for big row count - explicit initial list size:</p>\n\n<pre><code>... = new List<Tuple<char, int, int, int>[]>(myBoard.Length);//assuming myBoard is an array\n</code></pre>\n\n<p>without it, list would be recreated and rewritten every 4 new elements.</p>\n\n<p>Below is mine implementation with linq extensions. Probably it is not faster. I don't know if it is more readable, but at least line count is smaller :)</p>\n\n<pre><code>public struct Brick\n{\n public char Symbol { get; set; }\n public int Length { get; set; }\n public int RowID { get; set; }\n public int ColumnID { get; set; }\n\n public override string ToString()\n {\n return string.Format(\"{0} {1} {2} {3}\", Symbol, Length, RowID, ColumnID);\n }\n}\n\npublic Brick[][] GetHorizontalBricks(char[][] board)\n{\n return\n board\n .Reverse() //bottom up row order\n .Select((row,rowIndex) =>\n row\n .Select((c,i) => new { c = c, i = i })\n .GroupBy(symbol => symbol.c) //assumption that we will never see 2 groups of same nonzero character in single row\n .Where(symbol => symbol.Key != 0 && symbol.Count() > 1)\n .Select(brick =>\n new Brick\n {\n Symbol = brick.Key,\n RowID = rowIndex,\n ColumnID = brick.First().i,\n Length = brick.Count()\n })\n .ToArray()\n )\n .Reverse() //reverse again to show result in form like you provided\n .ToArray();\n}\n</code></pre>\n\n<p>and Console app test:</p>\n\n<pre><code>static void Main(string[] args)\n{\n char[][] board = new char[][]\n {\n new char[] { (char)0, (char)0, 'b' ,'b','b','c'},\n new char[] { (char)0, (char)0, 'h' ,'g','g','c'},\n new char[] { (char)0, (char)0, 'h' ,'a','a','c'},\n new char[] { (char)0, (char)0, 'f' ,'f','d','d'},\n new char[] { (char)0, (char)0, 'i' ,'j','e','e'},\n new char[] { (char)0, (char)0, 'i' ,'j',(char)0,(char)0}\n };\n\n foreach (var row in new Program().GetHorizontalBricks(board))\n {\n Console.WriteLine(\"Row:\");\n foreach (var brick in row)\n Console.WriteLine(brick);\n }\n\n Console.ReadLine();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T20:37:38.163",
"Id": "26314",
"Score": "0",
"body": "thank u, I didn't know that Linq `select` supports index as well"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T20:40:02.353",
"Id": "26315",
"Score": "0",
"body": "Small warning. Watch out for monster linq queries.\nIt looks nice to do all in one chain but it can be pretty nasty to debug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T09:25:35.387",
"Id": "26351",
"Score": "1",
"body": "If you don't specify size of a `List`, it's not going to be βrecreated every 4 elementsβ, that would have terrible performance. Instead, every time it gets full, it is recreated to twice the size it was previously. Specifying the size can help you a bit, but probably not noticeably."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T09:42:42.333",
"Id": "26353",
"Score": "0",
"body": "My mistake. It starts from 0, then 4, 8, 16, 32 and so on. \nhttp://stackoverflow.com/questions/1762817/default-capacity-of-list"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T20:22:12.937",
"Id": "16171",
"ParentId": "16153",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16171",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T12:49:21.283",
"Id": "16153",
"Score": "4",
"Tags": [
"c#",
"f#"
],
"Title": "How to refactor this groupby alike method but with index?"
}
|
16153
|
<p>I posted <a href="https://stackoverflow.com/a/12679544/1075247">this</a> an answer this to a question about drawing a random line from a file too large to put into memory. I hacked the below code together. In essence, this is what Reservoir Sampling does, in pseudo-code:</p>
<pre><code>Scan over the 'tape'
Put the first 'n' samples in a reservoir(of size n)
// samples are lines of a document, numbers, whatever
After the first 'n' :
Pick a random number between 1 and NumberOfLinesCounted
if the number is between 1 and n
replace an existing line with a 1/n chance
</code></pre>
<p>Here is the code designed to scan over a document, with said sampling method:</p>
<pre><code>import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
public class reservoirSampling {
public static void main(String[] args) throws FileNotFoundException, IOException{
Sampler mySampler = new Sampler();
List<String> myList = mySampler.sampler(10);
for(int index = 0;index<myList.size();index++){
System.out.println(myList.get(index));
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Sampler {
public Sampler(){}
public List<String> sampler (int reservoirSize) throws FileNotFoundException, IOException
{
String currentLine=null;
//reservoirList is where our selected lines stored
List <String> reservoirList= new ArrayList<String>(reservoirSize);
// we will use this counter to count the current line number while iterating
int count=0;
Random ra = new Random();
int randomNumber = 0;
Scanner sc = new Scanner(new File("Open_source.html")).useDelimiter("\n");
while (sc.hasNext())
{
currentLine = sc.next();
count ++;
if (count<=reservoirSize)
{
reservoirList.add(currentLine);
}
else if ((randomNumber = (int) ra.nextInt(count))<reservoirSize)
{
reservoirList.set(randomNumber, currentLine);
}
}
return reservoirList;
}
}
</code></pre>
<p>I'm using something very similar on a project I am on at the moment (i.e. the code is close enough I can transfer any changes easily by hand).</p>
<p>Is this a) efficient, and b) actually reservoir sampling (with equal odds of any line being drawn)?</p>
|
[] |
[
{
"body": "<p>At the first glance </p>\n\n<p>You can use <code>Scanner.netxLine()</code> available on all OS.</p>\n\n<pre><code>(randomNumber = (int) ra.nextInt(count))<reservoirSize \n</code></pre>\n\n<p><em>EDIT suppressed unnecessary lines after comments</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T07:46:14.693",
"Id": "26343",
"Score": "0",
"body": "So use sc.nextLine() not Scanner(...).useDelimeter(\"\\n\")? Got it. Also, I don't follow how an `else if` would miss some lines? Reservoir sampling takes the first `n` lines then randomly swaps them out. Sometimes it swaps, sometimes it doesn't I thnk I see what you're doing, but that's not quite the point of reservoir sampling I don't think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T07:54:38.047",
"Id": "26345",
"Score": "0",
"body": "@Pureferret `else if` whithout a final `else` block do not catch all conditions. But it is that you want. So remove `while(1) ..` line and `break` line with a `}` so you remove the negative int randomised and avoid a Exception (no negative integer in an array position)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T08:02:53.393",
"Id": "26346",
"Score": "0",
"body": "Well the only thing not inside both the `else` and the `if` statement is the while and the random number, which the iff relies on - why not make them the same line? Also, I should never get a random number less than 0...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T08:30:44.313",
"Id": "26348",
"Score": "0",
"body": "@Pureferret `java.util.Random` return also negative number so you cannot test the two limits in the `if( ..)` statement . Maodify with EDIT"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T08:48:08.907",
"Id": "26350",
"Score": "0",
"body": "From the [docs](http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html)`nextInt(int n): Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.` So no. It can't return a negative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T09:29:49.023",
"Id": "26352",
"Score": "0",
"body": "@Pureferret - Exact, as I usually use `.nextInt()` so my response out of scope. Corrected"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T07:35:31.743",
"Id": "16190",
"ParentId": "16154",
"Score": "2"
}
},
{
"body": "<p>Reviving an old, but really interesting post, that did not get a great opportunity for review the first time around....</p>\n<h2>What you've done well:</h2>\n<p>This code, for the most part, is excellent. As for your specific questions:</p>\n<p>Is this:</p>\n<ol>\n<li><p>efficient</p>\n<p>Mostly, yes. The inefficiencies in here are all related to the IO, and the Scanner, not your code. A more low-level API may net you some performance benefits, but not likely. You are also (re)using the Random class well, and there should not be a problem there.</p>\n</li>\n<li><p>actually reservoir sampling (with equal odds of any line being drawn)?</p>\n<p>Yes. This is a good implementation of the reservoir algorithm. The random arguments are good, and the substitutions should be fine.</p>\n</li>\n</ol>\n<h2>What's concerning</h2>\n<ul>\n<li><p>The most significant beef is that you do not close the <code>Scanner</code>. Scanners can hold on to open file-handles, and, if the file really is big, this may have system-wide consequences. A try-catch-finally block would be appropriate (or, a try-with-resources if you're on Java7 now).</p>\n</li>\n<li><p>A second (smaller) issue is that reservoir sampling is designed to handle huge data in a streaming way. I know it is perhaps unrealistic to consider in your use-case, but multi-gigabyte files are not unexpected, and the likelihood of overflowing the <code>count</code> variable is not unrealistic. That would cause problems....</p>\n</li>\n<li><p>You should consider converting <code>count</code> and <code>randomNumber</code> to be <code>long</code> values, and only convert it back to an <code>int</code> if it is less-than <code>reservoirSize</code></p>\n</li>\n</ul>\n<h2>Finally....</h2>\n<p>Nice code to review. Thanks. Obviously, the new language features in more recent Java versions may be interesting to consider....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T03:50:06.237",
"Id": "42838",
"ParentId": "16154",
"Score": "7"
}
},
{
"body": "<p>A few random notes:</p>\n\n<ol>\n<li><p><code>FileNotFoundException</code> is a subclass of <code>IOException</code>. Declaring both <code>FileNotFoundException</code> and <code>IOException</code> is redundant.</p></li>\n<li><p>The <code>Sampler()</code> constructor can be omitted, since it is just the default constructor that would have been implicitly defined anyway.</p></li>\n<li><p>Your <code>sampler()</code> method is just a pure function, and could be made <code>static</code>.</p></li>\n<li><p>The <code>reservoirSampling</code> class should be named <code>ReservoirSampling</code>:</p>\n\n<blockquote>\n <p>Class names should be nouns, in mixed case with the first letter of each internal word capitalized.</p>\n</blockquote>\n\n<p>Reference: <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a></p></li>\n<li><p>According to the previous Code Conventions, <code>sampler()</code> should be named <code>sample()</code>:</p>\n\n<blockquote>\n <p>Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.</p>\n</blockquote></li>\n<li><p>It is a bad idea to hard-code the filename from which you will be sampling. The file should be passed in as a parameter. I think it's odd to take samples from an HTML file, which usually doesn't contain line-oriented data.</p></li>\n<li><p>Variables <code>currentLine</code> and <code>randomNumber</code> are only used inside the while loop, and should be declared inside it. (See <em>Effective Java, 2nd edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>It is not too difficult to change your code produce samples with <em>any</em> type, not just strings:</p>\n\n<pre><code>public static <T> List<T> sample(Iterator<T> pool, int reservoirSize)\n{\n //reservoirList is where our selected lines stored\n List<T> reservoirList = new ArrayList<T>(reservoirSize);\n // we will use this counter to count the current item number while iterating \n int count = 0;\n\n Random ra = new Random();\n while (pool.hasNext())\n {\n T current = pool.next();\n count++;\n // ...\n }\n}\n</code></pre>\n\n<p>(See <em>Effective Java, 2nd edition, Item 27: Favor generic methods</em>)</p></li>\n<li><p>For an <code>Iterator<String></code> over the lines of a file, you could use <code>FileUtils.lineIterator(new File(...))</code> from <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#lineIterator%28java.io.File%29\">Apache Commons IO</a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T11:15:16.597",
"Id": "42855",
"ParentId": "16154",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "42838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T13:00:57.810",
"Id": "16154",
"Score": "10",
"Tags": [
"java",
"random"
],
"Title": "Is this code an efficient implementation of Reservoir Sampling?"
}
|
16154
|
<p>If you notice, there are variables of <code>street_address</code>, <code>route</code>, <code>intersection</code> re-used in the entire code base. They are actually from Google Maps geocoder address components.</p>
<p>How can I refactor this one so that I don't have to declare them one by one?</p>
<p>Note that in the geocoder address components, those 3 mentioned above are just part of the 20+ components. I just removed the rest for simplicity sake.</p>
<p>I have tried declaring the address components in a new array, and using <code>for</code> loop, but it gets messy and more complicated.</p>
<pre><code>$(function() {
$('#shop_formatted_address').autocomplete({
// This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
// Get address_components
for (var i = 0; i < item.address_components.length; i++)
{
var addr = item.address_components[i];
var get_street_address, get_route, get_intersection;
if (addr.types[0] == 'street_address')
get_street_address = addr.long_name;
if (addr.types[0] == 'route')
get_route = addr.long_name;
if (addr.types[0] == 'intersection')
get_intersection = addr.long_name;
}
return {
label: item.formatted_address,
value: item.formatted_address,
lat: item.geometry.location.lat(),
lng: item.geometry.location.lng(),
street_address: get_street_address,
route: get_route,
intersection: get_intersection
}
}));
})
},
// This bit is executed upon selection of an address
select: function(event, ui) {
clearValue();
// Get values
$('#shop_lat').val(ui.item.lat);
$('#shop_lng').val(ui.item.lng);
$('#shop_street_address').val(ui.item.street_address);
$('#shop_route').val(ui.item.route);
$('#shop_intersection').val(ui.item.intersection);
var location = new google.maps.LatLng(ui.item.lat, ui.item.lng);
marker.setPosition(location);
map.setCenter(location);
},
// Changes the current marker when autocomplete dropdown list is focused
focus: function(event, ui) {
var location = new google.maps.LatLng(ui.item.lat, ui.item.lng);
marker.setPosition(location);
map.setCenter(location);
}
});
});
// Add listener to marker for reverse geocoding
google.maps.event.addListener(marker, 'drag', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clearValue();
if (results[0]) {
// Get address_components
for (var i = 0; i < results[0].address_components.length; i++)
{
var addr = results[0].address_components[i];
if (addr.types[0] == 'street_address')
$('#shop_street_address').val(addr.long_name);
if (addr.types[0] == 'route')
$('#shop_route').val(addr.long_name);
if (addr.types[0] == 'intersection')
$('#shop_intersection').val(addr.long_name);
}
$('#shop_formatted_address').val(results[0].formatted_address);
$('#shop_lat').val(marker.getPosition().lat());
$('#shop_lng').val(marker.getPosition().lng());
} else {
alert('No results found. Please revise the address or adjust the map marker.');
}
}
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T15:54:15.763",
"Id": "26275",
"Score": "1",
"body": "I was about to write up an answer, but then I noticed that inside the `$.map(results, ...` you're declaring these variables `var get_street_address, get_route, get_intersection;` but you're overwriting them in the `for` loop *(assuming the loop runs more than once)* so when the values are used in the returned object, you're only getting the latest values. Are you certain that's what you want?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T23:23:04.537",
"Id": "26326",
"Score": "0",
"body": "Actually I could have put it outside the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T23:25:11.887",
"Id": "26327",
"Score": "0",
"body": "Whether the declaration is inside or outside the loop won't make a difference. Variables are scoped to the function they're in. Either way, you're just overwriting the values in each iteration, and returning whatever the values were after the last iteration. To use all the values, you'd need to assign some sort of collection type to each variable, and add items to the collections in each iteration."
}
] |
[
{
"body": "<p>You could refactor this using a few arrays to avoid as much typing, but I think readability is paramount, and I don't see many ways for it to be more readable than what you have submitted.</p>\n\n<p>You could try using filter instead, but it will be over 3 times slower (most of the time this won't matter), (N times slower where N is the number of components):</p>\n\n<pre><code> function getValueOfAddressType(values, addressType) {\n var candidates = $.filter(values, function(i) {\n return values[i].types[0] === addressType;\n });\n return candidates[0].long_name;\n }\n\n\n$('#shop_formatted_address').autocomplete({\nThis bit uses the geocoder to fetch address values\nsource: function(request, response) {\n geocoder.geocode( {'address': request.term }, function(results, status) {\n response($.map(results, function(item) {\n\n return {\n label: item.formatted_address,\n value: item.formatted_address,\n lat: item.geometry.location.lat(),\n lng: item.geometry.location.lng(),\n street_address: getValueOfAddressType(item.address_components, 'street_address'),\n route: getValueOfAddressType(item.address_components, 'route'),\n intersection: getValueOfAddressType(item.address_components, 'intersection')\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T08:34:34.843",
"Id": "26393",
"Score": "0",
"body": "You are one crazy guy! I will use your approach. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T03:18:55.727",
"Id": "16182",
"ParentId": "16156",
"Score": "1"
}
},
{
"body": "<p>Got a little carried away, but here's my take. Haven't been able to test it though, so consider it more as a draft of a different approach, than a drop-in replacement (although if it just works, that's cool too).</p>\n\n<p>Basically, I've DRY'ed the code as much as I could, breaking the logic into several functions, so the final event handlers are as straightforward as possible. I also ran with the fact that you've ID'ed your elements with the names of the values you want them to display, just prefixed with <code>shop_</code>.</p>\n\n<pre><code>$(function () {\n // Get all the elements once and for all\n var elements = (function () {\n var elements = {};\n $.each([\"lat\", \"lng\", \"street_address\", \"route\", \"intersection\", \"formatted_address\"], function (id) {\n elements[id] = $(\"#shop_\" + id);\n });\n return elements;\n }());\n\n\n // Generic result-extraction function\n // Takes an array of results, and an array of the address component\n // types it should collect\n function extract(results, types) {\n // Internal function to extract the address components\n function extractAddressComponents(result) {\n var i, l, address, type, extracted = {};\n for( i = 0, l = result.address_components.length ; i < l ; i++ ) {\n address = result.address_components[i];\n type = address.types[0];\n // Uncomment this next line, if you want to avoid what user1689607 mentions in the comments\n // if( extracted[type] ) { continue }\n if( types.indexOf(type) !== -1 ) {\n extracted[type] = address.long_name;\n }\n }\n return extracted;\n }\n\n return $.map(results, function (result) {\n $.extend({\n label: result.formatted_address,\n value: result.formatted_address,\n lat: result.geometry.location.lat(),\n lng: result.geometry.location.lng(),\n latlng: result.geometry.location,\n formatted_address: result.formatted_address\n }, extractAddressComponents(result));\n });\n }\n\n // Function to set the values of the elements\n function populate(obj) {\n var id;\n for( id in elements ) {\n if( !elements.hasOwnProperty(id) ) { continue; }\n if( obj.hasOwnProperty(id) ) {\n elements[id].val(obj[id]);\n } else {\n elements[id].val(\"\");\n }\n }\n }\n\n // Center the map and marker\n function center(latlng) {\n if( latlng ) {\n marker.setPosition(latlng);\n map.setCenter(latlng);\n }\n }\n\n // A little convenience wrapping of the geocoding functions\n var geocode = (function () {\n function geocode(query, callback) {\n geocoder.geocode(query, function (results, status) {\n if( status === google.maps.GeocoderStatus.OK ) {\n callback(extract(results, [\"street_address\", \"route\", \"intersection\"]));\n } else {\n callback([]);\n }\n });\n }\n\n return {\n address: function (address, callback) { geocode({address: address}, callback); },\n reverse: function (latlng, callback) { geocode({latLng: latlng}, callback); }\n };\n }());\n\n // Hook it all up here\n elements.formatted_address.autocomplete({\n source: function(request, response) {\n response(geocode.address(request.term));\n },\n\n select: function (event, ui) {\n clearValue(); // Don't know what this one does, but I left it in\n delete ui.item.formatted_address;\n populate(ui.item);\n center(ui.item.latlng);\n },\n\n focus: function (event, ui) {\n center(ui.item.latlng);\n }\n });\n\n google.maps.event.addListener(marker, 'drag', function() {\n var latlng = marker.getPosition(),\n results = geocode.reverse(latlng),\n result;\n\n clearValue(); // Don't know what this one does, but I left it in\n\n if( results.length ) {\n result = results[0];\n $.extend(result, {\n lat: latlng.lat(),\n lng: latlng.lng()\n });\n populate(result);\n } else {\n alert('No results found. Please revise the address or adjust the map marker.');\n }\n });\n});\n</code></pre>\n\n<p>In the end there's more code, but hopefully it'll seem cleaner, and be more maintainable. And there's very, very little repetition, which I believe is what you originally asked for (as I said, I got carried away).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T14:06:30.000",
"Id": "16201",
"ParentId": "16156",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "16182",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T15:37:42.097",
"Id": "16156",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"geospatial",
"google-maps"
],
"Title": "Address geocoder"
}
|
16156
|
<p>I was just trying to make an alternate Ajax watermark from "insert date" (first mode) to "mm/dd/yyyy" (second mode). After some trial and error, I successfully implemented a solution using JavaScript.</p>
<p>How can I improve this script functionality?</p>
<p><strong>JavaScript:</strong></p>
<pre><code>var original = "insert date";
var alternate = "mmddyyyy";
var countalerted = 0;
var txt = "";
var intird = 0;
if (intird == 0) {
intrId = setInterval(function () { alterWaterMarkForDateTBX() }, 1000);
}
function SetIntervalTBX() {
setInterval(function () { alterWaterMarkForDateTBX() }, 1000);
}
function alterWaterMarkForDateTBX() {
var d = new Date();
var t = d.toLocaleTimeString();
if (countalerted < 4) {
if (countalerted % 2 == 0) {
document.forms["form1"].elements["TBXinsertDate"].value = original;
}
else {
document.forms["form1"].elements["TBXinsertDate"].value = alternate;
}
countalerted++;
}
else {
window.status = intrId;
clearInterval(intrId);
// document.forms["form1"].elements["TBXinsertDate"].value = original;
}
}
var wasFocused = false;var wasBlur = false;
function Focus(objname, waterMarkText) {
wasFocused = true;
if (wasBlur == false) {
obj = document.getElementById(objname);
if (obj.value == waterMarkText) {
obj.value = "";
obj.className = "NormalTextBox";
if (obj.value == original || obj.value == alternate || obj.value == "" || obj.value == null) {
obj.style.color = "black";
}
}
}
}
//i added "__/__/____" for the value of the ajax MaskEdit
function Blur(objname, waterMarkText) {
wasBlur = true;
var alternateWM1 = "insert date";
var alternateWM2 = "mm/dd/yyyy";
obj = document.getElementById(objname);
if (obj.value == "" || obj.value == "__/__/____") {
obj.value = waterMarkText;
obj.className = "WaterMarkedTextBox";
}
else {
obj.className = "NormalTextBox";
}
if (obj.value == original || obj.value == alternate || obj.value == "" || obj.value == null || obj.value == "__/__/____") {
obj.style.color = "gray";
if (wasFocused == true) {
SetIntervalTBX();
}
}
}
</code></pre>
<p><strong>ASPX / HTML</strong></p>
<pre><code><form id="form1" runat="server">
<asp:TextBox ID="TBXinsertDate" runat="server"
ToolTip="date Box" Width="79px"
onfocus="Focus(this.id, this.value)"
onblur="Blur(this.id, this.value)" >
</asp:TextBox>
</form>
</code></pre>
|
[] |
[
{
"body": "<p>I think you're trying to create a simple placeholder.</p>\n\n<p>A placeholder adds default text to an emtpy input field.</p>\n\n<p>The <a href=\"http://www.w3schools.com/html5/att_input_placeholder.asp\" rel=\"nofollow\">placeholder</a> attribute is introduced in HTML 5.</p>\n\n<h2>Example 1: (<a href=\"http://jsfiddle.net/kWunt/\" rel=\"nofollow\">DEMO</a>)</h2>\n\n<pre><code><input type=\"text\" placeholder=\"Please fill this field\" />\n</code></pre>\n\n<h2>Example 2: (<a href=\"http://help.dottoro.com/external/examples/ljgugboo/placeholder_3.htm\" rel=\"nofollow\">DEMO</a>)</h2>\n\n<blockquote>\nThis cross-browser example implements the functionality of the placeholder property:\n</blockquote>\n\n<p>Take from <a href=\"http://help.dottoro.com/ljgugboo.php\" rel=\"nofollow\">http://help.dottoro.com/ljgugboo.php</a> </p>\n\n<pre><code><head>\n <script type=\"text/javascript\">\n function ClearPlaceHolder (input) {\n if (input.value == input.defaultValue) {\n input.value = \"\";\n }\n }\n function SetPlaceHolder (input) {\n if (input.value == \"\") {\n input.value = input.defaultValue;\n }\n }\n </script>\n</head> \n<body>\n <input type=\"text\" value=\"Please fill this field\" onfocus=\"ClearPlaceHolder (this)\" onblur=\"SetPlaceHolder (this)\" /> \n</body>\n</code></pre>\n\n<p>Lastly, I would only have one type of placeholder text for each input element. So use <code>insert date</code> or <code>mm/dd/yyyy</code> as placeholder, but not both.</p>\n\n<p>Extra Info:\nTry out <a href=\"http://www.w3schools.com/html/html5_form_input_types.asp\" rel=\"nofollow\">Input type=date</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-06T22:15:12.423",
"Id": "26461",
"Score": "0",
"body": "thanks for your answer though on my server i can't implement html5. what i was asking is about this code of JavaScript as it is now , it's supported in current VS 2010 , and in current window server (2003) iis6 , the issue here is a standart watermark turned into a dual mode , one mode is presenting the value needed to insert into the text box and second mode tells you in which format., the interval(1 sec each flip) is switching between modes. i was asking if there's a known version implemented already, if not.. then how's my (not so professional javascripting) in this code doing? is it fine?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-06T19:49:56.120",
"Id": "16273",
"ParentId": "16159",
"Score": "1"
}
},
{
"body": "<p>Some notes:</p>\n\n<ol>\n<li><p>Think about reusability. Your code integrates the field names directly into the functions. Same goes for some of your choices of function names (<code>alterWaterMarkForDateTBX</code>). This makes it difficult to reuse next time you need this function. </p></li>\n<li><p>You appear to be mixing ideas. You set a class name sometimes, set the text color other times. I'm not sure if this was intentional but I just changed it all to class names.</p></li>\n<li><p>You had some dead variables. Stuff like this just make it harder to edit in the future. Remove them.\n<code>var d = new Date(); var t = d.toLocaleTimeString();</code></p></li>\n<li><p>You are checking to make sure the field had focus before it blurred (and vice versa). And then Not sure what the purpose of that is. </p></li>\n<li><p>Your focus and blur events pass in the textbox name and the textbox value (as <code>watermarkText</code>. Then you check the value against a couple of other values and if it matches set the textbox back to <code>watermarkText</code>. This will never accomplish anything and is confusing. Just pass in the textbox itself.</p></li>\n<li><p>Think about non-intrusive javascript. It is easier to maintain. Notice how I added the blur and focus events to the field through javascript instead of directly in the html.</p></li>\n<li><p>You should try to avoid global objects. Look into putting this entire code block into an object. The problem you will face is what if you have two fields on the same form that need this functionality. The changes I have made below will go a long way in helping but the global interval and global counter will conflict with one another and it will not work. </p></li>\n</ol>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I was interested in this problem. So I extended my code.</p>\n\n<ol>\n<li><p>I moved the main work into a function object. This can now be called using a constructor which passes in the text box. This also allows for multiple textboxes using this even on the same page.</p></li>\n<li><p>I added an options object to the parameters. This will allow you to change the functionality of the script without changing the actual code. This allows for reusability without needing to modify the code (open-closed principle). This is also a common technique used in many of the JS frameworks (jQuery, mooTools, etc..)</p></li>\n</ol>\n\n<p>Styles:</p>\n\n<pre><code>.NormalTextBox {\ncolor = \"black\";\n}\n.WaterMarkedTextBox {\ncolor = \"grey\";\n}\n</code></pre>\n\n<p>Script:</p>\n\n<pre><code> var MultiWatermark = function (obj, options) {\n\n var defaultOptions = {\n // These variables can be changed to alter functionality using the passed in options object\n watermarkVals: [\"insert date\", \"mmddyyyy\"], // all watermark values.\n totalIterations: 2, // how many times to go through watermark Array.\n watermarkClassName: \"WaterMarkedTextBox\",\n normalClassName: \"NormalTextBox\",\n changeDelay: 1000, // in milliseconds\n extraValsToCheck: ['', null]// \n }\n\n //merge options with defaultOptions\n for (var property in defaultOptions) {\n if (!options.hasOwnProperty(property)) {\n options[property] = defaultOptions[property];\n }\n }\n\n // local variables (do not change)\n var textBox = obj;\n var iterationCounter = 0;\n var itemCounter = 0;\n var intrId;\n\n var startWatermark = function () {\n itemCounter = 0; iterationCounter = 0; // resets for after blur\n intrId = setInterval(function () { alterWaterMark() }, options.changeDelay);\n }\n\n var stopWatermark = function () {\n clearInterval(intrId);\n }\n\n var alterWaterMark = function () {\n\n if (iterationCounter < options.totalIterations) {\n\n textBox.value = options.watermarkVals[itemCounter];\n itemCounter += 1;\n if (itemCounter == options.watermarkVals.length) {\n itemCounter = 0;\n iterationCounter += 1;\n }\n }\n else {\n stopWatermark();\n }\n\n }\n\n var isWatermarkValue = function (val) {\n\n var i = options.watermarkVals.length;\n while (i--) {\n if (options.watermarkVals[i] === val) {\n return true;\n }\n }\n // value is not in watermark array, so check secondary values.\n i = options.extraValsToCheck.length;\n while (i--) {\n if (options.extraValsToCheck[i] === val) {\n return true;\n }\n }\n }\n\n var setClass = function () {\n textBox.className = isWatermarkValue(textBox.value) ? options.watermarkClassName : options.normalClassName;\n }\n\n var focusEvent = function () {\n\n stopWatermark();\n if (isWatermarkValue(textBox.value)) {\n textBox.value = \"\";\n }\n setClass()\n }\n\n var blurEvent = function () {\n\n if (isWatermarkValue(textBox.value)) {\n startWatermark();\n }\n setClass();\n\n }\n\n var initWatermark = function () {\n setClass();\n textBox.onfocus = focusEvent;\n textBox.onblur = blurEvent;\n startWatermark();\n }\n\n\n initWatermark();\n}\n</code></pre>\n\n<p>Body:</p>\n\n<pre><code><form id=\"form1\" runat=\"server\">\n <input ID=\"TBXinsertDate\" ToolTip=\"date Box\" Width=\"79px\" />\n <input ID=\"Text1\" ToolTip=\"date Box\" Width=\"79px\" />\n </form>\n\n<script>\n\n\nvar dateOptions = {\n // These variables alter functionality, the main script will use the defaults of any options not included here \n watermarkVals: [\"insert date\", \"mmddyyyy\", \"mm/dd/yyyy\"], // all watermark values.\n totalIterations: 4,\n changeDelay: 500, // in milliseconds\n extraValsToCheck: ['', null, '__/__/____', 'test']//\n}\nnew MultiWatermark(document.forms[\"form1\"].elements[\"TBXinsertDate\"], dateOptions);\nnew MultiWatermark(document.forms[\"form1\"].elements[\"Text1\"], dateOptions);\n</script>\n</body>\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T21:10:16.863",
"Id": "26541",
"Score": "0",
"body": "hey nickless jscripter , i am glad to see you've changed my code . i did try b4 your new \"Edit\" something was wrong on blur , now i can see you've updated it again so i will check on it , i hope you'll still be around later on !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T22:59:27.327",
"Id": "26551",
"Score": "0",
"body": "i checked your code , it works just fine, then i played with it (trying to perfect it even more) to make it work 1) on `documentreadystate`(so no need for <scrptags> at the end you would just have it layed among rest of js. 2) to send parameter for the target textbox 3) to make it as saperated js file and then just call function ondocumentready( executTheMultyWatermarkOn(tbxID);) i have the ready js without the need for Jquery i wanted to send you it's code if you like , and how do i contact you (mail ...skype)? **P.S** Your Js Coding Rocks !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-09T00:09:23.790",
"Id": "26560",
"Score": "0",
"body": "1) I left that off for simplicity sake. Putting the scripts at the bottom does the same thing (although could be considered messy. You could also just put everything in a separate file and then include them at the bottom of the page. 2) That is what I am doing at the bottom of the page. new MultiWatermark({textbox}, {options}) sets up the field automatically. 3) always a good idea to move scripts to external files. Thanks for the words of encouragement. :) My contact info is in my profile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-09T02:26:21.440",
"Id": "26564",
"Score": "0",
"body": "i am going to post your version but with my reconstracted version of your version (: soon i hope , cleaning up the code , meanwhile i was checking on how to avoid readystate via `defer` script-attribute and also how to include a `.js` file from a `.js` file (cool stuff) i hope you'll be interested although i did 'let you off the hook' you are already rewarded (L:"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-07T05:02:36.150",
"Id": "16292",
"ParentId": "16159",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "16292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:07:09.687",
"Id": "16159",
"Score": "3",
"Tags": [
"javascript",
"performance",
"datetime",
"asp.net",
"ajax"
],
"Title": "Dual-mode JavaScript textbox watermark"
}
|
16159
|
<p>I am calculating discounts based on a quantity after 6. </p>
<p>Is there a cleaner way to do this:</p>
<pre><code>$leg_directory_discount = array(
6 => .50,
7 => .50,
8 => .50,
9 => .50,
10 => .50,
11 => 1,
12 => 1,
13 => 1,
14 => 1,
15 => 1,
16 => 1,
17 => 1,
18 => 1,
19 => 1,
20 => 1,
21 => 1.5,
22 => 1.5,
23 => 1.5,
24 => 1.5,
25 => 1.5,
26 => 1.5,
27 => 1.5,
28 => 1.5,
29 => 1.5,
30 => 1.5,
31 => 1.5,
32 => 1.5,
33 => 1.5,
34 => 1.5,
35 => 1.5,
36 => 1.5,
37 => 1.5,
38 => 1.5,
);
</code></pre>
<p>edit: The max and min values of the discounts never change. Here is how I'm calculating the discount and arriving at the final price:</p>
<pre><code>if($v[0]['leg_discount'] == '1' && $v[0]['qty'] >= 6){
$discount = $qty * $leg_directory_discount[$qty];
$price = $price - $discount;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T15:59:58.853",
"Id": "26281",
"Score": "3",
"body": "What have tried? Can you add more details?"
}
] |
[
{
"body": "<p>Some simple logic will save you from all that (error-prone) writing. For instance:</p>\n\n<pre><code>if ($qty >= 6)\n{\n if ($qty >= 21)\n $leg_directory_discount = 1.5;\n elseif ($qty >=11)\n $leg_directory_discount = 1.0;\n else\n $leg_directory_discount = 0.5;\n}\nelse\n $leg_directory_discount = 0.0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:26:44.353",
"Id": "26285",
"Score": "0",
"body": "Overly complicated, I'd say. How do you integrate a new discount for three products at 0.2 easily?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:04:31.663",
"Id": "16162",
"ParentId": "16161",
"Score": "0"
}
},
{
"body": "<p>You could use a switch statement as well: </p>\n\n<pre><code>switch (true) {\n case ($price <=5):\n $discount = 0.0;\n break;\n case ($price <= 10):\n $discount = 0.5;\n break;\n case ($price <= 20):\n $discount = 1.0;\n break;\n default:\n $discount = 1.5;\n break;\n}\n</code></pre>\n\n<p>Also your final price could be reduced to <code>$price = $price * (100 - $discount) / 100;</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:18:51.047",
"Id": "26286",
"Score": "0",
"body": "Your switch statement looks bogus. Shouldn't it be at least `switch (true)` if you want to evaluate on every case line. You might get along because $price evaluates to true most of the time. I would try to avoid switch nonetheless - makes code overcomplicated in the long run."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:23:09.240",
"Id": "26287",
"Score": "0",
"body": "@Sven: your probably right, edited per your comment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:14:28.753",
"Id": "16164",
"ParentId": "16161",
"Score": "0"
}
},
{
"body": "<p>I like the idea of putting the discount steps into an array, but stating a discount for every possible quantity seems too much.</p>\n\n<pre><code>$leg_directory_discount = array(\n 0 => 0,\n 6 => .50,\n 11 => 1,\n 21 => 1.5,\n);\n</code></pre>\n\n<p>This is the discount configuration - can later be stored in a config file or database.</p>\n\n<p>This function gets the discount to be used:</p>\n\n<pre><code>function getDiscount($qty, $leg_directory_discount) {\n $return = 0;\n foreach ($leg_directory_discount as $amount => $discount) {\n if ($qty >= $amount) {\n $return = $discount;\n }\n }\n return $discount;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T16:24:05.477",
"Id": "16165",
"ParentId": "16161",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "16162",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T15:58:45.380",
"Id": "16161",
"Score": "0",
"Tags": [
"php"
],
"Title": "Building array keys using a span of numbers for like values"
}
|
16161
|
<p><strong>The Problem</strong></p>
<p>I have a cursor that I am trying to replace (perhaps unnecessarily) in an attempt to clean up a stored procedure. Essentially what it is doing is counting each note for each member in a temp table and then assigning each of those notes a sequential value into the field <code>NOTE_COUNTER (int)</code> of the temp table. Here is the original code for it with the variables:</p>
<pre><code>@lUPI_current CHAR(32),
@lCASE_SEQ_current INT,
@lDIFF_ENCOUNTER_DATE INT,
@lcounter INT
SET @lUPI_current = ''
SET @lCASE_SEQ_current = ''
SET @lDIFF_ENCOUNTER_DATE = 0
SET @lcounter = 0
DECLARE CURSOR_NOTE_COUNTER CURSOR FOR
SELECT
MEMBER,
CASE_SEQ,
ENCOUNTER_DATE
FROM
#TMP_NOTES
WHERE
TOTAL_CALLS > 1
ORDER BY
MEMBER,
CASE_SEQ,
ENCOUNTER_DATE
OPEN CURSOR_NOTE_COUNTER
FETCH NEXT FROM CURSOR_NOTE_COUNTER
INTO
@lUPI_current,
@lCASE_SEQ_current,
@lDIFF_ENCOUNTER_DATE
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @lcounter = (
SELECT
MAX(NOTE_COUNTER)
FROM
#TMP_NOTES
WHERE
MEMBER_UPI = @lUPI_current
AND CASE_SEQ = @lCASE_SEQ_current
)
UPDATE #TMP_NOTES
SET
NOTE_COUNTER = @lcounter + 1
FROM #TMP_NOTES
WHERE
MEMBER_UPI = @lUPI_current
AND CASE_SEQ = @lCASE_SEQ_current
AND DIFF_ENCOUNTER_DATE = @lDIFF_ENCOUNTER_DATE
FETCH NEXT FROM CURSOR_NOTE_COUNTER
INTO
@lUPI_current,
@lCASE_SEQ_current,
@lDIFF_ENCOUNTER_DATE
END
</code></pre>
<p><strong>What I Have Tried</strong></p>
<p>I tried replacing this with a CTE because of the notion that cursors should be avoided in favor of working on sets of data. Here was my attempt at that, the stumbling block being the ambiguity of the column names since it is working on the same table.</p>
<pre><code>WITH RecordsBeingUpdated AS
(
SELECT
MEMBER_UPI,
CASE_SEQ,
DIFF_ENCOUNTER_DATE,
ROW_NUMBER() OVER (PARTITION BY MEMBER_UPI, CASE_SEQ, DIFF_ENCOUNTER_DATE ORDER BY DIFF_ENCOUNTER_DATE ASC) AS RowNum
FROM
#TMP_NOTES
WHERE
TOTAL_CALLS > 1
)
UPDATE #TMP_NOTES
SET
NOTE_COUNTER = R.RowNum
FROM
RecordsBeingUpdated AS R
WHERE
MEMBER_UPI = R.MEMBER_UPI
AND CASE_SEQ = R.CASE_SEQ
AND DIFF_ENCOUNTER_DATE = R.DIFF_ENCOUNTER_DATE
</code></pre>
<p>Please tell me if there is a cleaner way to doing this. I am grateful for any time that the community can provide.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:22:22.833",
"Id": "26304",
"Score": "0",
"body": "Is it possible for there to be multiple records keyed by MEMBER_UPI, CASE_SEQ, DIFF_ENCOUNTER_DATE? Just making sure I understand the requirements correctly. So, you would like to see NOTE_COUNTER increment within a grouping of M_U, C_S, and D_E_D, then restart for a new value. So you might have a sequence in NOTE_COUNTER like 1,2,3,1,1,1,2,3,4,..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:27:06.633",
"Id": "26305",
"Score": "0",
"body": "If you are concerned about column ambiguity between #TMP_NOTES and RecordsBeingUpdated, you could alias the columns in RecordsBeingUpdated. (e.g.: SELECT MEMBER_UPI AS MU, ...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:31:49.860",
"Id": "26306",
"Score": "0",
"body": "In short, yes there may be multiple values. What I'm targeting is to take all of the CASE_SEQ values of each MEMBER_UPI and number them sequentially based off of the DIFF_ENCOUNTER_DATE. When there is a new CASE_SEQ for the same MEMBER_UPI, the numbering for NOTE_COUNTER should commence anew."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:47:13.623",
"Id": "26307",
"Score": "0",
"body": "In that case, shouldn't the DIFF_ENCOUNTER_DATE not be in the partition?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:49:49.453",
"Id": "26309",
"Score": "0",
"body": "@Griffin - Wow, really not one of my brighter moments haha. Much obliged, taking D_E_D out of the Partition worked. If you post as an answer and I'll accept."
}
] |
[
{
"body": "<p>So, you can simplify the CTE with some SQL magic:</p>\n\n<pre><code>WITH RecordsBeingUpdated AS \n( \n SELECT \n NOTE_COUNTER,\n MEMBER_UPI, \n CASE_SEQ, \n DIFF_ENCOUNTER_DATE, \n ROW_NUMBER() OVER (PARTITION BY MEMBER_UPI, CASE_SEQ ORDER BY DIFF_ENCOUNTER_DATE ASC) AS RowNum \n FROM \n #TMP_NOTES \n WHERE \n TOTAL_CALLS > 1 \n) \n\nUPDATE RecordsBeingUpdated\nSET NOTE_COUNTER = RowNum \n</code></pre>\n\n<p>Essentially, the virtual table built for the CTE has direct reference back to the concrete tables in the selection. This means you can update the CTE directly and SQL will update the corresponding concrete table within, provided the target table is the FROM table (not a joined) and there is no chance of ambiguity in what needs to be updated.</p>\n\n<p>(Removed DIFF_ENCOUNTER_DATE from partition per comments).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:54:48.937",
"Id": "26310",
"Score": "0",
"body": "Many thanks for the thorough explanation, would up-vote if I were able to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:57:46.513",
"Id": "26311",
"Score": "0",
"body": "Thank you. Also, to answer your title question - yes, please replace all cursors when possible. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T19:52:11.247",
"Id": "16170",
"ParentId": "16166",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "16170",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:06:42.820",
"Id": "16166",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Is it necessary to replace this cursor in SQL Server 2005?"
}
|
16166
|
<p>I need to calculate checksum using 16-bit ones' complement addition:</p>
<pre><code>while(byte>0) //len = Total num of bytes
{
Word = ((Buf[i]<<8) + Buf[i+1]) + Checksum; //get two bytes at a time and add previous calculated checsum value
Checksum = Word & 0x0FFFF; //Discard the carry if any
Word = (Word>>16); //Keep the carryout for value exceeding 16 Bit
Checksum = Word + Checksum; //Add the carryout if any
len -= 2; //decrease by 2 for 2 byte boundaries
i += 2;
}
Checksum = (unsigned int)~Checksum;
</code></pre>
<p>The above code works fine, and if I understood the concept well (to add 16 bits), add the carry if any and then take the compliment.</p>
<p>Are there any improvements or corrections?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:05:06.537",
"Id": "420238",
"Score": "1",
"body": "What are the types of `Word`, `Checksum` and `Buf`? It looks like `Word` must be a `uint32_t`, `Checksum` a `uint16_t` and `Buf` a `uint8_t*`, buf the information really ought to be included in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:06:05.250",
"Id": "420264",
"Score": "1",
"body": "You'd get better reviews if you provided at least a whole, compilable function."
}
] |
[
{
"body": "<p>If the packet size is less than 32k words, then you do not need to add the carry until the end:</p>\n\n<pre><code>while(byte>0) //len = Total num of bytes\n{\n Checksum = ((Buf[i]<<8) + Buf[i+1]) + Checksum; //get two bytes at a time and add previous calculated checsum value\n\n len -= 2; //decrease by 2 for 2 byte boundaries\n i += 2;\n}\n\n Checksum = (Checksum>>16) + Checksum; //Add the carryout\n\n Checksum = (unsigned int)~Checksum;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T20:00:32.517",
"Id": "26312",
"Score": "0",
"body": "Ok I understand why it could be done at the end only, but I didnt understand 32k words thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T21:18:41.463",
"Id": "26319",
"Score": "0",
"body": "If you have more than 32k 16-bit words, you can overflow a 32 bit integer when you add them up. With fewer than 32k words, you cannot overflow."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:49:11.970",
"Id": "16168",
"ParentId": "16167",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "16168",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T17:45:18.277",
"Id": "16167",
"Score": "5",
"Tags": [
"c",
"bitwise"
],
"Title": "16 bit checksum calculation"
}
|
16167
|
<pre><code>/* Infinite Scroll Pagination with a Wookmark layout
*
* Requires: jQuery, Wookmark
*/
var myApp = myApp || {};
;(function(myApp,$){
var WookmarkPagination = function(elem, options){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
};
WookmarkPagination.prototype = {
defaults: {
url: '',
page: 2,
per_page: 5,
template: '',
scroll: true,
item: ".item",
items: ".items",
loader_image: ''
},
fetchReady: {
status: true
},
/**
* Initiate app. Bind the scroll event and onScroll function to the document.
*
* @return this
*/
init: function(){
var _this = this;
_this.config = $.extend({}, _this.defaults, _this.options);
var loader = '<div id="wookmark-pagination-loader"><img src="'+_this.config.loader_image+'" alt="Loading..." /></div>';
// Set loader
$(loader).appendTo("body").hide();
// Build wookmark layout
wookmark_handler = this.$elem.find(_this.config.item);
wookmark_handler.wookmark({
container: _this.$elem,
offset: 15,
itemWidth: 160,
autoResize: true
});
if(_this.config.scroll){
$(document).bind('scroll', function(){
_this.onScroll();
});
}
return _this;
},
/**
* Rebuild Wookmark layout
*
* @return void
*/
refreshLayout: function(){
var _this = this;
var opt = _this.config;
//console.log(wookmark_handler);
// Rebuild wookmark positions
if(wookmark_handler) wookmark_handler.wookmarkClear();
wookmark_handler = _this.$elem.find(_this.config.item);
// Initialize Wookmark to build layout container
wookmark_handler.wookmark({
container: _this.$elem,
offset: 15,
itemWidth: 160,
autoResize: true
});
},
/**
* Fetches the JSON from the server. On success rebuilds Wookmark positioning.
*
* @return the JSON object
*/
fetch: function(){
var _this = this;
var opt = _this.config;
// If no other getJSON is being processed continue
if(_this.fetchReady.status){
// Block other requests
_this.fetchReady.status = false;
// Show loader
$("#wookmark-pagination-loader").fadeIn();
// Fetch Data
return $.getJSON(opt.url,{
page: opt.page,
per_page: opt.per_page
})
.success(function(data){
// Each data item is wrapped in a template and appended to the page.
$.each(data, function(i, item){
_this.$elem.find(_this.config.items).append(Mustache.to_html(opt.template, item.item));
});
// Set next page number for next request.
opt.page += 1;
_this.refreshLayout();
})
// TODO: setup error catching and show a user there was a problem with the request
//.error(function(data, response){})
.complete(function(data){
// Allow other getJSON requests
_this.fetchReady.status = true;
// Hide loader
$("#wookmark-pagination-loader").fadeOut();
});
}
},
/**
* Checks if the scroll position has reached the bottom, then runs the fetch function
*
* @return void
*/
onScroll: function() {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
if(closeToBottom) {
this.fetch();
}
}
};
WookmarkPagination.defaults = WookmarkPagination.prototype.defaults;
$.fn.wookmark_pagination = function(options) {
return this.each(function() {
new WookmarkPagination(this, options).init();
});
};
myApp.WookmarkPagination = WookmarkPagination;
})(myApp,jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T14:48:38.050",
"Id": "26688",
"Score": "0",
"body": "What is a Wookmark layout?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-08T12:04:38.417",
"Id": "29227",
"Score": "0",
"body": "Looks okay as per my review, no problem at all.. it will be better if you can give us a sample how actually you are using"
}
] |
[
{
"body": "<p>The code looks pretty good, but here are a couple suggestions:</p>\n\n<ul>\n<li>The semicolon at the top is unnecessary: <code>;(function(myApp,$){</code></li>\n<li>You use <code>_this</code> in many places where <code>this</code> would work:\n<ul>\n<li>Consider Function.bind (<a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow\">see MDN</a>, only works on modern browsers)</li>\n<li>This very much depends on personal style</li>\n</ul></li>\n<li><p>This is a little confusing. I don't write jQuery much, but it isn't clear what the first <code>this</code> is referring to (and the second this has a different meaning than the one above, which is also confusing):</p>\n\n<pre><code>$.fn.wookmark_pagination = function(options) {\n return this.each(function() {\n new WookmarkPagination(this, options).init();\n });\n};\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T00:18:09.217",
"Id": "30086",
"Score": "0",
"body": "`this` references `jQuery` iirc. Its standard for this type of code. Definitely agree there is no need for both `this` and `_this` in most places and is inconsistent."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T23:06:36.070",
"Id": "18864",
"ParentId": "16183",
"Score": "2"
}
},
{
"body": "<p>Use jslint to fix all warnings . It is not necessary, but sometimes helpful.\nThere are some bad things, like using <code>var</code>s without declaration and so on, and also bad formatting (can use jsmin to format JavaScript). I'd also add <code>$(document)</code> and <code>$(window)</code> as argument to plugin and use them inside plugin.</p>\n\n<p>There are also many common thing that you repeat:</p>\n\n<pre><code>$(\"#wookmark-pagination-loader\").fadeOut();\n</code></pre>\n\n<p>Push <code>$(\"#wookmark-pagination-loader\")</code> to plugin like argument or cache it in <code>var</code> and make method, that will show and hide loading.</p>\n\n<p>Also, each block of code after comment you can substitute with a function call:</p>\n\n<pre><code>// Build wookmark layout\nwookmark_handler = this.$elem.find(self.config.item);\n wookmark_handler.wookmark({\n container : self.$elem,\n offset : 15,\n itemWidth : 160,\n autoResize : true\n});\n\nfunction builtWookmarkLayout() {\n ... //do things here\n}\n</code></pre>\n\n<p>Use some hints to make jQuery faster. Cache requests to DOM tree in variables, use pure JavaScript sometimes.</p>\n\n<pre><code>var loadingContainer = $(document.getElementById('wookmark-pagination-loader'));\nshowLoading = function () {\n this.loadingContainer.fadeIn();\n}\n</code></pre>\n\n<p>For old browser, add an explicit function <code>create</code> like:</p>\n\n<pre><code>if (typeof Object.create !== 'function') {\n Object.create = function (obj) {\n function F() {};\n F.prototype = obj;\n return new F();\n }\n}\n</code></pre>\n\n<p>You also use objects with exactly one field, so substitute them with <code>var</code>.</p>\n\n<pre><code>fetchReady : {\n status : true\n}\n</code></pre>\n\n<p>Use explicit comparisons:</p>\n\n<pre><code>if (self.fetchReady.status === true) {...\n</code></pre>\n\n<p>I can find much more \"clever\" advice. But in my opinion, it is nit-picking. It works, it's readable, it's compact, it's OK.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T04:46:52.077",
"Id": "27332",
"ParentId": "16183",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T03:28:28.383",
"Id": "16183",
"Score": "8",
"Tags": [
"javascript",
"jquery",
"pagination"
],
"Title": "Infinite scroll pagination with a Wookmark layout"
}
|
16183
|
<p>First off I would like to state that this is a homework assignment. However, I am not looking for you to complete anything for me. I code I am posting is the completed homework assignment. However, since this is my first time using C++ I was curious if there might have been a better method to accomplish the same task.</p>
<pre><code>/*
* PROJECT: Week 1 - Homework (Circle Calculations)
* VERSION: 0.0.0 as of 201210104
*
* DESC:
* In this homework assignment you will create a program that
* will calculate the area and circumference of a circle.
*
*/
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<cmath>;
bool main(){
const double PI = 3.14;
double radius;
double circumference;
double area;
// display backing
cout << "In order to determine a circle's circumference and area the";
cout << "\nradius is required." << endl;
// display question
cout << "\nWhat is the radius?" << endl;
cin >> radius; // except input
// do the math
circumference = PI * 2 * radius; // circumference of a circle
area = PI * pow(radius,2.0); // area of a circle
// display answer
cout << "\nA circle with a radius of " << radius << endl;
cout << "has a circumference of: " << circumference << endl;
cout << "has an area of: " << area << "\n" << endl;
system("pause");
return true;
}
</code></pre>
<p>Here is the outcome of all changes I have made to the code above. I was able to solve how to handle an input other than of the the required data type.</p>
<pre><code>/*
* PROJECT: Week 1 - Homework (Circle Calculations)
* VERSION: 1.0.0 as of 201210106
*
* DESC:
* In this homework assignment you will create a program that
* will calculate the area and circumference of a circle.
*
*/
#include <cmath>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
bool GetInt(float & n)
{
string str;
getline(cin,str);
stringstream buffer(str);
buffer >> n;
if (!buffer)
{
cout << "non numerical data!" << endl;
return false;
}
if (!buffer.eof())
{
cout << "buffer not consumed!" << endl;
return false;
}
return true;
}
int main(){
const float PI = acos(-1);
float radius;
float circumference;
float area;
// display backing
cout << "In order to determine a circle's circumference and area the";
cout << "\nradius is required." << endl;
// display question
cout << "\nWhat is the radius? (type float)" << endl;
while (true){
cout << "enter a floating point number (0 to quit): ";
if (!GetInt(radius)){
cout << "\nyou did not enter a floating point number..." << endl;
}
else{
if (radius==0)
{
cout << "ok, bye!" << endl;
break;
}
// do the math
circumference = PI * 2 * radius; // circumference of a circle
area = PI * pow(radius,2.0); // area of a circle
// display answer
cout << "\nA circle with a radius of " << radius << endl;
cout << "has a circumference of: " << circumference << endl;
cout << "has an area of: " << area << endl << endl;
}
}
/*
using while loop to catch unexpected data types being
submitted, issue and error message, and ask for another
value to be submitted
while(!(cin >> radius)){// loop if not cin returns false
// display the error message
cout << "\nThat is not a floating point number." << endl;
cout << "Please enter a value that is a floating point number." << endl;
// display question again
cout << "\nWhat is the radius? (type float)" << endl;
// cin.clear() - reset the error control state
cin.clear();
/*
cin.ignore() - clear out last input sequence.
numeric_limits<streamsize>::max() - returns the max length of the
cin streamsize.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
*/
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>You've done it well bro. Just a little comment:</p>\n\n<p>+) please remove the semi-colon </p>\n\n<pre><code>#include<cmath>;\n</code></pre>\n\n<p>+) put all <code>#include</code> stuff at the start of program before importing anything from namespace.</p>\n\n<p>+) <code>int main()</code> and <code>return 0;</code> instead of yours. It's standard after all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T20:18:11.387",
"Id": "26419",
"Score": "3",
"body": "Don't need a `return 0;`. In main() (in C++ not C) no return means the compiler plants a `return 0` automatically. Thus if there is no way for your program to fail (as in this case) the standard is not to put a return statement (an indication to the maintainer it will not fail). Only have a specific return if there is a possibility of failure."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T06:12:48.163",
"Id": "16186",
"ParentId": "16185",
"Score": "0"
}
},
{
"body": "<p>Extremely good for a first time at C++! A few things though:</p>\n\n<ul>\n<li><code>#include<iostream></code> should be <code>#include <iostream></code></li>\n<li>Same with <code>#include<cmath></code></li>\n<li>Also, no need for the <code>;</code> after the <code>cmath</code> include</li>\n<li><code>main</code> does not have a return type of <code>bool</code>. <a href=\"http://en.wikipedia.org/wiki/Main_function_%28programming%29#C_and_C.2B.2B\" rel=\"nofollow noreferrer\">See this</a> or <a href=\"https://stackoverflow.com/q/204476/14065\">this</a>.</li>\n<li>I would put the <code>using</code> declarations after all includes. It should be safe, but no need to pull things into the global namespace until the last minute.</li>\n<li><code>cin >> radius;</code> doesn't check for failure or success (see note below)</li>\n<li>In your final output, you used all <code>endl</code> and then have a random <code>\\n</code>\n\n<ul>\n<li><code>\\n</code> and <code>endl</code> are not functionality-wise equivalent. In this situation though, that difference is not going to matter. I suggest you either stick with all <code>endl</code> or have all <code>\\n</code> and then a final <code>endl</code> (I would probably use all <code>endl</code> just for the consistency). <code>endl</code> is <a href=\"https://stackoverflow.com/a/214076/567864\">essentially equivalent</a> to writing a newline and flushing</li>\n</ul></li>\n<li>I'm not a fan of <code>system(\"pause\");</code> \n\n<ul>\n<li>It's system dependent. (The 'pause' part, not the <code>system</code> part.)</li>\n<li>And, in my opinion, your program has no reason to remain running once it's done. Leave it up to the user whether or not to leave the prompt open.</li>\n<li>Additionally, though it seems like <code>system(\"pause\");</code> is a quick little solution, it may be better to just block on reading any character if you're determined to leave the application running. <a href=\"http://en.cppreference.com/w/cpp/utility/program/system\" rel=\"nofollow noreferrer\"><code>system</code></a> seems a bit overkill.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Note about <code>cin >> radius;</code></p>\n\n<p>The typical approach with handling <code>istream</code>s is to use the extraction as a bool:</p>\n\n<pre><code>if (cin >> radius) {\n //A double was successfully read\n} else {\n //A double was not successfully read\n}\n</code></pre>\n\n<p>To be honest, I'm not actually sure what the idiomatic way to force a user to provide a valid input is. Hopefully one of the (much) more knowledge C++ regulars will comment on that. My guess though would be to use <code>ignore()</code> to clear out <code>cin</code>'s buffer and try to grab a new input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T06:27:28.403",
"Id": "26336",
"Score": "0",
"body": "`system(\"pause\");` is how they are teaching to do it at the moment. I was also trying to figure out how to check for a successful input, but I wasn't able to come up with one. Perhaps that will be addressed in the next couple classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T20:12:29.770",
"Id": "26417",
"Score": "2",
"body": "I would put the using declarations inside main (if I used them at all). Try and constrain using declarations to the smallest scope possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T20:21:02.083",
"Id": "26420",
"Score": "0",
"body": "@BrookJulias: Tell your teacher that he is an idiot for using `system(\"pause\");`. There are better ways. Most IDE will stop on exit if you configure them correctly and running from the command line you don't need it. Otherwise you can do platform neutral pause by waiting for a line to be entered. http://stackoverflow.com/q/2529617/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-28T04:39:40.703",
"Id": "173157",
"Score": "0",
"body": "I suggest adding a validation of the input that the radius must be a positive number in order to define a circle."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T06:17:54.723",
"Id": "16187",
"ParentId": "16185",
"Score": "7"
}
},
{
"body": "<p>In addition to what Corbin said, except where differing:</p>\n\n<ul>\n<li>I recommend just dropping the using-declarations altogether. As you use more of the standard library they will become a pain. Also, seeing as you cannot use them everywhere (sanely), you'll end up with a mix of qualified and unqualified things.</li>\n<li>If you want to use <code>std::system</code>, you need to include <code>cstdlib</code>. However, that doesn't matter because you shouldn't use <code>std::system</code>.</li>\n<li>I do not recommend using <code>std::pow</code> to square things. Writing out <code>radius*radius</code> is not going to make your code less clear (quite the opposite, imho).</li>\n<li>I do not recommend writing your own <code>pi</code> constant. Use <code>std::acos(-1)</code> or somesuch.</li>\n<li>Write a function to do input sanely with error-checking and all, then just write <code>double radius = readDouble(\"Enter a number: \");</code>. Or, better <code>auto const radius = read<double>(\"Enter a number: \");</code>. <a href=\"http://liveworkspace.org/code/9bb21225b071b96fe12443e00955c7d2\" rel=\"nofollow\">See here for an example implementation.</a> Simplify as necessary.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T14:46:14.860",
"Id": "26365",
"Score": "0",
"body": "So would recommend `using namespace std;` instead of breaking it down? Also thank you for the link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T21:15:44.783",
"Id": "26385",
"Score": "0",
"body": "@BrookJulias: No, just explicitly qualify the names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T12:59:36.990",
"Id": "26398",
"Score": "0",
"body": "No using declarations? Are you sure? Seems a bit overkill to be naming every single identifier everywhere (I mean, I already do it in header files, but to extend that to cpp files too...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T13:39:26.127",
"Id": "26400",
"Score": "0",
"body": "@luiscubal: I find that most identifiers are used sufficiently rarely that qualifying them explicitly (especially in the case of the `std` namespace) is not a problem. If any particular one gets used very often I may add a using declaration for it, but I find the inconsistent use of `name` vs `std::name` in source vs header files more of a bother than typing those extra characters. (It also helps a lot to know where a name comes from in more complex programs.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T20:16:30.967",
"Id": "26418",
"Score": "1",
"body": "PI: http://stackoverflow.com/q/1727881/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-06T04:49:15.017",
"Id": "26432",
"Score": "0",
"body": "Thanks, favourited. I don't like defines, so I'd prefer the boost solution or acos. Hoping that the latter gets optimised out, but haven't checked."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T09:35:30.360",
"Id": "16193",
"ParentId": "16185",
"Score": "4"
}
},
{
"body": "<p>Analysis of new code:</p>\n\n<ul>\n<li>Stop using <code>using namespace std;</code>, that's definitely worse than what you had before.</li>\n<li>A function called <code>GetInt</code> that returns a float by reference is just silly.</li>\n<li>Your <code>while(true)</code> loop will keep going even if <code>std::cin</code> has reached EOF.</li>\n<li>Don't keep commented-out code there like that, especially not between <code>/* ... */</code> comments due to their unnestability; use <code>#if 0 ... #endif</code> or just get rid of the code and rely on your version control system to find it back.</li>\n</ul>\n\n<p>For your loop, I'd suggest...</p>\n\n<pre><code>while (std::cin) {\n if (!GetFloat(radius)) {\n std::cout << \"Not a float!\" << std::endl;\n continue;\n }\n // Logic\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T17:28:51.217",
"Id": "16413",
"ParentId": "16185",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16187",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T05:43:29.843",
"Id": "16185",
"Score": "11",
"Tags": [
"c++",
"homework"
],
"Title": "Simple C++ function to determine the circumference and area of a circle"
}
|
16185
|
<p>I wrote a C# tool that make a recursive search. I need the file size and the size on disc. I am using a function that give me the size on disc but it is very slow.</p>
<p>Is there any other way to do it except the following code?</p>
<pre><code>public void RecursiveSearch(string path)
{
try
{
foreach (string dir in Directory.GetDirectories(path))
{
foreach (string file in Directory.GetFiles(dir))
{
FileInfo fi = new FileInfo(file);
Application.DoEvents();
lblPfad.Text = fi.FullName;
long FileLength = fi.Length;
long FileLengthOnHarddisc = GetFileSizeOnDisk(file,fi);
if ((FileLength == FileLengthOnHarddisc && FileLength == 4096) || FileLength >= FileLengthOnHarddisc)
{
myStreamWriter.WriteLine(file + " - GrΓΆΓe - " + FileLength.ToString() + " - GrΓΆΓe auf DatentrΓ€ger - " + FileLengthOnHarddisc.ToString());
}
}
RecursiveSearch(dir);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
</code></pre>
<p>Here is the function for getting the size on disc:</p>
<pre><code> public static long GetFileSizeOnDisk(string file,FileInfo info)
{
uint dummy, sectorsPerCluster, bytesPerSector;
int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy);
if (result == 0) throw new Win32Exception();
uint clusterSize = sectorsPerCluster * bytesPerSector;
uint hosize;
uint losize = GetCompressedFileSizeW(file, out hosize);
long size;
size = (long)hosize << 32 | losize;
return ((size + clusterSize - 1) / clusterSize) * clusterSize;
}
[DllImport("kernel32.dll")]
static extern uint GetCompressedFileSizeW([In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
[Out, MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh);
[DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)]
static extern int GetDiskFreeSpaceW([In, MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName,
out uint lpSectorsPerCluster, out uint lpBytesPerSector, out uint lpNumberOfFreeClusters,
out uint lpTotalNumberOfClusters);
</code></pre>
|
[] |
[
{
"body": "<p>One aside to mention: you should split your UI and business logic code. For the sake of tossing it into a working example quickly (I'm doing this over lunch), I removed all the UI code and replaced any print-outs with <code>Console.WriteLine</code> calls.</p>\n\n<p>I also did a little refactoring to split method calls.</p>\n\n<p>Additionally, I renamed <code>RecursiveSearch</code> to <code>RecursiveSearch2</code> so I could run it side-by-side with the original.</p>\n\n<p>Finally, I made some of the non-static method static, but only to speed up running the project. Pay no mind to these changes.</p>\n\n<pre><code> public static void RecursiveSearch2 (string path)\n {\n try\n {\n RecursiveSearch2 (new DirectoryInfo (path));\n }\n catch (Exception ex)\n {\n Console.WriteLine (ex.Message);\n }\n }\n</code></pre>\n\n<p>Since I switched to use DirectoryInfo, I went ahead and made two overloads of the RecursiveSearch method. One takes in the string for the initial search, but sub-directories can call the overload which takes in DirectoryInfo directly. The first allows you to make the change without breaking your interface, while the second is more useful during processing work.</p>\n\n<p>For speed, I pushed the try/catch up here and left out exception handling elsewhere, though you may want to add some at the lower level methods, if only to provide more descriptive logging/exception messages.</p>\n\n<pre><code> public static void RecursiveSearch2 (DirectoryInfo dir)\n {\n foreach (var item in dir.GetFileSystemInfos ())\n {\n if (item is FileInfo)\n PrintFileInfo (item as FileInfo);\n else if (item is DirectoryInfo)\n RecursiveSearch2 (item as DirectoryInfo);\n }\n }\n</code></pre>\n\n<p>If you call the <code>DirectoryInfo.GetFileSystemInfos</code> method, it returns all directories and files in one call. The upside is that it reduces the calls to the filesystem, which are generally going to be your bottleneck. The downside is that you get a base type back, so some type handling may be necessary.</p>\n\n<pre><code> private static void PrintFileInfo (FileInfo fi)\n {\n long FileLength = fi.Length;\n long FileLengthOnHarddisc = GetFileSizeOnDisk (fi.FullName, fi);\n\n\n if ((FileLength == FileLengthOnHarddisc && FileLength == 4096) || FileLength >= FileLengthOnHarddisc)\n {\n Console.WriteLine (fi.FullName + \" - GrΓΆΓe - \" + FileLength.ToString () + \" - GrΓΆΓe auf DatentrΓ€ger - \" + FileLengthOnHarddisc.ToString ());\n }\n }\n</code></pre>\n\n<p>We are then left with handling the actual file, which I split off into a different method. The only notable differences is that I changed the input to be a FileInfo type rather than string, since I already have the FileInfo object from the calling method's loop.</p>\n\n<p>Running your method versus the modified version on my <code>c:\\downloads</code> folder cut the time consistently between 1/4 to 1/2 the time of the original, though my sample size is far too small to be conclusive. I would advise benchmarking it yourself, though. It is possible that the performance characteristics change wildly based upon the folder structure, depth, and ratio of directories to files.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T19:03:29.533",
"Id": "16208",
"ParentId": "16195",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "16208",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T11:45:11.510",
"Id": "16195",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Getting the size on disc"
}
|
16195
|
<p>How to write following if condition clean/fast/readable.
Any one of the fields <code>'address', 'city', 'district', 'province'</code> can be null. I want to make full address by concat all these fields. Like </p>
<pre><code>address = "Street # 32"
city = "My City"
District = "New York"
Province = "NY"
fullAddress = "Stree #32, My City, New York, NY"
</code></pre>
<p>If any information is missing then don't add this in string like if district is missing then don't include it.</p>
<pre><code>address = "Street # 32"
city = "My City"
District = ""
Province = "NY"
fullAddress = "Stree #32, My City, NY"
</code></pre>
<p>Following code I have written but not good.</p>
<pre><code>string address = dr["Address"].ToString();
string city = dr["City"].ToString();
string district = dr["District"].ToString();
string province = dr["Province"].ToString();
string fullAddress = "";
if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(district) && !string.IsNullOrEmpty(province))
{
fullAddress = address + ", " + city + ", " + district + ", " + province;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(district))
{
fullAddress = address + ", " + city + ", " + district;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(province))
{
fullAddress = address + ", " + city + ", " + province;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(district) && !string.IsNullOrEmpty(province))
{
fullAddress = address + ", " + district + ", " + province;
}
else if (!string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(district) && !string.IsNullOrEmpty(province))
{
fullAddress = city + ", " + district + ", " + province;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city))
{
fullAddress = address + ", " + city;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(province))
{
fullAddress = address + ", " + province;
}
else if (!string.IsNullOrEmpty(address))
{
fullAddress = address;
}
else if (!string.IsNullOrEmpty(city))
{
fullAddress = city;
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd suggest to create a method like:</p>\n\n<pre><code>public static string CreateAddressFrom(Dictionary dr)\n{\n var addressDetails = new List<string>{\"Address\",\"City\",\"District\",\"Province\"};\n var fullAddress = string.Empty;\n\n foreach (var addressDetail in addressDetails)\n {\n string addressDetailStr = dr[addressDetail];\n if (!string.IsNullOrEmpty(addressDetailStr))\n fullAddress += fullAddress + \", \" + addressDetailStr;\n }\n\n return fullAddress.TrimStart(\", \".ToCharArray());\n}\n</code></pre>\n\n<p>So your client code now can generate the address like this:</p>\n\n<pre><code>...\nvar myDictionary = ...;\nvar fullAddress = CreateAddrressFrom(myDictionary);\n...\n</code></pre>\n\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T12:23:59.983",
"Id": "26357",
"Score": "2",
"body": "Why do you use `??` when you then check for `null` again by using `IsNullOrEmpty()`? Also, `Convert.ToChar(\", \")` doesn't make sense and will throw an exception. Maybe you meant `\", \".ToCharArray()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T12:37:12.123",
"Id": "26359",
"Score": "0",
"body": "Yes, my error! I'll edit my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T12:02:52.323",
"Id": "16197",
"ParentId": "16196",
"Score": "2"
}
},
{
"body": "<p>I think using LINQ together with <a href=\"http://msdn.microsoft.com/en-us/library/dd783876.aspx\"><code>string.Join()</code></a> would be the best option here:</p>\n\n<pre><code>var fields = new[] { \"Address\", \"City\", \"District\", \"Province\" };\nvar setValues = fields.Select(field => (string)dr[field])\n .Where(value => !string.IsNullOrEmpty(value));\nstring fullAddress = string.Join(\", \", setValues);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T12:23:01.280",
"Id": "16198",
"ParentId": "16196",
"Score": "11"
}
},
{
"body": "<p>I know there's already an accpeted answer here. But I have another solution, a bit different.</p>\n\n<pre><code>Dictionary<string, string> dr = GetValues(); \n//GetValues is where you would get the data\n\nstring addressFromDictionary = dr.Where(k => !String.IsNullOrEmpty(k.Value))\n .Select(d => d.Value)\n .Aggregate((c, n) => c + \", \" + n);\n</code></pre>\n\n<p>svick's solution works fine. But I would avoid using a separate list with the field-keys. And using the Select() before the Where() first gets all fields from the dictionary and then selects the non-empty ones. Here you only get the fields that have a non-null value and concatenate those values using the Aggregate() function.</p>\n\n<p>Not saying my code is better, just showing another possibility! ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T03:01:39.623",
"Id": "34784",
"Score": "1",
"body": "It's okay to add another answer, even if there already is an accepted one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T09:07:17.630",
"Id": "21610",
"ParentId": "16196",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T11:45:12.810",
"Id": "16196",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Write it better/neat/fast (if condition)"
}
|
16196
|
<p>The bellow functions are used to generate a string with random characters, and they have a parameter to specify the string length.</p>
<p>The string can be composed of letters, numbers or a conjunction of both.</p>
<p>I've been using this for a very long time now, and currently, I look at it and it seems to damn extensive for the end result.</p>
<h2>Functions</h2>
<pre><code>function assign_rand_value($num) {
// accepts 1 - 36
switch($num) {
case "1" : $rand_value = "a"; break;
case "2" : $rand_value = "b"; break;
case "3" : $rand_value = "c"; break;
case "4" : $rand_value = "d"; break;
case "5" : $rand_value = "e"; break;
case "6" : $rand_value = "f"; break;
case "7" : $rand_value = "g"; break;
case "8" : $rand_value = "h"; break;
case "9" : $rand_value = "i"; break;
case "10" : $rand_value = "j"; break;
case "11" : $rand_value = "k"; break;
case "12" : $rand_value = "l"; break;
case "13" : $rand_value = "m"; break;
case "14" : $rand_value = "n"; break;
case "15" : $rand_value = "o"; break;
case "16" : $rand_value = "p"; break;
case "17" : $rand_value = "q"; break;
case "18" : $rand_value = "r"; break;
case "19" : $rand_value = "s"; break;
case "20" : $rand_value = "t"; break;
case "21" : $rand_value = "u"; break;
case "22" : $rand_value = "v"; break;
case "23" : $rand_value = "w"; break;
case "24" : $rand_value = "x"; break;
case "25" : $rand_value = "y"; break;
case "26" : $rand_value = "z"; break;
case "27" : $rand_value = "0"; break;
case "28" : $rand_value = "1"; break;
case "29" : $rand_value = "2"; break;
case "30" : $rand_value = "3"; break;
case "31" : $rand_value = "4"; break;
case "32" : $rand_value = "5"; break;
case "33" : $rand_value = "6"; break;
case "34" : $rand_value = "7"; break;
case "35" : $rand_value = "8"; break;
case "36" : $rand_value = "9"; break;
}
return $rand_value;
}
function get_rand_alphanumeric($length) {
if ($length>0) {
$rand_str="";
for ($i=1; $i<=$length; $i++) {
mt_srand((double)microtime() * 1000000);
$num = mt_rand(1,36);
$rand_str .= assign_rand_value($num);
}
}
return $rand_str;
}
function get_rand_numbers($length) {
if ($length>0) {
$rand_str="";
for($i=1; $i<=$length; $i++) {
mt_srand((double)microtime() * 1000000);
$num = mt_rand(27,36);
$rand_str .= assign_rand_value($num);
}
}
return $rand_str;
}
function get_rand_letters($length) {
if ($length>0) {
$rand_str="";
for($i=1; $i<=$length; $i++) {
mt_srand((double)microtime() * 1000000);
$num = mt_rand(1,26);
$rand_str .= assign_rand_value($num);
}
}
return $rand_str;
}
</code></pre>
<hr />
<h2>Usage:</h2>
<p>Basically I have a main function with the values, then I call secondary functions to build my string based on the length parameter:</p>
<p><em><strong>Letters:</strong></em></p>
<pre><code>$str = get_rand_letters(8); // Only Letters
</code></pre>
<p><em><strong>Numbers:</strong></em></p>
<pre><code>$str = get_rand_numbers(8); // Only Numbers
</code></pre>
<p><em><strong>AlphaNumeric:</strong></em></p>
<pre><code>$str = get_rand_alphanumeric(8); // Numbers and Letters
</code></pre>
<hr />
<h2>My question:</h2>
<p>How would I go, as to reduce the amount of code, keeping the end result the same?</p>
|
[] |
[
{
"body": "<p>First: I'm sure there's even simpler way than this (i.e. a library that just does what you need, period), but heck, I figured I'd try. Been years since I spent my days with PHP (don't particularly miss it).</p>\n\n<p>Anyway, skip the whole <code>switch</code> lookup. <strike><code>chr()</code> will take an int and give you its ASCII value. The 97-122 range (inclusive) is a-z (65-90 is A-Z). As for numbers, well, that's what a random function gives you - no need to look that up.</strike> See <a href=\"https://codereview.stackexchange.com/questions/16199/refactoring-functions-that-generate-string-with-random-letters-numbers-or-mixed/16204#comment26369_16204\">Rene Geuze's comment below</a>; while <code>chr</code> works just fine, <code>range</code> is indeed more readable.</p>\n\n<pre><code>function get_rand($min, $max) {\n mt_srand((double) microtime() * 1000000);\n return mt_rand($min, $max);\n}\n\nfunction get_rand_alphanumeric($length) {\n $alnum = \"\";\n $range = range(\"a\", \"z\");\n $limit = count($range) + 9;\n while(strlen($alnum) < $length) {\n $rand = get_rand(0, $limit);\n if( $rand < 10 ) {\n $alnum .= $rand;\n } else {\n $alnum .= $range[$rand - 10];\n }\n }\n return $alnum;\n}\n\nfunction get_rand_numbers($length) {\n if( $length <= 8 ) { // avoid int overflow\n return (string) get_rand(pow(10, $length-1), pow(10, $length));\n } else {\n $numbers = \"\";\n while(strlen($numbers) < $length) $numbers .= get_rand_numbers(8);\n return substr($numbers, 0, $length);\n }\n}\n\nfunction get_rand_letters($length) {\n $letters = \"\";\n $range = range(\"a\", \"z\");\n $limit = count($range) - 1;\n while(strlen($letters) < $length) $letters .= $range[get_rand(0, $limit)];\n return $letters;\n}\n</code></pre>\n\n<p>You get results like this</p>\n\n<pre><code>get_rand_alphanumeric(42) => upop8eoome0y0av2qav1j7yn5linyjshiurc8lbjja\nget_rand_numbers(42) => 365818982423371436493339856184748778003731\nget_rand_letters(42) => abfmthyuxdlganhfthebfjaugeeoniqawocgavowpx\n</code></pre>\n\n<p><strong>Edit</strong> I just realized that your original alphanumeric function will pick randomly from your entire list, meaning it's 2.6 times more likely that the pick will be a letter. I edited mine to do the same to keep the results similar.</p>\n\n<p>Also, the calls to <code>mt_srand</code> are by far the most expensive operation. Consider calling it less frequently, if speed is a concern. If I omit it, the functions above are 7.5-10x faster than the original; if I leave it as you see in the code, the functions are still faster, but only very marginally so (1.1x to 1.4x). In either case, <code>get_rand_numbers</code> obviously sees the biggest speedup since there's not lookup going on.</p>\n\n<p><strong>Edit 2</strong> Replaced <code>chr</code> usage with a <code>range</code> array, re: the comments</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T16:41:03.857",
"Id": "26369",
"Score": "1",
"body": "Using the range() function is probably more human readable than using chr. Used by filling one array with range and just pick randomly from the array instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T17:15:28.447",
"Id": "26370",
"Score": "0",
"body": "@ReneGeuze Good point. Adding it to my answer, thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T15:46:23.810",
"Id": "16204",
"ParentId": "16199",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "16204",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T12:55:01.410",
"Id": "16199",
"Score": "0",
"Tags": [
"php"
],
"Title": "Refactoring functions that generate string with random letters, numbers or mixed chars?"
}
|
16199
|
<p>I have three input boxes that are all linked to each other by some pretty basic rules:</p>
<p><ul>
<li><strong>Editing the page title will copy the contents to menu title</strong>
<ul>
<li>Unless menu title has been manually edited</li>
<li>clearing menu title sets it back to automatic</li>
</ul>
</li>
<li><strong>Editing the menu title will copy the contents as a url slug to slug</strong>
<ul>
<li>Unless the slug has been manually edited</li>
<li>clearing the slug sets it back to automatic</li>
<li>Editing page title counts as editing menu title if it is set to automatic</li>
</ul>
</li>
<li><strong>The Page Title, and the other two boxes are never visible at the same time!</strong></li>
</ul>βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ</p>
<p>Here is a demo: <a href="http://jsfiddle.net/6VPpj/1/" rel="nofollow">http://jsfiddle.net/6VPpj/1/</a></p>
<p>and here is my rather horrible code, how can I clean this up? </p>
<pre><code>$(function(){
var automatic = true;
var pager = true;
var cache = {};
var slug = $('#slug');
var menu = $('#menu_title');
var page = $('#page_title');
page.on('change', function() {
if (pager) {
menu.val(page.val());
menu.keyup();
}
});
menu.on('keypress keyup keydown change', function() {
if (automatic) {
var n = menu.val();
if (n in cache) {
slug.val(cache[n]);
return;
}
cache[n] = toSlug(n);
slug.val(cache[n]);
return;
}
});
menu.on('change', function() {
if (menu.val() == '') {
pager = true;
page.change();
}
else {
pager = false;
}
});
slug.on('change', function() {
if (slug.val() == '') {
automatic = true;
menu.keyup();
}
else {
automatic = false;
var n = slug.val();
if (n in cache) {
slug.val(cache[n]);
return;
}
cache[n] = toSlug(n);
slug.val(cache[n]);
return;
}
});
function toSlug(Text) {
return Text.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '').replace(/--+/g, '-');
}β
});
</code></pre>
|
[] |
[
{
"body": "<p>It's not so horrible. You managed to cache your jQuery selectors, which is more than a lot of people can say. Good job there.</p>\n\n<hr>\n\n<p><code>automatic</code> and <code>pager</code> are not super great names in this context. I suggest renaming them to <code>autoSlug</code>/<code>autoMenu</code> or <code>manualSlug</code>/<code>manualMenu</code>. </p>\n\n<hr>\n\n<p>You are caching <code>toSlug</code>, but really, it's not complex enough to warrant caching. I did some quick and dirty testing and found that you save about 10ms per 1,000 executions. That is not worth anything here. So, to reduce code size and bug potential, I suggest removing all caching.</p>\n\n<hr>\n\n<p>Variables and parameters should not be capitalized unless they represent a class. As such, the <code>Text</code> parameter in <code>toSlug</code> should be <code>text</code>.</p>\n\n<hr>\n\n<p>Finally, and this is more of a personal preference, but I find that code is easier to read and follow when reading functions and not event handlers. By that I mean this: instead of calling <code>menu.change()</code>, why not move that code to a function and call <code>updateMenu()</code>?</p>\n\n<p>Here is the final result:</p>\n\n<pre><code>$(function(){\nvar autoSlug = true;\nvar autoMenu = true;\n\nvar slug = $('#slug');\nvar menu = $('#menu_title');\nvar page = $('#page_title');\n\npage.on('change', function() {\n if (autoMenu) {\n updateMenu()\n }\n});\n\nmenu.on('change', function() {\n autoMenu = (menu.val() == '');\n updateMenu()\n});\n\nslug.on('change', function() {\n autoSlug = (slug.val() == '');\n updateSlug();\n});\n\nfunction updateMenu(){\n if(autoMenu){\n menu.val(page.val())\n }\n if(autoSlug){\n updateSlug()\n }\n}\n\nfunction updateSlug(){\n var text = autoSlug ? menu.val() : slug.val();\n slug.val(toSlug(text));\n}\n\nfunction toSlug(text) {\n return text.toLowerCase().replace(/ /g, '-').replace(/[^\\w-]+/g, '').replace(/--+/g, '-');\n}β\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T17:56:51.470",
"Id": "16205",
"ParentId": "16202",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T15:00:01.213",
"Id": "16202",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"optimization"
],
"Title": "Tidying up jquery code for linking inputs"
}
|
16202
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.