body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I want to make a C++ object hierarchy of "classifiers", which can be composed together via logical operators into a single classifier that implements the whole logical combination.</p>
<p>This is actually for a particle physics analysis library, but I'll present a much simpler example which just classifies integers. The motivation is that a candidate physics object to be classified might have lots of floating point properties on which basis it could be kept or discarded: e.g. mass, energy, angles, etc. -- I can't possibly create all the possible combinations of function signatures to handle this, and even if I could, there's no way for the compiler to determine e.g. "does the 3rd double mean mass or angle?" So the intention is to make the users' code clearer and less ambiguous, while reducing the number of function signatures in my API <em>and</em> increasing flexibility.</p>
<p>Here's an example of what I would <em>like</em> the resulting usage to look like, for the integer classifier example:</p>
<pre><code>Classifier c = IsOdd() || (IsEven() && LessThan(6));
for (int i = 0; i < 10; ++i) {
if (c.classify(i)) cout << i << " ";
}
// prints 0 1 2 3 4 5 7 9
</code></pre>
<p>This demonstrates several requirements:</p>
<ul>
<li>I want to be able to do more than one logical combination in a single expression</li>
<li>The objects are all stack-allocated -- no <code>new</code>s are involved to mess up the syntax. <code>new IsOdd() || (new IsEven() ... )</code> would both be distracting and would introduce problems of memory management for the user.</li>
<li>The logical operators should have their usual meanings, precedences, and lazy evaluation behaviour: calling <code>classify</code> on a composite classifier should call the same function on each of the chain of logical combinations, stopping as soon as possible.</li>
<li>The concrete classifiers (<code>IsOdd</code>, <code>LessThan</code>, etc.) should be objects with state, e.g. the constructor argument passed to <code>LessThan</code> rather than having to have a different <code>LessThanX</code> class for every integer!</li>
<li>The base class should ideally be able to be instantiated rather than have to be handled through (const) references.</li>
</ul>
<p>I've made several attempts to implement this, but keep hitting problems. Typically these have been polymorphism-related: if each <code>Classifier</code> is to contain other classifier(s), then they need to be held as pointers (references can't be stored) and we're back to memory management issues. I found a way around this using the <a href="http://cpp-experiment.sourceforge.net/boost/libs/dynamic_any/doc/" rel="nofollow"><code>dynamic_any</code></a> extension to boost's <a href="http://www.boost.org/doc/libs/1_51_0/doc/html/any.html" rel="nofollow">any</a>:</p>
<p><strong>Infrastructure:</strong></p>
<pre><code>#include <boost/any.hpp>
#include <dynamic_any.hpp>
using boost::any_cast;
using boost::dynamic_any_cast;
#include <string>
#include <vector>
#include <iostream>
#include <cassert>
#include <utility>
using namespace std; // for clarity only, won't go in any public header!
/// Main types
class Classifier {
public:
virtual bool classify(int a) const = 0;
};
class ClassifierAND : public Classifier {
public:
bool classify(int a) const {
return dynamic_any_cast<const Classifier&>(classifiers.first).classify(a)
&& dynamic_any_cast<const Classifier&>(classifiers.second).classify(a);
}
pair<boost::dynamic_any, boost::dynamic_any> classifiers;
};
class ClassifierOR : public Classifier {
public:
bool classify(int a) const {
return dynamic_any_cast<const Classifier&>(classifiers.first).classify(a)
|| dynamic_any_cast<const Classifier&>(classifiers.second).classify(a);
}
pair<boost::dynamic_any, boost::dynamic_any> classifiers;
};
/// Operator overloads
template <typename Classifier1, typename Classifier2>
inline ClassifierAND operator && (const Classifier1& c1, const Classifier2& c2) {
ClassifierAND rtn;
rtn.classifiers.first = c1;
rtn.classifiers.second = c2;
return rtn;
}
template <typename Classifier1, typename Classifier2>
inline ClassifierOR operator || (const Classifier1& c1, const Classifier2& c2) {
ClassifierOR rtn;
rtn.classifiers.first = c1;
rtn.classifiers.second = c2;
return rtn;
}
</code></pre>
<p><strong>Concrete classifiers:</strong></p>
<pre><code>struct IsEven : public Classifier {
bool classify(int a) const { return a % 2 == 0; }
};
struct LessThan : public Classifier {
LessThan(int val) { cutval = val; }
bool classify(int a) const { return a < this->cutval; }
int cutval;
};
struct GtrThan : public Classifier {
GtrThan(int val) { cutval = val; }
bool classify(int a) const { return a > this->cutval; }
int cutval;
};
</code></pre>
<p><strong>Test program:</strong></p>
<pre><code>void test(const Classifier& c) {
for (int i = -3; i < 10; ++i) {
if (c.classify(i)) cout << i << " ";
}
cout << "\n";
}
int main() {
IsEven e;
GtrThan g4(4);
GtrThan g2(2);
LessThan l(-1);
const Classifier& c1 = e || GtrThan(4);
test(c1);
// -2 0 2 4 5 6 7 8 9
ClassifierAND c2 = e && g2 && g4;
test(c2);
test(e && g2 && g4);
// 6 8 (twice)
test(e && l);
// -2
const Classifier& c4 = IsEven() || LessThan(3);
test(c4);
test(IsEven() || LessThan(3));
// -3 -2 -1 0 1 2 4 6 8 (twice)
}
</code></pre>
<p>As seen from the output, this does work... but I think/hope it can still be improved. In particular, the <code>Classifier</code> base class is virtual, which forces me to use const references: fine as an argument signature (cf. <code>test</code>) but a bit confusing for an explicit variable as in the last test and risks "object slicing" errors if used without care.</p>
<p>Additionally the <code>ClassifierAND/OR</code> types are really clunky -- I'd originally tried to put a "next" <code>Classifier</code> member and a logical operation enum in the base class to avoid these pairs, but couldn't make it work nicely. It would be nice to hide these or avoid them entirely so that the compiler doesn't emit warnings about a chain of logically combined classifiers being of a type that the user isn't exposed to.</p>
<p>I'm also not sure if the efficiency can be improved: due to the AND/OR pairs, there could in general be quite a lot of pair nesting.</p>
<p>Any feedback and suggestions for improvements would be very welcome!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T20:57:26.110",
"Id": "28495",
"Score": "2",
"body": "I think you will have better success using templates and duck typeing rather than a polymorphic interface. The C++ standard library uses duck typing to achieve the same affect you are trying to achieve here."
}
] |
[
{
"body": "<p>I think you will have better success using templates and duck typeing rather than a polymorphic interface. The C++ standard library uses duck typing to achieve the same affect you are trying to achieve here.</p>\n\n<p>This is what I would do:</p>\n\n<pre><code>// A couple of these are already in the standard library have a look.\nstruct IsEven\n{\n bool operator()(int a) const { return a % 2 == 0; }\n};\n\nstruct LessThan\n{\n LessThan(int val): cutval(val) {}\n bool operator()(int a) const { return a < cutval; }\n int cutval;\n};\n\nstruct GtrThan\n{\n GtrThan(int val): cutval(val) {}\n bool operator()(int a) const { return a > this->cutval; }\n int cutval;\n};\n\ntemplate<typename T1, typename T2>\nstruct AndOp\n{\n AndOp(T1 const& t1, T2 const& t2) : t1(t1), t2(t2) {}\n T1 const t1;\n T2 const t2;\n bool operator()(int a) const { return t1(a) && t2(a);}\n};\n\ntemplate<typename T1, typename T2>\nstruct OrOp\n{\n OrOp(T1 const& t1, T2 const& t2) : t1(t1), t2(t2) {}\n T1 const t1;\n T2 const t2;\n bool operator()(int a) const { return t1(a) || t2(a);}\n};\n\ntemplate<typename T1, typename T2>\nAndOp<T1, T2> make_and_op(T1 const& t1, T2 const& t2)\n{\n return AndOp<T1, T2>(t1, t2);\n}\ntemplate<typename T1, typename T2, typename T3>\nAndOp<AndOp<T1, T2>, T3> make_and_op(T1 const& t1, T2 const& t2, T3 const& t3)\n{\n return AndOp<AndOp<T1, T2>, T3>(make_and_op(t1, t2), t3));\n}\n\ntemplate<typename T1, typename T2>\nOrOp<T1, T2> make_or_op(T1 const& t1, T2 const& t2)\n{\n return OrOp<T1, T2>(t1, t2);\n}\n</code></pre>\n\n<p>Now we can test with:</p>\n\n<pre><code>template<typename T>\nvoid test(const T& c) {\n for (int i = -3; i < 10; ++i) {\n if (c(i)) cout << i << \" \";\n }\n cout << \"\\n\";\n}\n\nint main()\n{\n\n test(make_or_op(IsEven(), GtrThan(4)));\n // -2 0 2 4 5 6 7 8 9\n\n test(make_and_op(IsEven(), GtrThan(2), GtrThan(4)));\n // 6 8\n\n test(make_and_op(IsEven(), LessThan(-1)));\n // -2\n\n test(make_or_op(IsEven(), LessThan(3))); \n // -3 -2 -1 0 1 2 4 6 8\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T07:54:40.307",
"Id": "28560",
"Score": "0",
"body": "Thanks Loki. Without polymorphism this could get cumbersome, though: you've explicitly made a 3-arg `make_and_op` to avoid nested calls to the 2-arg version. I really wanted to overload the boolean operators to make this feel natural to the user, not have surprises (\"no 3-arg OR?\" ;-) \"If the AND worked for 2 and 3 args, it must work for 4...\", etc.) and not have boilerplate taking up a lot of space.\nProbably we can combine the two approaches by _also_ inheriting from a base class and defining boolean ops on that... or not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T08:14:54.553",
"Id": "28563",
"Score": "0",
"body": "Sorry don't like you overload of the || (and &&) operators. Its the classic lets abuse the operators syndrome to do a clever trick. It works for you because you wrote it. But nobody else will find it intuitive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T09:00:05.217",
"Id": "28565",
"Score": "0",
"body": "I'm confused: the use of those operators is for logical combination of the classifiers according to exactly the normal meanings of those operators... or at least, that's the the intention. How is it unintuitive? IMHO, having to use named functions to express boolean combinations is much more confusing..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:13:46.200",
"Id": "28585",
"Score": "0",
"body": "@andybuckley: Because they are not performing the operation you expect. I expect || (and &&) to return a boolean value using short cut semantics. So in this situation where they do neither of the above; then have to dig into the code to find out exactly what is happening before you can use them. Check out any forum (or google) about \"C++ overloading operator abuse\". This falls squarely in this category. Its intuitive to you because you wrote it. To everybody else they will need to dig out the source to work out what is happening before they can use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:14:44.047",
"Id": "28586",
"Score": "0",
"body": "@andybuckley: Best practive (and maintainable code) would dictate the use of a named function that describes what is happening. (Yours is a nice trick that everybody learning C++ tries. But ultimately leads to maintenance problems)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:19:14.540",
"Id": "28588",
"Score": "0",
"body": "@andybuckley: Its not as if what you are doing is unique. You are re-inventing a simplified lambda syntax. Already been done. And from lots of previous trial and error the community has decided function are better in the long run. Look at the standard library and boost for inspiration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T18:14:31.063",
"Id": "28971",
"Score": "0",
"body": "I didn't think it was unique :) But whether an API is appropriate depends on the context it will be used in, not \"the community\", whatever that is! This case is restricted to logical combinations, and syntactic cleanliness is paramount (hence my including the logical operator overloading in the design requirements.) Restricting to named functions would defeat much of the point. Incidentally, Boost Spirit contains some of the least intuitive operator overloading I've seen in a major production library! Thanks for the feedback, and some apologies for my dissenting view."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T21:14:28.663",
"Id": "17902",
"ParentId": "17881",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T12:26:40.680",
"Id": "17881",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"operator-overloading"
],
"Title": "Implementing C++ boolean function objects with logical operator combinations"
}
|
17881
|
<p>The function takes 2 arguments: array: int[], cap: int</p>
<p>Members would be ranged from 0 to cap.</p>
<p>e.g.</p>
<pre><code>array = [0,0,0,2,6,3,0,4,2,4,0]
cap = 6
</code></pre>
<p>The return value is a new array of same length based on these rules:</p>
<ol>
<li><p>The function can only change values of consecutive elements which are > 0. i.e. any where the original array has 0, the new array has 0 as well.</p></li>
<li><p>In a consecutive series of elements which are > 0, if the maximum of it equals cap, then in the new array they are changed to 1,1,...,1,cap of the same length. e.g. 0,2,6,4,0 -> 0,1,1,6,0</p></li>
<li><p>In a consecutive series of elements which are > 0, if the maximum of it is smaller than cap, then the elements in the new array are mapped to either 1 or maximum (if the element value < maximum then 1, otherwise maximum ) . e.g. 0,2,5,5,0 -> 0,1,5,5,0</p></li>
</ol>
<p>So the sample array would map to [0,0,0,1,1,6,0,4,1,4,0]</p>
<p>The following are my code which are implemented in both languages, it surprises me that F# takes same lines as C#.</p>
<p>I would like to suggestions to improve either language.</p>
<p>F#</p>
<pre><code>open System
let private reorder cap (array: int[]) =
if Array.isEmpty array then
array
else
let max = array |> Array.max
if max = cap then
let newArray = Array.create array.Length 1
newArray.[array.Length-1] <- cap
newArray
else
array |> Array.map (fun elem -> if elem = max then max else 1)
let private getZeroes todo =
todo |> Seq.takeWhile (fun elem -> elem = 0)
|> Seq.toArray
let private getNumbers todo cap =
todo |> Seq.takeWhile (fun elem -> elem <> 0)
|> Seq.toArray
|> reorder cap
let GetEquivalentPermutation (array: int[], cap) =
let rec joinParts finished todo =
if Seq.isEmpty todo then finished |> Seq.toArray
else
let zeroes = getZeroes todo
let nextTodo = todo |> Seq.skip zeroes.Length
let numbers = getNumbers nextTodo cap
let finalTodo = nextTodo |> Seq.skip numbers.Length
let newFinished = Seq.append (Seq.append finished zeroes) numbers
joinParts newFinished finalTodo
joinParts [] array
</code></pre>
<p>C#</p>
<pre><code> static int[] EquivalentOutput(int cap, int[] permutation)
{
IEnumerable<int> right = permutation;
List<int> equivalentLine = new List<int>();
while (right.Any())
{
var leftArray = right.TakeWhile(x => x != 0).ToArray();
List<int> leftEquivalent;
if (leftArray.Length == 0)
{
leftEquivalent = new List<int>();
}
else if (leftArray.Length != 1)
{
int max = leftArray.Max();
if (max == cap)
{
leftEquivalent = leftArray.Take(leftArray.Length - 1).Select(x => 1).ToList();
leftEquivalent.Add(cap);
}
else
{
leftEquivalent = leftArray.Select(x => x < max ? 1 : max).ToList();
}
}
else
{
leftEquivalent = leftArray.ToList();
}
equivalentLine.AddRange(leftEquivalent);
equivalentLine.AddRange(right.SkipWhile(x => x != 0).TakeWhile(x => x == 0));
right = right.SkipWhile(x => x != 0).SkipWhile(x => x == 0);
}
return equivalentLine.ToArray();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T14:39:49.853",
"Id": "28468",
"Score": "1",
"body": "What is your question? Are you wanting this improved in F#, C# or both? What type of improvements are you looking for: performance, readability?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T15:00:18.890",
"Id": "28470",
"Score": "0",
"body": "@GeneS either will do. Yes, readability or elegance or conciseness"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:46:02.523",
"Id": "59316",
"Score": "0",
"body": "please separate these into two questions, either you want a review in C# or you want a review in F#, pick one"
}
] |
[
{
"body": "<p>Seems you might be overusing Linq since you are manipulating an array. Here is an example that to me is a bit more readable (although the readability could be improved further) and it is faster.</p>\n\n<pre><code>private static int[] EquivalentOutput(int cap, int[] permutation)\n{\n int[] copy = permutation.ToArray();\n\n for (int i = 0; i < copy.Length; i++)\n {\n if (copy[i] == 0)\n continue;\n\n var consecutiveElements = copy.Skip(i).TakeWhile(x => x != 0).ToArray();\n var max = consecutiveElements.Max();\n if (max == cap)\n {\n for (int j = 0; j < consecutiveElements.Length - 1; j++)\n copy[i++] = 1;\n copy[i++] = cap;\n }\n else\n {\n for (int j = 0; j < consecutiveElements.Length; j++)\n copy[i] = copy[i++] == max ? max : 1;\n }\n }\n return copy;\n}\n</code></pre>\n\n<p><strong>Update</strong>:\n@svick pointed out that it feels a bit \"weird\" changing the loop variable inside the loop so I am providing an alternative which some people will consider easier to read...</p>\n\n<pre><code>private static int[] EquivalentOutput(int cap, int[] permutation)\n{\n int[] copy = permutation.ToArray();\n\n int i = 0;\n while (i < copy.Length)\n {\n if (copy[i] > 0)\n {\n var consecutiveElements = copy.Skip(i).TakeWhile(x => x != 0).ToArray();\n var max = consecutiveElements.Max();\n if (max == cap)\n {\n for (int j = 0; j < consecutiveElements.Length - 1; j++)\n copy[i++] = 1;\n copy[i++] = cap;\n }\n else\n {\n for (int j = 0; j < consecutiveElements.Length; j++)\n copy[i] = copy[i++] == max ? max : 1;\n }\n }\n\n i++;\n }\n return copy;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T18:35:03.557",
"Id": "28486",
"Score": "1",
"body": "I think you should use cast to `int[]` instead of `as`. If you make an error, you want to get an exception, not `null`. Also, modifying the loop variable inside the loop feels weird to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T10:27:25.820",
"Id": "28735",
"Score": "0",
"body": "why do u use `.Clone()` instead of `.ToArray()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:23:29.320",
"Id": "28748",
"Score": "0",
"body": "@colingfang Wasn't thinking of that. `.ToArray()` is much better. Changing code to reflect this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:25:48.397",
"Id": "28749",
"Score": "0",
"body": "@svick Used @colinfant suggestion so cast no longer necessary. As far as modifying the loop variable inside the loop...It performs well and I do not think it lessens the readability much. The `for` loop could be changed to a `while` loop if you think that improves the readability."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T16:36:34.837",
"Id": "17892",
"ParentId": "17882",
"Score": "2"
}
},
{
"body": "<p>I think you should separate your concerns: first split the array into groups, then process each group separately and finally combine them back into a single array.</p>\n\n<p>I think doing this results in code that is easier to understand:</p>\n\n<pre><code>private static IEnumerable<List<int>> SplitInGroups(int[] permutation)\n{\n var result = new List<int>();\n\n foreach (var i in permutation)\n {\n // is this a new series?\n if (result.Any() && ((result.Last() == 0) != (i == 0)))\n {\n yield return result;\n result = new List<int>();\n }\n result.Add(i);\n }\n\n if (result.Any())\n yield return result;\n}\n\nprivate static IEnumerable<int> ProcessGroup(int cap, List<int> group)\n{\n // testing the first element is enough\n if (group[0] == 0)\n return group;\n\n int max = group.Max();\n if (max == cap)\n return Enumerable.Repeat(1, group.Count - 1).Concat(new[] { max });\n\n return group.Select(i => i == max ? max : 1);\n}\n\nprivate static int[] EquivalentOutput(int cap, int[] permutation)\n{\n return SplitInGroups(permutation).SelectMany(g => ProcessGroup(cap, g)).ToArray();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:37:54.387",
"Id": "28751",
"Score": "0",
"body": "Definitely creative (not in a bad way) but not sure I agree it is easier to understand."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T19:03:35.440",
"Id": "17895",
"ParentId": "17882",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T13:35:24.253",
"Id": "17882",
"Score": "2",
"Tags": [
"c#",
"f#"
],
"Title": "How to improve this array manipulation function?"
}
|
17882
|
<p>I have a for loop which loops through a list and builds and object, I needed to check the previous object with the one i'm building...which way is better?</p>
<p>This way?:</p>
<pre><code> String lastDirection= "";
List<Stages> stages = new ArrayList();
for (Object object : results) {
Vector result = (Vector) object;
Stages stage = new Stages();
stage.setStage(result.get(0).toString());
stage.setDirection((String) result.get(1));
stage.setStageName((String) result.get(2));
if(!stage.getDirection.equals(lastDirection))
stages.add(stage);
lastAtco = stage.getDirection();
}
return stages;
</code></pre>
<p>Or This way?:</p>
<pre><code> List<Stages> stages = new ArrayList();
for (Object object : results) {
Vector result = (Vector) object;
Stages stage = new Stages();
stage.setStage(result.get(0).toString());
stage.setDirection((String) result.get(1));
stage.setStageName((String) result.get(2));
if (stages.size() >= 1 && stages.get(stages.size() - 1).getDirection().equals(stage.getDirection())) {
} else {
stages.add(stage);
}
}
return stages;
</code></pre>
<p>I can see how one looks better than the other...but which one would be more efficient? </p>
|
[] |
[
{
"body": "<p>The former would definitely be more efficient.</p>\n\n<p>In the latter case, you \"forget\" a local variable that you have available (by letting it go out of scope), and then on the next iteration get it back by calling <code>stages.get()</code>. There's no way that the <code>get()</code> call will be as cheap as simply referencing the <code>lastDirection</code> variable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T16:06:12.223",
"Id": "28477",
"Score": "0",
"body": "I see what you mean. I didn't think about that lol."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T15:50:02.210",
"Id": "17886",
"ParentId": "17885",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "17886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T15:45:36.170",
"Id": "17885",
"Score": "6",
"Tags": [
"java"
],
"Title": "Which is better for checking previous object in list?"
}
|
17885
|
<p>I'm curious when a piece of code should be its own method or just left alone. This came up when I was creating a "work item" from the thread pool. When passing the argument to the "WaitCallback" object, I would argue that if the code that will run will ONLY run when this thread is being run, then it's OK to wrap the code inside of an Action delegate. If other places need to run this same code, then I understand separating it into a new method.</p>
<p>So, for example, what's better practice?</p>
<p>This --</p>
<pre><code>ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
{
Contract.SaveContract(Customer);
pushResultNotification = DoPushContact();
MyDispatcher.BeginInvoke((Action)(() => actionNotification.CompleteAction()), null);
}));
</code></pre>
<p>Or this --</p>
<pre><code>ThreadPool.QueueUserWorkItem(new WaitCallback(DoStuff));
private void DoStuff(object state)
{
Contract.SaveContract(Customer);
pushResultNotification = DoPushContactToGp();
MyDispatcher.BeginInvoke((Action)(() => actionNotification.CompleteAction()), null);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T17:33:02.297",
"Id": "28541",
"Score": "1",
"body": "My experience has been that things that are only used once are almost always only used once *for now*."
}
] |
[
{
"body": "<p>I believe that option one is the most correct option and I say that because limiting the number of threads that have availability to a specific piece of code built to run on a background thread will keep you from seeing locking and race conditions in production that you wouldn't see in development.</p>\n\n<p>Furthermore, this code is clearly calling out to some other methods as well so containing the point at which it runs would be of interest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T19:13:11.717",
"Id": "28490",
"Score": "2",
"body": "Thread safety is always an issue with multithreaded code, but I don't think using lambda will help you with that. If the code is not thread safe, you can get into problems just by calling the method containing `QueueUserWorkItem` twice from the same thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T11:24:07.737",
"Id": "28518",
"Score": "0",
"body": "@svick, +1 as that is quiet correct. What I maybe should have stated is it's more like \"out of sight out of mind\" and so the chances of developers abusing it is smaller. It seems that sometimes if you just make it hard for developers to be bad they won't as frequently."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T18:54:35.197",
"Id": "17894",
"ParentId": "17893",
"Score": "2"
}
},
{
"body": "<p>I think the answer here is no, it shouldn't be a separate method, as long as the piece of code in question is short. That way, when you read the code, you immediately see what the code does, you don't have to go elsewhere for that. But if the piece of code was too long, it would make the whole method less readable, so in that case, I think you should put it into a separate method.</p>\n\n<p>Few more notes:</p>\n\n<p>You don't need the <code>new WaitCallback()</code> in either case, the compiler can create the delegate automatically.</p>\n\n<p>Also, it might make sense to use <code>Task</code> instead of <code>ThreadPool</code>, assuming you're on .Net 4+.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T19:20:46.853",
"Id": "17897",
"ParentId": "17893",
"Score": "6"
}
},
{
"body": "<p>A \"process\" as defined for this answer is a distinct logical unit of functionality. Generally, a method/function should do one thing. Separating processes into their own methods makes your code more readable, especially for complex code bases. Separating processes into their own methods makes your code more maintainable. Since \"simple\" methods often evolve into complex ones, and software developers tend to do less refactoring than they should, it is often a better strategy to think long term early and put those \"one off\" processes into their own methods to begin with. They might not be \"one off\" for long.</p>\n\n<p>There may come a time when multiple methods use the same process. By having a process contained within its own method, you can more easily maintain your code and simply call that method. If something about that process changes, you only need to change it in one place - the method where you so smartly put it when you wrote it. </p>\n\n<p>So, to make a long story short, it may seem like overkill to move your process to its own method now, but in the long run, it is probably a better strategy for the readability and maintainability of your code. Yes, it is as much an art as it is a science. You have to decide whether or not a segment of code is its own process (as I defined earlier), or merely part of a different process. That decision should tell you whether or not it goes in its own method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T21:22:08.733",
"Id": "17903",
"ParentId": "17893",
"Score": "5"
}
},
{
"body": "<p>Either way works and is good. Keep in mind though, that reducing duplication is not the only reason to create a method. I often extract a method that is only used once in order to give it a descriptive name that increases the readability and intentionality of the code.</p>\n\n<p>I probably would not add a method to call it \"DoStuff\", but maybe something like this would be helpful to future maintainers of the code:</p>\n\n<pre><code>ThreadPool.QueueUserWorkItem(new WaitCallback(SaveCustomerAndFireNotifications));\n\nprivate void SaveCustomerAndFireNotifications(object state)\n{\n Contract.SaveContract(Customer);\n pushResultNotification = DoPushContactToGp();\n MyDispatcher.BeginInvoke((Action)(() => actionNotification.CompleteAction()), null);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:09:33.137",
"Id": "20746",
"ParentId": "17893",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T18:45:55.447",
"Id": "17893",
"Score": "6",
"Tags": [
"c#",
"multithreading"
],
"Title": "Should a piece of code only ever called once be a separate method?"
}
|
17893
|
<p>I have a chunk of code that averages around the points of a grid of values and Im trying to figure out if there is a better way to do the averaging. The array itself is 1 dimensional but i am using an x and y and stride to keep track of it in 2d space. Im mainly just trying to figure out if there is a more optimized way to average this or if this is the best way. </p>
<p>Let me know if anything needs clearing up. Thanks for any input!</p>
<pre><code>for (int y=0;y<lockObj.m_iSize[1];y++)
{
for (int x=0;x<lockObj.m_iSize[0];x++)
{
if(m_bShouldSmooth)
{
float avgAround = 0.0f;
if(x == 0)
{
if(y==0)
avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+x]) / 4;
else if(y==lockObj.m_iSize[1]-1)
avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x+1)] + pDest[(y-1)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x+1)]) / 4;
else
avgAround = (pDest[(y)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x)]) / 6;
}
else if(x==lockObj.m_iSize[0]-1)
{
if(y==0)
avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+x]) / 4;
else if(y==lockObj.m_iSize[1]-1)
avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x)]) / 4;
else
avgAround = (pDest[(y)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x)]) / 6;
}
else
{
if(y==0)
avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+x] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)]) / 6;
else if(y==lockObj.m_iSize[1]-1)
avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+x] + pDest[(y-1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)]) / 6;
else
avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+x] + pDest[(y-1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x)] + pDest[(y+1)*lockObj.m_iStride+(x-1)]) / 9;
}
if(this->GetContactForce() > 0){
if(avgAround < pDest[y*lockObj.m_iStride+x])
pDest[y*lockObj.m_iStride+x] = avgAround;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T21:27:19.163",
"Id": "28500",
"Score": "1",
"body": "You'll get more useful answers if you include the language you are using in the tags. I can't really tell from the code itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T22:55:55.310",
"Id": "28501",
"Score": "0",
"body": "When you say optimized, do you want it to run faster, or do you want less code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T13:39:08.633",
"Id": "28530",
"Score": "0",
"body": "Oops sorry! Meant to mention c++ somewhere in there. And I am just trying to determine if there is a better way to do this. By optimized, I mean if there is any cleaner way to do this without slowing it down any. I thought there might be a way with recursion but I couldn't think of how and if it would be any better."
}
] |
[
{
"body": "<p>I'm not into C++, but here's a suggestion for what it is worth. Create a class that encapsulates the array, let's call it <code>Array</code>. Define an <code>operator[]</code> method that gives you the value of the element of the array at (x,y); the function returns 0.0 if the coordinates are invalid. Another method, <code>n_points</code>, returns the number of valid points around (x,y) - ie. 4, 6 or 9. Then you can compute the average using the following function, ignoring where the point (x,y) is located in the array:</p>\n\n<pre><code>float average(const Array &array, int x, int y)\n{\n return\n (array[x-1,y-1] + array[x,y-1] + array[x+1,y-1] +\n array[x-1,y] + array[x,y] + array[x+1,y] + \n array[x-1,y+1] + array[x,y+1] + array[x+1,y+1])\n / array.n_points(x,y);\n}\n</code></pre>\n\n<p>That won't be more efficient (the reverse probably), but it would be more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T22:17:11.953",
"Id": "17935",
"ParentId": "17900",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T20:56:38.523",
"Id": "17900",
"Score": "2",
"Tags": [
"c++",
"optimization"
],
"Title": "Better way to average around points"
}
|
17900
|
<p>My goal is to compute the intersections of several vectors (sets of identifiers, gene-names to be specific). I start with a list of vectors and run the function below, which loops through 1:n where n is the number of sets and then uses <a href="http://stat.ethz.ch/R-manual/R-patched/library/utils/html/combn.html" rel="nofollow">combn</a> to generate all combinations of my sets taken m at a time.</p>
<p>I paste together a name and then reduce by intersection over my sets yielding a named list of character vectors holding the elements in common between each combination of sets.</p>
<p>My question is, of course, is there a better way to accomplish this?</p>
<pre><code>## Compute the intersection of all combinations of the
## elements in the list of vectors l. Might be useful
## for generating Venn/Euler diagrams.
## There might be better ways to do this!
overlap <- function(l) {
results <- list()
# combinations of m elements of list l
for (m in seq(along=l)) {
# generate and iterate through combinations of length m
for (indices in combn(seq(length(l)), m, simplify=FALSE)) {
# make name by concatenating the names of the elements
# of l that we're intersecting
name <- do.call(paste, c(as.list(names(l)[indices]), sep="_"))
# adding the init=l[indices[1]] parameter helps with the case
# where we're only dealing with one set, i==1 and length(indices)==1,
# and we want only unique items in that set.
# Reduce(intersect, list(c(1,2,3,3))) => c(1,2,3,3)
# Reduce(intersect, list(c(1,2,3,3)), init=l[[indices[1]]]) => c(1,2,3)
results[[name]] <- Reduce(intersect, l[indices], init=l[[indices[1]]])
}
}
results
}
overlap( list(foo=c('a','b','c','d','e','e'),
bar=c('a','c','e','f','g'),
bat=c('a','b','c','d','g')))
</code></pre>
|
[] |
[
{
"body": "<p>Your approach seems reasonable, but there are some simplifications you can make.</p>\n\n<p>First, your construction of <code>name</code> is needlessly complex. This works just as well:</p>\n\n<pre><code>name <- paste(names(l)[indices], collapse=\"_\")\n</code></pre>\n\n<p>Second, you can call <code>unique</code> on each element of <code>l</code> at the outset which eliminates the need to specify an <code>init</code> value to <code>Reduce</code> (and thus reducing all the calculations by one call to <code>intersect</code>). It also shortens the arguments to <code>intersect</code> since duplicates have already been eliminated.</p>\n\n<pre><code>l <- lapply(l, unique)\n</code></pre>\n\n<p>These two give a function</p>\n\n<pre><code>overlap <- function(l) {\n results <- list()\n # Remove duplicates within each entry of l\n l <- lapply(l, unique)\n\n # combinations of m elements of list l\n for (m in seq(along=l)) {\n\n # generate and iterate through combinations of length m\n for (indices in combn(seq(length(l)), m, simplify=FALSE)) {\n\n # make name by concatenating the names of the elements\n # of l that we're intersecting\n name <- paste(names(l)[indices], collapse=\"_\")\n\n results[[name]] <- Reduce(intersect, l[indices])\n }\n }\n results\n}\n</code></pre>\n\n<p>Further elimination of duplicate work would involve recognizing that higher order interactions, as you are determining them now, are repeating the intersections of the lower orders (that is <code>foo_bar_bat</code> first intersects <code>foo</code> and <code>bar</code> and then intersects that with <code>bat</code>, but the intersection of <code>foo</code> and <code>bar</code> was already determined). And \"first\" order interactions are just the arguments passed through <code>unique</code> (as they were simplified in the previous iteration).</p>\n\n<pre><code>overlap <- function(l) {\n results <- lapply(l, unique)\n\n # combinations of m elements of list l\n for (m in seq(along=l)[-1]) {\n\n # generate and iterate through combinations of length m\n for (indices in combn(seq(length(l)), m, simplify=FALSE)) {\n\n # make name by concatenating the names of the elements\n # of l that we're intersecting\n name_1 <- paste(names(l)[indices[-m]], collapse=\"_\")\n name_2 <- names(l)[indices[m]]\n name <- paste(name_1, name_2, sep=\"_\")\n\n results[[name]] <- intersect(results[[name_1]], results[[name_2]])\n\n }\n }\n results\n}\n</code></pre>\n\n<p>If you really want to eliminate more duplicate calculations, you can assign <code>names(l)</code> outside both loops and <code>length(l)</code> outside the outer loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T08:33:46.380",
"Id": "28564",
"Score": "0",
"body": "Hi Brian, Thanks! That's very slick and quite a bit more efficient than what I started with."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T20:18:39.267",
"Id": "17931",
"ParentId": "17905",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "17931",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T22:07:18.310",
"Id": "17905",
"Score": "3",
"Tags": [
"r"
],
"Title": "Compute intersections of all combinations of vectors in a list of vectors in R"
}
|
17905
|
<blockquote>
<p>Given two strings str1 and str2, write a function that prints all
interleavings of the given two strings. You may assume that all
characters in both strings are different</p>
<p>Example:</p>
<pre><code>Input: str1 = "AB", str2 = "CD"
Output:
ABCD
ACBD
ACDB
CABD
CADB
CDAB
Input: str1 = "AB", str2 = "C"
Output:
ABC
ACB
CAB
</code></pre>
<p><a href="https://stackoverflow.com/questions/6804956/interleaving-of-two-strings">The idea</a> comes from Ray Toal:</p>
<p>The base case is when one of the two strings are empty:</p>
<pre><code>interleave(s1, "") = {s1}
interleave("", s2) = {s2}
</code></pre>
<p>Notice the order of the arguments doesn't really matter, because</p>
<pre><code>interleave("ab", "12") = {"ab12", "a1b2", "1ab2", "a12b", "1a2b", "12ab"} = interleave("12", "ab")
</code></pre>
<p>So since the order doesn't matter we'll look at recursing on the length of the first string.</p>
<p>Okay so let's see how one case leads to the next. I'll just use a
concrete example, and you can generalize this to real code.</p>
<pre><code>interleave("", "abc") = {"abc"} interleave("1", "abc") = {"1abc",
"a1bc", "ab1c", "abc1"} interleave("12", "abc") = {"12abc", "1a2bc",
"1ab2c", "1abc2", "a12bc", "a1b2c", "a1bc2", "ab12c", "ab1c2" "abc12"}
</code></pre>
<p>So everytime we added a character to the first string, we formed the
new result set by adding the new character to all possible positions
in the old result set. Let's look at exactly how we formed the third
result above from the second. How did each element in the second
result turn into elements in the third result when we added the "2"?</p>
<pre><code>"1abc" => "12abc", "1a2bc", "1ab2c", "1abc2" "a1bc" => "a12bc",
"a1b2c", "a1bc2" "ab1c" => "ab12c", "ab1c2" "abc1" => "abc2"
</code></pre>
<p>Now look at things this way:</p>
<pre><code>"1abc" => {1 w | w = interleave("2", "abc")} "a1bc" => {a1 w | w =
interleave("2", "bc")} "ab1c" => {ab1 w | w = interleave("2", "c")}
"abc1" => {abc1 w | w = interleave("2", "")}
</code></pre>
</blockquote>
<p>The following is my code building on top of the above idea. Can anyone help me verify it? </p>
<pre><code>void interleaving(const string& s2, string result, int start, int depth)
{
if(depth == s2.size())
cout << result << endl;
else
{
for(int i = start; i <= result.size(); ++i)
{
result.insert(i, 1, s2[depth]);
interleaving(s2, result, i+1, depth+1);
result.erase(i, 1);
}
}
}
int main()
{
string s1("");
string s2("12");
string result(s1);
interleaving(s2, result, 0, 0);
system("pause");
return 0;
}
</code></pre>
<p>There is another much more beautiful solution for this problem comes from an unknown friend <a href="http://www.geeksforgeeks.org/archives/17743" rel="nofollow noreferrer">akash01</a>:</p>
<pre><code>void printIlsRecur (char *str1, char *str2, char *iStr, int m, int n, int i)
{
// Base case: If all characters of str1 and str2 have been included in
// output string, then print the output string
if ( m==0 && n ==0 )
{
printf("%s\n", iStr) ;
}
// If some characters of str1 are left to be included, then include the
// first character from the remaining characters and recur for rest
if ( m != 0 )
{
iStr[i] = str1[0];
printIlsRecur (str1 + 1, str2, iStr, m-1, n, i+1);
}
// If some characters of str2 are left to be included, then include the
// first character from the remaining characters and recur for rest
if ( n != 0 )
{
iStr[i] = str2[0];
printIlsRecur (str1, str2+1, iStr, m, n-1, i+1);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T14:05:48.103",
"Id": "28534",
"Score": "4",
"body": "There is a standard function to do this: `std::next_permutation()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T14:48:48.990",
"Id": "28539",
"Score": "0",
"body": "@LokiAstari, thanks very much. If it was an interview question and ask you to write the code by yourself, can you help me check it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T23:54:47.080",
"Id": "28554",
"Score": "0",
"body": "Why not test it with the examples you gave in the question? Also, does it have to be recursive? Your last question used recursion too... (perhaps you should be learning Haskell)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T00:17:22.110",
"Id": "28555",
"Score": "0",
"body": "@WilliamMorris, I've tested a lot of cases including the examples given in the question. It seems it's right. I'm doing practice in recursive algorithm. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T07:07:35.650",
"Id": "28674",
"Score": "1",
"body": "@LokiAstari Given that the characters from either input string occur in the same order in the output as in the respective input, how does `next_permutation` help?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-26T05:50:42.960",
"Id": "230924",
"Score": "0",
"body": "nice and detailed explanation: http://javabypatel.blogspot.in/2016/03/print-all-interleaving-of-given-two-strings.html"
}
] |
[
{
"body": "<p>Your algorithm is correct, as you explained. However, I didn't find the code easy to understand.</p>\n\n<p>Staying within the spirit of your solution, I've cleaned it up a bit:</p>\n\n<ul>\n<li>Renamed <code>s2</code> → <code>s1</code> (because <code>s2</code> coming first is confusing), <code>result</code> → <code>s2</code>.</li>\n<li>Renamed <code>depth</code> → <code>i1</code>, <code>start</code> → <code>i2</code> to emphasize their relationship with <code>s1</code> and <code>s2</code>.</li>\n<li>Swapped the order of the last two parameters for parallelism.</li>\n<li>Provided defaults for the last two parameters to make <code>main()</code> prettier.</li>\n<li>Eliminated the variable <code>i</code>, because using <code>i2</code> directly is clearer.</li>\n<li>Used an early return to reduce a level of indentation.</li>\n</ul>\n\n<p>Simultaneously tracking all of those substitutions is tricky, but here is the result:</p>\n\n<pre><code>void interleaving(const string& s1, string s2, int i1=0, int i2=0)\n{\n if (i1 == s1.size())\n {\n cout << s2 << endl;\n return;\n }\n\n // Transfer the first character of s1 into s2\n // anywhere after the last previously inserted\n // character from s1.\n for ( ; i2 <= s2.size(); i2++)\n {\n s2.insert(i2, 1, s1[i1]);\n interleaving(s1, s2, i1 + 1, i2 + 1);\n s2.erase(i2, 1); // Undo the insert() above\n }\n}\n</code></pre>\n\n<p>Since passing the second parameter by value would cause it to be copied unnecessarily on each recursive call, you might want to change it to be passed by reference instead.</p>\n\n<pre><code>static void interleaving_helper(const string& s1, string &s2, int i1, int i2)\n{\n if (i1 == s1.size())\n {\n cout << s2 << endl;\n return;\n }\n\n for ( ; i2 <= s2.size(); i2++)\n {\n s2.insert(i2, 1, s1[i1]);\n interleaving_helper(s1, s2, i1 + 1, i2 + 1);\n s2.erase(i2, 1); // Undo the insert above\n }\n}\n\nvoid interleaving(const string& s1, string s2, int i1=0, int i2=0)\n{\n interleaving_helper(s1, s2, i1, i2);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T10:40:15.633",
"Id": "44499",
"ParentId": "17909",
"Score": "2"
}
},
{
"body": "<p>For comparison, here's a \"pure\" recursive solution that resembles the solution by akash01. It isn't implemented efficiently, but it illustrates the elegance of recursion and is a good starting point.</p>\n\n<pre><code>void interleave(const std::string s1, const std::string s2, const std::string result=\"\") {\n if (s1.empty() && s2.empty()) {\n std::cout << result << std::endl;\n return;\n }\n if (!s1.empty()) {\n interleave(s1.substr(1), s2, result + s1[0]);\n }\n if (!s2.empty()) {\n interleave(s1, s2.substr(1), result + s2[0]);\n }\n}\n</code></pre>\n\n<p>That pure solution involves a lot of copying, so here's an adaptation to make it more idiomatic C++:</p>\n\n<pre><code>/* Helper function */\nstatic void interleave(std::string::const_iterator s1, std::string::const_iterator end1,\n std::string::const_iterator s2, std::string::const_iterator end2,\n const std::string &result = \"\") {\n if (s1 == end1 && s2 == end2) {\n std::cout << result << std::endl;\n return;\n }\n if (s1 != end1) {\n interleave(s1 + 1, end1, s2, end2, result + *s1);\n }\n if (s2 != end2) {\n interleave(s1, end1, s2 + 1, end2, result + *s2);\n }\n}\n\nvoid interleave(const std::string &s1, const std::string &s2) {\n interleave(s1.begin(), s1.end(), s2.begin(), s2.end());\n}\n</code></pre>\n\n<p>You might compromise purity for a further performance gain by using <code>result</code> as a mutable buffer:</p>\n\n<pre><code>static void interleave(std::string::const_iterator s1, std::string::const_iterator end1,\n std::string::const_iterator s2, std::string::const_iterator end2,\n std::string &result) {\n if (s1 == end1 && s2 == end2) {\n std::cout << result << std::endl;\n return;\n }\n if (s1 != end1) {\n interleave(s1 + 1, end1, s2, end2, result.append(1, *s1));\n result.pop_back();\n }\n if (s2 != end2) {\n interleave(s1, end1, s2 + 1, end2, result.append(1, *s2));\n result.pop_back();\n }\n}\n\nvoid interleave(const std::string &s1, const std::string &s2) {\n std::string buffer;\n buffer.reserve(s1.length() + s2.length()); // optional\n interleave(s1.begin(), s1.end(), s2.begin(), s2.end(), buffer);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T10:41:18.117",
"Id": "44500",
"ParentId": "17909",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T02:57:11.637",
"Id": "17909",
"Score": "2",
"Tags": [
"c++",
"strings",
"recursion",
"combinatorics"
],
"Title": "Print all interleavings of two given strings"
}
|
17909
|
<p>Here is a code I want to simplify:</p>
<pre><code>public void Method1(Context context, EventLog log = null)
{
Class myClass = ConvertToMyClass();
ApiCall1 apiCall = new ApiCall1(context);
if (log != null)
{
eventLog.WriteEntry("Starting");
}
try
{
apiCall.Call1(myClass, null, false);
IsCallSuccess = true;
}
catch (Exception e)
{
if (log != null)
{
eventLog.WriteEntry("error");
}
IsCallSuccess= false;
CallErrorMessage = e.Message;
}
}
public void Method2(Context context, EventLog log = null)
{
Class myClass = ConvertToMyClass();
ApiCall2 apiCall = new ApiCall2(context);
if (log != null)
{
eventLog.WriteEntry("Starting");
}
try
{
apiCall.Call1(myClass);
NewItemID = myClass.ItemID;
IsCallSuccess = true;
}
catch (Exception e)
{
if (log != null)
{
eventLog.WriteEntry("error");
}
IsCallSuccess= false;
CallErrorMessage = e.Message;
}
}
public void Method3Context context, EventLog log = null)
{
Class myClass = ConvertToMyClass();
ApiCall3 apiCall = new ApiCall3(context);
if (log != null)
{
eventLog.WriteEntry("Starting");
}
try
{
apiCall.Call3(myClass, "param1");
UpdatedItemID = myClass.UpdatedItemID;
IsCallSuccess = true;
}
catch (Exception e)
{
if (log != null)
{
eventLog.WriteEntry("error");
}
IsCallSuccess= false;
CallErrorMessage = e.Message;
}
}
</code></pre>
<p>There are 3 methods. I've been thinking about how I could simplify them using delegates or lambdas and didn't find anything.</p>
<p>Note that ApiCall1/2/3 are all defined in a third-party library.
Your thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T11:42:12.573",
"Id": "28520",
"Score": "0",
"body": "Do ApiCall1/2/3 all implement the same base class or interface?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T16:03:24.690",
"Id": "28683",
"Score": "0",
"body": "Yes, they do..."
}
] |
[
{
"body": "<p>Alright, let's see if we can <s>simplify</s>abstract this for you. I'm not going to say simplify because often times abstracting something is far from simplifying it.</p>\n\n<p>I <strong>think</strong> you can turn the method into something like this:</p>\n\n<pre><code>public void Method<T>(Context context, Action<T, Class> body, EventLog log = null)\n{\n Class myClass = ConvertToMyClass();\n T apiCall = Activator.CreateInstance(typeof(T), new [] { context });\n if (log != null)\n {\n eventLog.WriteEntry(\"Starting\");\n }\n\n try\n {\n body(apiCall, class);\n IsCallSuccess = true;\n }\n catch (Exception e)\n {\n if (log != null)\n {\n eventLog.WriteEntry(\"error\");\n }\n\n IsCallSuccess = false;\n CallErrorMessage = e.Message;\n }\n}\n</code></pre>\n\n<p>... then you should be able to call it like this:</p>\n\n<pre><code>// Method1\nMethod<ApiCall1>(\n yourContextInstance,\n (apiCall, myClass) =>\n {\n apiCall.Call1(myClass, null, false);\n },\n yourLogInstance);\n\n// Method2\nMethod<ApiCall2>(\n yourContextInstance,\n (apiCall, myClass) =>\n {\n apiCall.Call1(myClass);\n NewItemID = myClass.ItemID;\n },\n yourLogInstance);\n\n// Method3\nMethod<ApiCall3>(\n yourContextInstance,\n (apiCall, myClass) =>\n {\n apiCall.Call3(myClass, \"param1\");\n UpdatedItemID = myClass.UpdatedItemID;\n },\n yourLogInstance);\n</code></pre>\n\n<p>... one caveat is <code>NewItemID</code> and <code>UpdatedItemID</code>. If you're not making these calls from inside the class <code>Method</code> is defined in, you may need to modify this a tad to get the <code>Method</code> to return and integer instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T11:58:23.637",
"Id": "28679",
"Score": "0",
"body": "Instead of `Activator.CreateInstance()`, you could use another delegate to make it more type-safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T16:05:07.140",
"Id": "28684",
"Score": "0",
"body": "I agree with svick."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T11:58:26.117",
"Id": "17917",
"ParentId": "17911",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T06:36:13.737",
"Id": "17911",
"Score": "3",
"Tags": [
"c#",
".net"
],
"Title": "How do I simplify the code in C#?"
}
|
17911
|
<p>I have implemented a Non Reentrant Lock. I want to know if this has any mistakes, race conditions etc. I am aware of the fact that existing libraries have to be used (instead of writing our own), but this is just to see if I am understanding the java concurrency correctly. Any feedback is appreciated.</p>
<pre><code>public class MyLock {
private boolean isLocked = false;
private long owner = -1;
private static String TAG = "MyLock: ";
public synchronized void Lock() throws InterruptedException, IllegalStateException {
if(owner == Thread.currentThread().getId()) {
throw new IllegalStateException("Lock already acquired. " +
"This lock is not reentrant");
} else {
while(isLocked == true) {
System.out.println(TAG+"Waiting for Lock, Tid = " +
Thread.currentThread().getId());
wait();
}
}
isLocked = true;
owner = Thread.currentThread().getId();
System.out.println(TAG+"Lock Acquired: Owner = " + owner);
}
public synchronized void Unlock() throws IllegalStateException {
if(!isLocked || owner != Thread.currentThread().getId()) {
throw new IllegalStateException("Only Owner can Unlock the lock");
} else {
System.out.println(TAG+"Unlocking: Owner = " + owner);
owner = -1;
isLocked = false;
notify();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T12:54:55.473",
"Id": "28525",
"Score": "0",
"body": "Your `wait()` action lock the `while(..)`, you have to give wait[Time](inMilliseconds)."
}
] |
[
{
"body": "<p>Shouldn't isLocked be set to <code>true</code> somewhere in here? It seems like when this thread gets notified, it will just print \"lock acquired\" without actually acquiring the lock and setting the owner to itself.</p>\n\n<pre><code> wait();\n }\n // Perhaps here you set isLocked to true and owner to \"me\"?\n }\n}\nSystem.out.println(TAG+\"Lock Acquired: Owner = \" + owner);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T07:52:38.437",
"Id": "28558",
"Score": "0",
"body": "Oops, good catch!! Fixed it now. Regarding printing, it should print all the threads that are waiting since, wait() releases the Object lock."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T07:53:44.423",
"Id": "28559",
"Score": "0",
"body": "Ahh, ok. I've edited that part out of my answer; I'm pretty new to java concurrency myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T08:03:44.667",
"Id": "28561",
"Score": "0",
"body": "yeah me too. Still experimenting with java concurrency. I come from a pThreads background where basic implementation of locks are non-reentrant. I did not find any such lock in Java collections, so implemented one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T13:37:39.643",
"Id": "28583",
"Score": "1",
"body": "@vikky.rk if you are looking for additional feedback, I'd strongly suggest un-accepting this answer and waiting a few days. You can always re-accept later, but it will encourage others to contribute."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T02:50:59.643",
"Id": "28673",
"Score": "0",
"body": "@codesparkle: Ok done"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T06:46:39.467",
"Id": "17945",
"ParentId": "17913",
"Score": "3"
}
},
{
"body": "<p>Your code works, but its quality leaves some room for improvement. It should be simplified by refactoring.\nHere are some suggestions:</p>\n\n<h2>Naming</h2>\n\n<p>Even if it is only an exercise, utmost care should be applied when choosing names to make sure they are descriptive and clear, but also to comply with coding conventions:</p>\n\n<ul>\n<li>Consider calling your class <code>NonReentrantLock</code> instead of <code>MyLock</code>.</li>\n<li>Methods should be camel-case, starting with a lower-case character, so <code>Lock()</code> should be <code>lock()</code> and <code>Unlock()</code> should be <code>unlock()</code>.</li>\n<li>Only constants should be upper-case, so <code>TAG</code> should be made a constant. But <code>TAG</code> can mean anything. The solution is to refactor your code (as shown below) such that <code>TAG</code> is only used once and is no longer needed as a class variable.</li>\n</ul>\n\n<h2>Constants</h2>\n\n<ul>\n<li><p><code>TAG</code> is not a useful constant because it leads to lots of <code>System.out.println</code> calls which you want to avoid. All your logging should happen in a single place, not be spread out over your class.</p></li>\n<li><p>However, you are using the magic value of <code>-1</code> to show that nobody owns the lock at the moment. You should introduce a constant <code>NOBODY</code> and use that to set <code>owner</code>:</p>\n\n<pre><code>private static final long NOBODY = -1;\nprivate long owner = NOBODY;\n</code></pre></li>\n</ul>\n\n<h2>Redundancy</h2>\n\n<h3>Tracking the same state twice</h3>\n\n<p>Look carefully at your instance variables <code>owner</code> and <code>isLocked</code>. Track their values during runtime with the debugger, and you will see: <em>if <code>owner == -1</code> then <code>isLocked == false</code>, but if owner != -1 then isLocked == true</em>. In other words, you are using two variable to track the same piece of state.</p>\n\n<p>You should remove <code>isLocked</code> and replace it it with the following method:</p>\n\n<pre><code>private synchronized boolean isLocked() {\n return owner != NOBODY;\n}\n</code></pre>\n\n<h3>Doing the same string concatenations multiple times</h3>\n\n<p>You have used <code>System.out.println</code> throughout your code, always passing <code>TAG</code>, a message, and a thread id. You can extract this functionality into a new method:</p>\n\n<pre><code>private void log(String message, long threadId) {\n System.out.println(String.format(\"MyLock: %s %s\", message, threadId));\n}\n</code></pre>\n\n<p>That way, <code>System.out.println</code> is only called in a single place and can easily be disabled or replaced with a real logger. For instance, this:</p>\n\n<pre><code>System.out.println(TAG+\"Lock Acquired: Owner = \" + owner);\n</code></pre>\n\n<p>can become this:</p>\n\n<pre><code>log(\"lock acquired, owner =\", owner);\n</code></pre>\n\n<h3>Miscellaneous redundancies</h3>\n\n<ul>\n<li><p>If you throw an exception, inside an if-structure, you the <code>else</code> branch is redundant, so code like</p>\n\n<pre><code>if (condition) {\n throw new IllegalStateException(...);\n} else {\n doSomethingElse();\n}\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>if (condition) {\n throw new IllegalStateException(...);\n}\ndoSomethingElse();\n</code></pre></li>\n<li><p>You have code duplication when checking if the current thread is the owner of the lock. Refactor out this method instead:</p>\n\n<pre><code>private boolean ownerIsCurrentThread() {\n return owner == Thread.currentThread().getId();\n}\n</code></pre></li>\n<li><p>You should extract argument validation into a separate method:</p>\n\n<pre><code>private void throwIf(boolean condition, String message) throws IllegalStateException {\n if (condition) {\n throw new IllegalStateException(message);\n }\n}\n</code></pre>\n\n<p>which will allow you to replace your argument validation if-statements with code like</p>\n\n<pre><code>throwIf(ownerIsCurrentThread(), \"the lock has already been acqired\");\n</code></pre></li>\n</ul>\n\n<h2>Error messages</h2>\n\n<p>At the beginning of <code>unlock()</code>, you throw an <code>IllegalStateException</code> with the same message for two completely different reasons. That's not very helpful for debugging. Instead, check them separately:</p>\n\n<pre><code>public synchronized void unlock() throws IllegalStateException {\n throwIf(!isLocked(), \"only a locked lock can be unlocked\");\n throwIf(!ownerIsCurrentThread(), \"only owner can unlock the lock\");\n</code></pre>\n\n<h1>End Result</h1>\n\n<pre><code>public class NonReentrantLock {\n private static final long NOBODY = -1;\n private long owner = NOBODY;\n\n public synchronized void lock() throws InterruptedException, IllegalStateException {\n throwIf(ownerIsCurrentThread(), \"the lock has already been acqired\");\n long threadId = Thread.currentThread().getId();\n while (isLocked()) {\n log(\"waiting for lock on thread\", threadId);\n wait();\n }\n owner = threadId;\n log(\"lock acquired, owner =\", owner);\n }\n\n public synchronized void unlock() throws IllegalStateException {\n throwIf(!isLocked(), \"only a locked lock can be unlocked\");\n throwIf(!ownerIsCurrentThread(), \"only owner can unlock the lock\");\n log(\"unlocking, owner =\", owner);\n owner = NOBODY;\n notify();\n }\n\n private synchronized boolean isLocked() {\n return owner != NOBODY;\n }\n\n private boolean ownerIsCurrentThread() {\n return owner == Thread.currentThread().getId();\n }\n\n private void throwIf(boolean condition, String message) throws IllegalStateException {\n if (condition) {\n throw new IllegalStateException(message);\n }\n }\n\n private void log(String message, long threadId) {\n System.out.println(String.format(\"MyLock: %s %s\", message, threadId));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T19:11:16.527",
"Id": "28690",
"Score": "1",
"body": "Thanks for the detailed feedback, really appreciate it. I am aware of most of the things you mentioned, but my main focus here was Java concurrency. However I agree with you, I will make sure I post a clean code next time, so that reviewers can have more clarity."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T14:15:33.200",
"Id": "17990",
"ParentId": "17913",
"Score": "5"
}
},
{
"body": "<p>I have read Java Concurrency In Practice and the authors give tips on building custom synchronizers. The AbstractQueuedSynchronizer is the perfect starting point for this purpose. The AQS holds a simple volatile variable integer state which is the 'synchronization state'. The <code>tryAcquire()</code> and <code>tryRelease()</code> are the main methods required to be overridden to implement your Custom Synchronizer. These methods grant the thread exclusive access to the state of the object. The shared and interruptible versions of these methods finally invoke one of these two methods to acquire/release the lock. The <code>compareAndSetState(expectedValue, newValue)</code> is atomic and changes the state of the synchronizer. For a Lock this is from 0 to 1.</p>\n\n<pre><code>import java.util.concurrent.TimeUnit;\nimport java.util.concurrent.locks.AbstractQueuedSynchronizer;\n\npublic class NonRentrantLock {\n private final Sync sync = new Sync();\n\n public void unlock() {\n\n sync.release(0);\n }\n\n public boolean tryLock(int time, TimeUnit timeUnit)\n throws InterruptedException {\n\n return sync.tryAcquireNanos(0, timeUnit.toNanos(time));\n }\n\n private static class Sync extends AbstractQueuedSynchronizer {\n\n /* is the lock already held by some thread ? */\n protected boolean isHeldExclusively() {\n return getState() == 1;\n }\n\n /*\n * tryAcquire first checks the lock state. If it is unheld, it tries to\n * update the lock state to indicate that it is held.\n */\n protected boolean tryAcquire(int acquires) {\n\n if (compareAndSetState(0, 1)) {\n setExclusiveOwnerThread(Thread.currentThread());\n return true;\n }\n return false;\n }\n\n /*\n * tryRelease first checks the lock state. If it is unheld, it throws\n * and IllegalMonitorStateException else it tries to update the lock\n * state to indicate that it is unheld.\n */\n protected boolean tryRelease(int releases) {\n\n if (getState() == 0)\n throw new IllegalMonitorStateException();\n setExclusiveOwnerThread(null);\n setState(0);\n return true;\n }\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T19:14:25.620",
"Id": "28692",
"Score": "0",
"body": "As of now I haven't looked at Java concurrency in practice, so I used my basic understanding of Locks/Synchronization to implement a basic version. I will go through AbstractQueuedSynchronizer and try to implement a better version. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T17:24:08.277",
"Id": "17994",
"ParentId": "17913",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>Consider using <code>notifyAll</code> instead of <code>notify</code>:</p>\n\n<blockquote>\n <p>A related issue is whether you should use <code>notify</code> or <code>notifyAll</code> to wake waiting threads. \n (Recall that <code>notify</code> wakes a single waiting thread, assuming such a\n thread exists, and <code>notifyAll</code> wakes all waiting threads.) It is often said that you\n should <em>always</em> use <code>notifyAll</code>. This is reasonable, conservative advice. It will\n always yield correct results because it guarantees that you’ll wake the threads that\n need to be awakened. You may wake some other threads, too, but this won’t affect\n the correctness of your program. These threads will check the condition for which\n they’re waiting and, finding it false, will continue waiting.</p>\n \n <p>[...]</p>\n</blockquote>\n\n<p>From: <em>Effective Java, 2nd Edition</em>, <em>Item 69: Prefer concurrency utilities to wait and notify</em></p></li>\n<li><p>I'd use a private lock object instead of synchronizing on <code>this</code> with synchronized methods.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/442564/843804\">Avoid synchronized(this) in Java?</a></li>\n<li><em>Java Concurrency in Practice, 4.2.1. The Java Monitor Pattern</em></li>\n<li><em>Item 70: Document thread safety</em> in <em>Effective Java, 2nd Edition</em> also mentions this pattern.</li>\n</ul></li>\n<li><p>A small note to codesparkle's great answer: Instead of the <code>throwIf</code> method I'd use <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkState%28boolean,%20java.lang.Object%29\" rel=\"nofollow noreferrer\">Guava's <code>checkState</code></a> here. I would prefer this because it's obvious that the method throws <code>IllegalStateException</code>, it's in its name. (It also has <code>checkArgument</code> methods which throw <code>IllegalArgumentException</code> and <code>checkNotNull</code> methods with <code>NullPointerException</code>.)</p></li>\n<li><p>I'd use a <a href=\"https://stackoverflow.com/a/2727536/843804\">logger framework instead of <code>System.out.println</code> statements</a>. I suggest you <a href=\"http://slf4j.org/faq.html#logging_performance\" rel=\"nofollow noreferrer\">SLF4J with parameterized messages</a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T06:07:26.923",
"Id": "18007",
"ParentId": "17913",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "17990",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T10:25:14.247",
"Id": "17913",
"Score": "3",
"Tags": [
"java",
"locking",
"synchronization"
],
"Title": "Java Non Reentrant Lock Implementation"
}
|
17913
|
<p>I have a gridview with <code>CheckBox</code> inside it. When the user selects a row and clicks
on a button, a message is sent for the specific user.</p>
<p>How can this be optimized?</p>
<pre><code>protected void btnSendSMSForSpeceficUser_Click(object sender, EventArgs e)
{
using (NoavaranModel.NoavaranEntities1 dbContext=new NoavaranModel.NoavaranEntities1())
{
int userId = Int32.Parse(Session["UserId"].ToString());
var query = (from p in dbContext.Users
where p.UserId == userId
select p.CountOfSMS).FirstOrDefault();
var query2 = (from p in dbContext.Users
where p.UserId == userId
select p).FirstOrDefault();
int j = 0,sendCount=0;
for (int i = 0; i <= grdStudents.Rows.Count - 1; i++)
{
string MobileNumbers = grdStudents.Rows[i].Cells[2].Text;
int stID = Int32.Parse(grdStudents.Rows[i].Cells[0].Text);
var query3 = (from p in dbContext.Students
where p.Id == stID
where p.IsRecivedSMS==false
select p).FirstOrDefault();
GridViewRow row = grdStudents.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("chkSelectStudents");
if (Ckbox.Checked)
{
j++;
if (j <= query) {
sendCount++;
Utility.SendMessageForStudents(MobileNumbers, txtMessage.Text);
query3.IsRecivedSMS = true;
}
}
}
query2.CountOfSMS = query.Value - sendCount;
dbContext.SaveChanges();
ListBox1.Items.Add(sendCount.ToString());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>To be perfectly honest it seems quite optimized to me. And to prove that point, about the only thing you could change is making it so you only make one round trip to the server for all of the ID's, but that would also force you to iterate that list twice, consider the following code:</p>\n\n<pre><code>// list of ID's that need their IsReceivedSMS set to true\nvar ids = grdStudents.Rows;\n\nfor (int i = 0; i <= grdStudents.Rows.Count - 1; i++)\n{\n string MobileNumbers = grdStudents.Rows[i].Cells[2].Text;\n int stID = Int32.Parse(grdStudents.Rows[i].Cells[0].Text);\n\n GridViewRow row = grdStudents.Rows[i];\n CheckBox Ckbox = (CheckBox)row.FindControl(\"chkSelectStudents\");\n if (Ckbox.Checked)\n {\n j++;\n if (j <= query) {\n sendCount++;\n Utility.SendMessageForStudents(MobileNumbers, txtMessage.Text);\n\n // we've sent the SMS so let's queue it for update\n ids.Add(stID);\n }\n }\n}\n\n// this **should** generate an IN clause on the server\n// allowing you to perform just **one** round trip\nvar query3 = (from p in dbContext.Students\n where ids.Contains(p.Id)\n where p.IsRecivedSMS==false\n select p).ToList();\n\n// here is the second iteration\nquery3.ForEach(o => o.IsRecivedSMS = true)\n</code></pre>\n\n<p>However, if that query to <code>Students</code> is heavy (which it seems unlikely but it <strong>could</strong> be), the iterating a <strong><em>very select</em></strong> list a second time would be less expensive.</p>\n\n<p>Again, there are some things that need to be considered here that I have no knowledge of.</p>\n\n<p>So, to recap, the code you originally posted makes one round trip for every ID regardless of its need to update <code>IsReceivedSMS</code> whereas this example makes one round trip for the very select list that needs updated. However, there are times that performing this type of optimization literally holds no value, and thus my original statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T11:47:06.447",
"Id": "28521",
"Score": "0",
"body": "thanks,i want admin can select specific users in Gridview and send message for them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T12:09:11.630",
"Id": "28523",
"Score": "0",
"body": "@SirwanAfifi, certainly, and that's what your current code is doing. All I did was pull the query that determines the rows to update out into one query instead of many small ones. Again, often time optimizations like this cause more problems than they help, you have to determine that based on whether or not you **already** have a performance issue."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T11:37:09.253",
"Id": "17915",
"ParentId": "17914",
"Score": "2"
}
},
{
"body": "<p>I'm not sure of everything (worked with notepad) but:</p>\n\n<pre><code>protected void btnSendSMSForSpeceficUser_Click(object sender, EventArgs e)\n{\n using (NoavaranModel.NoavaranEntities1 dbContext = new NoavaranModel.NoavaranEntities1())\n {\n var userId = int.Parse(Session[\"UserId\"].ToString());\n\n var user = dbContext.Users.FirstOrDefault(p => p.UserId == userId);\n var countOfSms = user.CountOfSMS.Value;\n var j = 0;\n foreach (var row in grdStudents.Rows)\n {\n var cells = row.Cells;\n var MobileNumbers = cells[2].Text;\n var stID = int.Parse(cells[0].Text);\n\n var student = dbContext.Students.FirstOrDefault(p => p.Id == stID && !p.IsRecivedSMS);\n\n var Ckbox = (CheckBox)row.FindControl(\"chkSelectStudents\");\n if (Ckbox.Checked)\n {\n j++;\n if (j <= countOfSms) {\n Utility.SendMessageForStudents(MobileNumbers, txtMessage.Text);\n student.IsRecivedSMS = true;\n\n user.CountOfSMS = countOfSms - 1;\n }\n }\n }\n\n dbContext.SaveChanges();\n ListBox1.Items.Add(sendCount.ToString());\n }\n}\n</code></pre>\n\n<p>This is a cleaner version of your code with less query (the first was unneccesary) and inside the loop you are making a lot of small query which can be really bad but first you have to modify your code to not work directly with the context in you page code but through an interface (first iterate through the rows and get all data then pass them to the worker (which can work with the context) and return the result & update the UI).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T13:35:51.913",
"Id": "28529",
"Score": "0",
"body": "thanks great,\ni have a table called 'SMSLog' with these fields(id,userName,datetime,stMobileNo)\nand i want to log all messages that admin send,where can i place code is better?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T11:41:00.477",
"Id": "17916",
"ParentId": "17914",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "17916",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T11:01:25.707",
"Id": "17914",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Sending a message based on selected row"
}
|
17914
|
<p>Please review this code, which should calculate the tax percentage a person will pay in a progressive tax system. The goal is to have a perfect program.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class TaxLevel
{
private decimal _Money=-1;
/// <summary>
/// the money count that the tax applies to
/// </summary>
public decimal Money
{
get { return _Money; }
set { if (value > 0) { _Money = value; } else { throw new ArgumentOutOfRangeException("Money must be grater than 0"); } }
}
private decimal _TaxDeduction=-1;
/// <summary>
/// the tax level where 1.0 is 100% tax
/// </summary>
public decimal TaxDeduction
{
get { return _TaxDeduction; }
set { if (value > 0 && value < 1.0m) { _TaxDeduction = value; } else { throw new ArgumentOutOfRangeException("TaxDeduction must be between 0.0 and 1.0"); } }
}
}
class TaxCalculator
{
List<TaxLevel> _TaxLevels;
public bool DeterminateTaxLevels(){
_TaxLevels = new List<TaxLevel>();
_TaxLevels.Add(new TaxLevel {Money = 4770m, TaxDeduction = 0.10m });
_TaxLevels.Add(new TaxLevel { Money = 3700, TaxDeduction = 0.14m });
_TaxLevels.Add(new TaxLevel { Money = 4249m, TaxDeduction = 0.20m });
_TaxLevels.Add(new TaxLevel { Money = 5529m, TaxDeduction = 0.28m });
_TaxLevels.Add(new TaxLevel { Money = 21089m, TaxDeduction = 0.31m });
_TaxLevels.Add(new TaxLevel { Money = decimal.MaxValue, TaxDeduction = 0.42m });
return true;
}
/// <summary>
/// Gets Salley In Bruto Calculates Netto Sallery
/// </summary>
/// <param name="SalleryInNis">Employee Bruto Sallery</param>
/// <returns>Neto Sallery</returns>
public decimal CalculateNetto(decimal SalleryInNis)
{
if (SalleryInNis < 0) throw new ArgumentOutOfRangeException("SalleryInNis must be greater than 0");
if (_TaxLevels == null) throw new ArgumentNullException("DeterminateTaxLevels First");
decimal TmpSallery =SalleryInNis;
decimal Netto = 0.0m;
foreach (var taxlevel in _TaxLevels)
{
if (TmpSallery <= 0) break;
if (TmpSallery > taxlevel.Money)
{
Netto += taxlevel.Money * (1-taxlevel.TaxDeduction);
}
else {
Netto += TmpSallery * (1-taxlevel.TaxDeduction);
}
TmpSallery -= taxlevel.Money;
}
return Netto;
}
/// <summary>
/// Calculates Average Tax for employee
/// </summary>
/// <param name="SalleryInNis">Employee Bruto Sallery</param>
/// <returns>AverageTax</returns>
public decimal CalculateAverageTax(decimal SalleryInNis)
{
if (SalleryInNis < 0) throw new ArgumentOutOfRangeException("SalleryInNis must be greater than 0");
return 1- (CalculateNetto(SalleryInNis) / SalleryInNis);
}
}
class Program
{
static void Main(string[] args)
{
decimal Sal= 11712000;
TaxCalculator TaxCalculator = new TaxCalculator();
TaxCalculator.DeterminateTaxLevels();
Console.WriteLine("Brutto " + Sal);
Console.WriteLine("Netto " + TaxCalculator.CalculateNetto(Sal));
Console.WriteLine("Average Tax " + TaxCalculator.CalculateAverageTax(Sal));
Console.Read();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Define \"perfect program\". If it works every time and does not have any bugs then I say it is perfect.</p>\n\n<p>Having said that, if you are looking for ways that you may improve the code...</p>\n\n<ul>\n<li><p>Your code does not following <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx\" rel=\"nofollow\">coding standards</a>... Not that everyone follows the same set of standards but your code seems to miss quite a few. Coding standards are important because when people review your code or maintain it in the future it is easier and less frustrating for them to read it from the start.</p></li>\n<li><p><code>DetermineTaxLevels</code> contains hard-coded values. Will the values always be the same or can they change in the future. If they can change then typically these values would be pulled from an outside source, such as an XML file or a SQL database. If they will never change then they should be defined as constant values at the top of your class or possibly in another class if they may be shared by other classes.</p></li>\n<li><p>Several other methods contain hard-coded values (magic numbers). You should consider putting these into constants as well.</p></li>\n<li><p>I do like that you have broken your class into separate methods instead of one large method. Seems like you have a good <em>separation of concerns</em>.</p></li>\n<li><p>I also like that you are guarding against invalid values.</p></li>\n</ul>\n\n<p>Hope this helps give you some things to consider.</p>\n\n<p><strong>UPDATE: To respond to your comment...</strong></p>\n\n<p>Here are the items <strong>I</strong> would change. You are welcome to take or leave these suggestions as you wish...</p>\n\n<ul>\n<li><p>Although I have seen several different guidelines about naming class level variables, I mostly see _camelCase (sometimes m_camelCase). So the <code>private decimal _Money</code> would generally be <code>private decimal _money</code> or <code>private decimal m_money</code>. Interesting enough Microsoft recommends not prefixing them with anything so it would just be <code>money</code>. They then go further to say the keyword <code>.this</code> should always be used when you refer to them within methods. I <em>really</em> don't like this standard because then you have your code cluttered with <code>this.</code> everywhere. I think most people agree with me because I mostly see class variables named in this manner <code>_camelCase</code>.</p></li>\n<li><p>Local variables should be camelCase. So in the <code>CalculateNetto</code> method the variable <code>TmpSallery</code> should be <code>tmpSallery</code></p></li>\n<li><p>Find a better place to guard your class variables instead of inside methods. Guarding class level variables inside a local method would mean you would have to do it in every method they are used.</p></li>\n<li><p>Main method should be at top.</p></li>\n<li><p>Do not put too much information on one line of code, such as your setters.</p></li>\n<li><p>Put your guard clauses at the top of a code block.</p></li>\n<li><p>If you want your code to be testable then you will want to implement interfaces and injects the interface into your methods (I am not showning the Interfaces here).</p></li>\n<li><p>I personally like to store a method call return value into a variable to help with debugging.<br/>so</p></li>\n</ul>\n\n<p><code>return 1 - (CalculateNetto(salleryInNis) / salleryInNis);</code></p>\n\n<p>would be </p>\n\n<pre><code>var netto = CalculateNetto(salleryInNis);\nreturn 1 - (netto / salleryInNis);\n</code></pre>\n\n<p>Taking all these things together...if I was to writing this here is the way it would look...</p>\n\n<pre><code>using System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n private const decimal SOME_VALUE = 11712000;\n static void Main(string[] args)\n {\n\n decimal sal = SOME_VALUE;\n ITaxCalculator taxCalculator = new TaxCalculator();\n taxCalculator.DeterminateTaxLevels();\n Console.WriteLine(\"Brutto \" + sal);\n Console.WriteLine(\"Netto \" + taxCalculator.CalculateNetto(sal));\n Console.WriteLine(\"Average Tax \" + taxCalculator.CalculateAverageTax(sal));\n Console.Read();\n }\n }\n\n class TaxLevel : ITaxLevel\n {\n private const decimal MIN_TAX_DEDUCTION = 0;\n private const decimal MAX_TAX_DEDUCTION = 1;\n\n private decimal _money = -1;\n\n /// <summary>\n /// the money count that the tax applies to\n /// </summary>\n public decimal Money\n {\n get { return _money; }\n set\n {\n if (value <= 0)\n throw new ArgumentOutOfRangeException(\"Money must be grater than 0\");\n\n _money = value;\n }\n }\n\n private decimal _taxDeduction = -1;\n /// <summary>\n /// the tax level where 1.0 is 100% tax\n /// </summary>\n public decimal TaxDeduction\n {\n get { return _taxDeduction; }\n set\n {\n if (value <= MIN_TAX_DEDUCTION || value > MAX_TAX_DEDUCTION)\n throw new ArgumentOutOfRangeException(\"TaxDeduction must be between 0.0 and 1.0\");\n\n _taxDeduction = value;\n }\n }\n\n }\n\n class TaxCalculator : ITaxCalculator\n {\n IList<ITaxLevel> _taxLevels = new List<ITaxLevel>();;\n\n public bool DeterminateTaxLevels()\n {\n // Too lazy to remove these magic numbers but they should be turned into constants\n _taxLevels.Add(new TaxLevel { Money = 4770m, TaxDeduction = 0.10m });\n _taxLevels.Add(new TaxLevel { Money = 3700, TaxDeduction = 0.14m });\n _taxLevels.Add(new TaxLevel { Money = 4249m, TaxDeduction = 0.20m });\n _taxLevels.Add(new TaxLevel { Money = 5529m, TaxDeduction = 0.28m });\n _taxLevels.Add(new TaxLevel { Money = 21089m, TaxDeduction = 0.31m });\n _taxLevels.Add(new TaxLevel { Money = decimal.MaxValue, TaxDeduction = 0.42m });\n return true;\n }\n\n /// <summary>\n /// Gets Salley In Bruto Calculates Netto Sallery\n /// </summary>\n /// <param name=\"SalleryInNis\">Employee Bruto Sallery</param>\n /// <returns>Neto Sallery</returns>\n public decimal CalculateNetto(decimal salleryInNis)\n {\n if (salleryInNis < 0) \n throw new ArgumentOutOfRangeException(\"SalleryInNis must be greater than 0\");\n\n if (_taxLevels == null) \n throw new ArgumentNullException(\"DeterminateTaxLevels First\");\n\n decimal tmpSallery = salleryInNis;\n decimal netto = MIN_TAX_DEDUCTION;\n foreach (var taxlevel in _taxLevels)\n {\n if (tmpSallery <= 0) break;\n if (tmpSallery > taxlevel.Money)\n {\n Netto += taxlevel.Money * (1 - taxlevel.TaxDeduction);\n }\n else\n {\n Netto += TmpSallery * (1 - taxlevel.TaxDeduction);\n }\n tmpSallery -= taxlevel.Money;\n }\n return netto;\n }\n\n /// <summary>\n /// Calculates Average Tax for employee\n /// </summary>\n /// <param name=\"SalleryInNis\">Employee Bruto Sallery</param>\n /// <returns>AverageTax</returns>\n public decimal CalculateAverageTax(decimal salleryInNis)\n {\n if (salleryInNis < 0) \n throw new ArgumentOutOfRangeException(\"salleryInNis must be greater than 0\");\n\n return 1 - (CalculateNetto(salleryInNis) / salleryInNis);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T14:01:53.157",
"Id": "28533",
"Score": "0",
"body": "I was refering to perfect code. as in clean extendable scaleable testable readable and efficient\n\nwhat coding standarts i didn't follow except using var? (i don't like using it)\n\nDetermineTaxLevels uses hardcoded values as it is only an interview question. In the real world of course id use a database/config file"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T13:43:02.827",
"Id": "17919",
"ParentId": "17918",
"Score": "4"
}
},
{
"body": "<ul>\n<li>If something is mandatory then use private setters and constructor arguments, and validate in the constructor (<code>TaxLevel</code>) [1];</li>\n<li>Use collection initializer notation [2];</li>\n<li><code>DeterminateTaxLevels</code> should be private and called from the constructor (I would actually make it a simple attribution in the constructor);</li>\n<li><code>DeterminateTaxLevels</code> should have a better name like <code>LoadTaxLevels</code>, because it does not "<a href=\"http://www.ldoceonline.com/popup/popupmode.html?search_str=determine\" rel=\"noreferrer\">determine</a>" anything;</li>\n<li><code>DeterminateTaxLevels</code> has no reason to return bool - why does it?;</li>\n<li>Salary is misspelt;</li>\n<li>Either call the salary "bruto" or "in Nis" - you should be consistent, and I advise "bruto" because it means more than some random <a href=\"http://en.wikipedia.org/wiki/Three-letter_acronym\" rel=\"noreferrer\">TLA</a> like NIS (whatever it is);</li>\n<li>As @<a href=\"https://codereview.stackexchange.com/a/17919/7773\">Gene S</a> said, try to follow <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx\" rel=\"noreferrer\">coding standards</a>: use brackets in ifs, use line-breaks after ifs, use camelCase on parameter names and not PascalCase, etc...</li>\n</ul>\n<hr />\n<h1>footnotes</h1>\n<p>[1]:</p>\n<pre><code>private class TaxLevel\n{\n /// <summary>\n /// The money count that the tax applies to.\n /// </summary>\n public decimal Money { get; private set; }\n /// <summary>\n /// The tax level where 1.0 is 100% tax.\n /// </summary>\n public decimal TaxDeduction { get; private set; }\n \n public TaxLevel(decimal money, decimal taxDeduction) {\n if (money < 0 ) {\n throw new ArgumentOutOfRangeException("Money must be grater than 0");\n }\n if (taxDeduction < 0 || taxDeduction > 1.0m) {\n throw new ArgumentOutOfRangeException("TaxDeduction must be between 0.0 and 1.0");\n }\n Money = money;\n TaxDeduction = taxDeduction;\n }\n}\n</code></pre>\n<p>[2]:</p>\n<pre><code>_TaxLevels = new List<TaxLevel>() {\n new TaxLevel {Money = 4770m, TaxDeduction = 0.10m },\n new TaxLevel { Money = 3700, TaxDeduction = 0.14m },\n // ...\n new TaxLevel { Money = decimal.MaxValue, TaxDeduction = 0.42m },\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T15:29:54.700",
"Id": "17922",
"ParentId": "17918",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "17919",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T13:02:10.517",
"Id": "17918",
"Score": "5",
"Tags": [
"c#",
".net",
"finance"
],
"Title": "Progressive tax program"
}
|
17918
|
<p>Is this the best way to check if two floating point numbers are equal, or close to being equal?</p>
<pre><code>template <class T>
bool IsEqual(T rhs, T lhs)
{
T diff = std::abs(lhs - rhs);
T epsilon = std::numeric_limits<T>::epsilon( ) * std::max(std::abs(rhs), std::abs(lhs));
return diff <= epsilon ;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:23:51.680",
"Id": "28590",
"Score": "1",
"body": "So I should consider: 100000000000000000 and 100000000000000020 to be the same number?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:24:16.483",
"Id": "28591",
"Score": "0",
"body": "PS. Typo inside std::max() you have two rhs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:42:41.613",
"Id": "28594",
"Score": "1",
"body": "@LokiAstari With floating point numbers, they are not accurate and the farther away you get from 1 the less accurate you get. Therefore, I'm trying to check if they are equal with some reason. To answer your question, yes those two values should be equal. But at the same time, I don't want 1 == 20"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T15:40:24.383",
"Id": "28597",
"Score": "1",
"body": "Correct. And if that is what you need fine. But it is not what most people are going to need. I would use @William Morris solution as this would be more normal usage as i do want to distinguish larger numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T15:49:55.160",
"Id": "28598",
"Score": "0",
"body": "@LokiAstari The thing is that you can't guarantee that your large numbers are stored accurately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T15:59:00.773",
"Id": "28600",
"Score": "0",
"body": "As i said last time; you are correct. Does not change anything in my previous statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-12T23:18:27.303",
"Id": "62776",
"Score": "0",
"body": "When in doubt, consult [boost](http://www.boost.org/doc/libs/1_35_0/libs/test/doc/components/test_tools/floating_point_comparison.html) for a comprehensive intro to different float comparisons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-01T19:11:06.537",
"Id": "187850",
"Score": "0",
"body": "You can avoid a *third parameter* if you can calculate the [ulp](https://en.wikipedia.org/wiki/Unit_in_the_last_place) (unit in the last place) of a floating point number. Its not *that* difficult to calculate. Just use the larger of the two ulp's as an acceptable difference. But you will also need that epsilon you're currently using, to handle the *corner cases* like `0`, `INFINITY`, `NaN` (to be dealt with separately)."
}
] |
[
{
"body": "<p>Seems unlikely. <code>epsilon</code> from <code>std::numeric_limits</code> is the smallest increment representable by the type (around the value 1).</p>\n\n<p>You want to check for something \"close to\" equal, but you don't say what close to means for you. Assuming it to be a few multiples of epsilon, the following check would seem reasonable:</p>\n\n<pre><code>const int FEW = 10;\nT diff = std::abs(lhs - rhs);\nT epsilon = std::numeric_limits<T>::epsilon();\n\nreturn diff < (epsilon * FEW);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T14:21:09.573",
"Id": "28589",
"Score": "1",
"body": "From my understanding, floating point numbers get less and less accurate the further away you get from 1. While you code is fine, it is only gone work for a small lower range of floating point numbers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T13:28:12.833",
"Id": "17960",
"ParentId": "17923",
"Score": "4"
}
},
{
"body": "<p>No, not really. You want a third parameter that gives an acceptable difference -- this can be number of decimals, percent of value, or a fixed value, but it needs to be coming from outside to really be useful.</p>\n\n<p>A function that does it with a constant diff, might be useful in some limited circumstances, but not generally.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-12T23:01:08.127",
"Id": "18516",
"ParentId": "17923",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18516",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T16:37:18.890",
"Id": "17923",
"Score": "7",
"Tags": [
"c++",
"floating-point"
],
"Title": "Checking if two floating point numbers are equal"
}
|
17923
|
<p>I wrote this function to read Las file and save a shapefile. The function creates a shapefile with 8 fields. What I wish insert a parse element in the function in order to select the fields I wish to save <code>LAS2SHP(inFile, outFile=None, parse=None)</code>. If <code>parse=None</code> all fields are saved. If <code>parse="irn"</code> the fields <code>intensity</code>, <code>return_number</code>, and <code>number_of_returns</code> are saved, following the legend:</p>
<pre><code>"i": p.intensity,
"r": p.return_number,
"n": p.number_of_returns,
"s": p.scan_direction,
"e": p.flightline_edge,
"c": p.classification,
"a": p.scan_angle,
</code></pre>
<p>I wrote a solution <code>if....ifelse....else</code> really code consuming (and not elegant). Thanks for all helps and suggestions for saving code.</p>
<p>Here is the original function in Python:</p>
<pre><code>import shapefile
from liblas import file as lasfile
def LAS2SHP(inFile,outFile=None):
w = shapefile.Writer(shapefile.POINT)
w.field('Z','C','10')
w.field('Intensity','C','10')
w.field('Return','C','10')
w.field('NumberRet','C','10')
w.field('ScanDir','C','10')
w.field('FlightEdge','C','10')
w.field('Class','C','10')
w.field('ScanAngle','C','10')
for p in lasfile.File(inFile,None,'r'):
w.point(p.x,p.y)
w.record(float(p.z),float(p.intensity),float(p.return_number),float(p.number_of_returns),float(p.scan_direction),float(p.flightline_edge),float(p.classification),float(p.scan_angle))
if outFile == None:
inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))
inFile_name = os.path.splitext(inFile_name_ext)[0]
w.save("{0}\\{1}.shp".format(inFile_path,inFile_name))
else:
w.save(outFile)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T18:33:03.240",
"Id": "28546",
"Score": "0",
"body": "If you'd post the code of the function, I could help you convert the if/elifs/else to a dictionary."
}
] |
[
{
"body": "<p>A possible dictionary based solution:</p>\n\n<pre><code>import os.path\n\nimport shapefile\nfrom liblas import file as lasfile\n\n\n# map fields representing characters to field name and attribute\nFIELDS = {\n 'i': ('Intensity', 'intensity'),\n 'r': ('Return', 'return_number'),\n 'n': ('NumberRet', 'number_of_returns'),\n 's': ('ScanDir', 'scan_direction'),\n 'e': ('FlightEdge', 'flightline_edge'),\n 'c': ('Class', 'classification'),\n 'a': ('ScanAngle', 'scan_angle'),\n}\n\n# assuming that field order is important define it explicitly, otherwise it\n# could simply be DEFAULT_PARSE = FIELDS.keys()\nDEFAULT_PARSE = 'irnseca'\n\n\ndef enhanced_LAS2SHP(inFile, outFile=None, parse=DEFAULT_PARSE):\n w = shapefile.Writer(shapefile.POINT)\n # add 'Z' field not present in fields map\n w.field('Z', 'C', '10')\n # initialise list of desired record attributes\n attributes = []\n # add mapped 'shapefile' fields and desired attributes to list\n for f in parse:\n field, attr = FIELDS[f]\n w.field(field_name, 'C', '10')\n attributes.append(attr)\n # create record from attributes in list of desired attributes\n for p in lasfile.File(inFile, None, 'r'):\n w.point(p.x, p.y)\n record_args = [float(p.z)]\n record_args += (float(getattr(p, attr)) for attr in attributes)\n w.record(*record_args)\n # if not output filename was supplied derive one from input filename\n if outFile is None:\n inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))\n inFile_name, _ = os.path.splitext(inFile_name_ext)\n outFile = os.path.join(inFile_path, '{}.shp'.format(inFile_name))\n # save records to 'shapefile'\n w.save(outFile)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T20:38:26.960",
"Id": "17933",
"ParentId": "17924",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "17933",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T17:17:39.417",
"Id": "17924",
"Score": "2",
"Tags": [
"python",
"optimization"
],
"Title": "Python: improve in elegant way (code saving) a function in order to avoid several statements"
}
|
17924
|
<p>What can I do to improve performance of this function? So far I've changed stuff as local as possible and made a <code>break</code> if all possible surrounding tiles have been found. Also I use a separate variable to track the length of a list instead of <code>len()</code>.</p>
<p>The usage of this is to find surrounding tiles for all tiles.</p>
<pre><code>def getsurroundings(tiles):
for t in tiles:
currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
check = currentrect.colliderect
surroundings = t.surroundings
append = t.surroundings.append
surroundingscount = t.surroundingscount
for t2 in tiles:
if check(t2.rect) and not t == t2 and not t2 in surroundings:
append(t2)
t2.surroundings.append(t)
surroundingscount+=1
t2.surroundingscount+=1
if surroundingscount == 8:
break
return tiles
</code></pre>
<p>Here's the code without localisations which might be easier to read:</p>
<pre><code>def getsurroundings(tiles):
for t in tiles:
currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
for t2 in tiles:
if currentrect.colliderect(t2.rect) and not t == t2 and not t2 in t.surroundings:
t.surroundings.append(t2)
t2.surroundings.append(t)
t.surroundingscount+=1
t2.surroundingscount+=1
if t.surroundingscount == 8:
break
return tiles
</code></pre>
|
[] |
[
{
"body": "<pre><code>def getsurroundings(tiles):\n # skip the last rect in the outer loop, as it can't possibly have any subsequent neighbors\n for index, t in enumerate(tiles[:-2]):\n # if you've already found the maximum neighbors for t, skip the whole process\n if len(t.surroundings) < 8:\n currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)\n # only iterate over the part of the tile list that hasn't already been run through in the outer loop\n for t2 in tiles[index + 1:]:\n if currentrect.colliderect(t2.rect):\n t.surroundings.append(t2)\n t2.surroundings.append(t)\n if len(t.surroundings) == 8:\n break\n</code></pre>\n\n<p>I could be wrong, but I seem to recall that slicing does a shallow copy, so you could conceivably get even better performance if you swap the loops to iterating over indeces instead of slices.</p>\n\n<p>Assuming this is PyGame, and assuming (since your code says you can't have more then 8 neighbors) that rects are non-overlapping and can only have one other rect per side (such as on a chess board), here's a bit better solution, I think:</p>\n\n<pre><code>Tile(Rect):\n\n neighbors_map = ((('upper_center', 'mid_left'),\n ('mid_left', 'upper_center')),\n (('upper_left', 'mid_right'),\n ('upper_right', 'mid_left'),\n ('mid_left', 'upper_right'),\n ('mid_right', 'upper_left')),\n (('upper_center', 'mid_left'),\n ('mid_right', 'upper_center')),\n (('upper_left', 'lower_center'),\n ('upper_center', 'lower_left'),\n ('lower_left', 'upper_center'),\n ('lower_center', 'upper_left')),\n (('upper_center', 'lower_right'),\n ('upper_right', 'lower_center'),\n ('lower_center', 'upper_right'),\n ('lower_right', 'upper_center')),\n (('mid_left', 'lower_center'),\n ('lower_center', 'mid_left')),\n (('mid_left', 'lower_right'),\n ('mid_right', 'lower_left'),\n ('lower_left', 'mid_right'),\n ('lower_right', 'mid_left')),\n (('mid_right', 'lower_center'),\n ('lower_center', 'mid_right')))\n\n def __init__(self, *args, **kwargs):\n self.clear_neighbors()\n Rect.__init__(self, *args, **kwargs)\n\n def clear_neighbors(self):\n self.neighbors = [None] * 8\n\n def __getattr__(self, name):\n try:\n index = self.resolve_name(name)\n except ValueError:\n raise AttributeError\n return self.neighbors(index)\n\n def __setattr__(self, name, value):\n try:\n super(Tile, self).__setattr__(name, value)\n except AttributeError:\n try:\n index = self.resolve_name(name)\n except ValueError:\n raise AttributeError\n if not self.neighbors[index]:\n self.neighbors[index] = value\n for neighbor_name, neighbor_neighbor_name in Tile.neighbors_map[index]:\n neighbor = getattr(self, neighbor_name)\n if neighbor:\n setattr(neighbor, neighbor_neighbor_name, value)\n\n def resolve_name(self, name):\n parts = name.split('_')\n if parts[0] == 'upper':\n index = 0\n elif parts[0] == 'mid':\n if parts[1] == 'left':\n return 3\n elif parts[1] == 'right':\n return 4\n else:\n raise ValueError\n elif parts[0] == 'lower':\n index = 5\n else:\n raise ValueError\n if parts[1] == 'left':\n return index\n elif parts[1] == 'center':\n return index + 1\n elif parts[1] == 'right':\n return index + 2\n else:\n raise ValueError\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>def populate_neighbors(tile_list):\n tile_list_copy = copy.copy(tile_list)\n while tile_list_copy:\n current_tile = tile_list_copy.pop(0)\n if all current_tile.neighbors:\n continue\n full_tile_indeces = []\n for index, search_tile in enumerate(tile_list_copy):\n if all search_tile.neighbors:\n full_tile_indeces.append(index)\n else:\n if current_tile.right == search_tile.left + 1:\n if current_tile.bottom == search_tile.top + 1:\n current_tile.lower_right = search_tile\n elif current_tile.top == search_tile.bottom - 1:\n current_tile.upper_right = search_tile\n elif (current_tile.top == search_tile.top\n and current_tile.bottom == search_tile.bottom):\n current_tile.mid_right = search_tile\n elif current_tile.left == search_tile.right - 1:\n if current_tile.bottom == search_tile.top + 1:\n current_tile.lower_left = search_tile\n elif current_tile.top == search_tile.bottom - 1:\n current_tile.upper_left = search_tile\n elif (current_tile.top == search_tile.top\n and current_tile.bottom == search_tile.bottom):\n current_tile.mid_left = search_tile\n elif (current_tile.left == search_tile.left\n and current_tile.right == search_tile.right):\n if current_tile.bottom == search_tile.top + 1:\n current_tile.lower_center = search_tile\n elif current_tile.top == search_tile.bottom - 1:\n current_tile.upper_center = search_tile\n for index in reversed(full_tile_indeces):\n tile_list_copy.pop(index)\n</code></pre>\n\n<p>It would probably be a good idea to break the neighbor setting logic out of the <code>Tile</code> class, but that can be something to figure out. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T18:27:17.647",
"Id": "28543",
"Score": "0",
"body": "Why not use `itertools.combinations(tiles,2)`? [If you're sticking with brute force pairwise comparisons, I mean.]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T18:28:33.333",
"Id": "28544",
"Score": "1",
"body": "@DSM because I didn't think of it. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T18:29:08.970",
"Id": "28545",
"Score": "0",
"body": "The downside is that you couldn't short-circuit the same way at 8, I guess. You could `islice` to avoid making the slice copy, though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T18:23:29.533",
"Id": "17926",
"ParentId": "17925",
"Score": "2"
}
},
{
"body": "<p>What about this?<br>\nI added a second list, so you only iterate over combinations you didn't already check.</p>\n\n<p>By the way, you should code with spaces, not with tabs.</p>\n\n<pre><code>def getsurroundings(tiles):\n tiles2 = tiles[:]\n for t in tiles:\n currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)\n check = currentrect.colliderect\n surroundings = t.surroundings\n append = t.surroundings.append\n surroundingscount = t.surroundingscount\n tiles2.pop(0)\n for t2 in tiles2:\n if check(t2.rect) and not t == t2 and not t2 in surroundings:\n append(t2)\n t2.surroundings.append(t)\n surroundingscount+=1\n t2.surroundingscount+=1\n if surroundingscount == 8:\n break\n return tiles\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T08:08:30.600",
"Id": "28562",
"Score": "0",
"body": "But I like tabs D:"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T18:24:11.767",
"Id": "17927",
"ParentId": "17925",
"Score": "0"
}
},
{
"body": "<p>The problem here isn't in the details of the code, but in the algorithm. For every tile, you check all tiles, so for <em>n</em> tiles, your code has to perform <em>n^2</em> checks, which is a lot. The only way to significantly reduce the running time of your code, is to make the search smarter. If you can make your use case a bit more visual, we might be able to come up with something.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T18:25:58.023",
"Id": "17928",
"ParentId": "17925",
"Score": "5"
}
},
{
"body": "<p>I don't know exactly what you are doing, but it seems like something similar to Minesweeper counts for bombs surrounding a tile.</p>\n\n<p>I would to do this by iterating through the tiles once, and increment their neighbour's count by one if they have some feature you're interested in (like a bomb) to get the result. That way you only need k * 8 iterations (minus the ones over the edges) with k being the number of tiles having the feature you're interested in. For a board of 8x8 having 28 bombs that would be 224 iterations, instead of the 4096 when using a n^2 algorithm.</p>\n\n<p>With Numpy this is relatively easy to do. And about ten times faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T06:52:38.120",
"Id": "17946",
"ParentId": "17925",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "17946",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T17:58:58.923",
"Id": "17925",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Finding surrounding tiles for all tiles"
}
|
17925
|
<p>I've recently been learning (and struggling with) integrating AutoFac, NHibernate & ASP.NET Web API. I have found several tutorials with code that did not work as anticipated but managed to finally find a working solution.</p>
<p>Essentially what I'm doing is registering a singleton of my <code>SessionFactory</code> to the <code>WebApiApplication.SessionFactory</code> object, registering a per-API-request <code>ISession</code> & <code>IClientRepository</code>. After these are registered, I'm creating a controller with a DI'ed <code>IClientRepository</code> (which in turn has an <code>ISession</code> injected which creates a new session as seen in the code below).</p>
<p>My controllers are marked with a custom <code>TranscationActionFilterAttribute</code> to bind (or create) a session. The issue I was initially encountering while implementing this pattern is that considering a new session is created every time <code>IClientRepository</code> was injected with an <code>ISession</code>, the session was never automatically bound and the code in my Transcation action filter would always create an extraneous session, thereby making updates and deletes not function properly. I got around this by binding the <code>ISession</code> in the constructor of my <code>ClientRepository</code>.</p>
<p>Is this safe?</p>
<p>Global.asax:</p>
<pre><code>public class WebApiApplication : System.Web.HttpApplication
{
public static ISessionFactory SessionFactory { get; set; }
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var configuration = GlobalConfiguration.Configuration;
var builder = new ContainerBuilder();
// Register ISessionFactory as Singleton
builder.Register(x => NHibernateConfigurator.BuildSessionFactory()).SingleInstance();
// Register API controller types using assembly scanning.
builder.RegisterAssemblyTypes(
Assembly.GetExecutingAssembly())
.Where(t =>
!t.IsAbstract && typeof(ApiController).IsAssignableFrom(t));
// Register ISession as instance per web request
builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).InstancePerApiRequest();
// Register clients controller as instance per web request
builder.RegisterType<ClientRepository>().As<IClientRepository>().InstancePerApiRequest();
// Register all controllers
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AsSelf();
// Override default dependency resolver to use Autofac
var container = builder.Build();
// Set the dependency resolver implementation.
var resolver = new AutofacWebApiDependencyResolver(container);
configuration.DependencyResolver = resolver;
}
}
</code></pre>
<p>TransactionAttribute.cs:</p>
<pre><code>public class TransactionAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
private ISessionFactory SessionFactory { get; set; }
public TransactionAttribute()
{
SessionFactory = WebApiApplication.SessionFactory;
}
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!CurrentSessionContext.HasBind(SessionFactory))
{
CurrentSessionContext.Bind(SessionFactory.OpenSession());
}
var session = SessionFactory.GetCurrentSession();
session.BeginTransaction();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var session = SessionFactory.GetCurrentSession();
var transcation = session.Transaction;
if (transcation != null && transcation.IsActive)
{
transcation.Commit();
}
session = CurrentSessionContext.Unbind(SessionFactory);
session.Close();
}
}
</code></pre>
<p>And the constructor for my repository:</p>
<pre><code> public ClientRepository(ISession session)
{
if (session == null) throw new ArgumentNullException("nhSession");
this._session = session;
CurrentSessionContext.Bind(_session);
}
</code></pre>
|
[] |
[
{
"body": "<p>This is not going to answer your question directly but..</p>\n\n<blockquote>\n <p>By definition I suppose that Code Review allows me to suggest and\n share subjective ideas (to be determined)...</p>\n</blockquote>\n\n<p>By convention, stuff that needs to be done on the application start can be located in a App_Start folder.</p>\n\n<p>Here's a template for AutoFac, <code>~/App_Start/AutofacMvcConfig.cs</code>:</p>\n\n<pre><code>using System.Web.Mvc;\nusing Autofac;\nusing Autofac.Integration.Mvc;\nusing Models;\nusing MvcApplication.App_Start;\n\n[assembly: WebActivator.PreApplicationStartMethod(typeof(AutofacMvcConfig), \"Start\")]\n\nnamespace MvcApplication.App_Start\n{\n public class AutofacMvcConfig\n {\n public static void Start()\n {\n var builder = new ContainerBuilder();\n\n builder.RegisterControllers(typeof(MvcApplication).Assembly);\n builder.RegisterType<TodoCommands>().As<ITodoCommands>().InstancePerHttpRequest();\n builder.RegisterType<TodoQueries>().As<ITodoQueries>();\n\n var container = builder.Build();\n\n // Install-Package Autofac.Mvc3\n DependencyResolver.SetResolver(new AutofacDependencyResolver(container));\n }\n }\n}\n</code></pre>\n\n<h2>Readings</h2>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5335350/unitofwork-in-action-filter-seems-to-be-caching\">https://stackoverflow.com/questions/5335350/unitofwork-in-action-filter-seems-to-be-caching</a></li>\n<li><a href=\"http://jittuu.com/2012/2/9/UnitOfWork-pattern-and-asp.net-mvc/\" rel=\"nofollow noreferrer\">http://jittuu.com/2012/2/9/UnitOfWork-pattern-and-asp.net-mvc/</a></li>\n<li><a href=\"http://slynetblog.blogspot.ca/2012/03/using-aspnet-mvc-4-webapi-with.html\" rel=\"nofollow noreferrer\">http://slynetblog.blogspot.ca/2012/03/using-aspnet-mvc-4-webapi-with.html</a></li>\n<li><a href=\"http://ben.onfabrik.com/posts/yet-another-session-per-request-post\" rel=\"nofollow noreferrer\">http://ben.onfabrik.com/posts/yet-another-session-per-request-post</a></li>\n</ul>\n\n<p>Keywords: mvc, unit of work, autofac, actionfilterattribute</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T19:47:50.763",
"Id": "18557",
"ParentId": "17930",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T20:05:04.587",
"Id": "17930",
"Score": "8",
"Tags": [
"c#",
"dependency-injection",
"asp.net-mvc-4"
],
"Title": "AutoFac, NHibernate & ASP.NET Web API integration"
}
|
17930
|
<p>I am new to Java and I am trying to learn about optimizing code to make it production ready. I have the following code below. I would like to know how I could optimize it. I thought by using a small snippet of could, it would be a good way to learn.</p>
<p>Some points:</p>
<ol>
<li>The function would be run many times to it needs to be fast.</li>
<li>The input is unconstrained since it might come from a user or from a file. Is there a way to deal with this so not exceptions are thrown? I was thinking of using a regular expression.</li>
<li>Is there anything else I need to do to make it production ready? e.g. unit tests. If so, what would be the best way to do this?</li>
<li>I am assuming that the string to be searched is not very long.</li>
<li>When I say optimization, I mean doing things like replacing the <code>+</code> operator with something faster is it can effect memory and performance, etc.</li>
</ol>
<pre><code>public String strReplave(String originalStr, String oldStr, String newStr) {
int start = 0;
while ((start = originalStr.indexOf(oldStr, start)) > 0) {
originalStr= originalStr.substring(0,start) + newStr+ originalStr.substring(start + oldStr.length());
start += newStr.length();
}
return originalStr;
}
</code></pre>
<p>Thanks for your help and if you need me to clarify anything please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T21:28:49.727",
"Id": "28550",
"Score": "3",
"body": "I feel like I'm missing something? Why don't you use `String replace(CharSequence target, CharSequence replacement);`? `String`s implement `CharSequence`, so you could use that like `String ns = \"Hello world\".replace(\"world\", \"people\");`"
}
] |
[
{
"body": "<p>String.replace(..) will work as Corbin said.</p>\n\n<p>Be careful when you mix String objects with the '+' operator in Java, especially within a loop.</p>\n\n<pre><code>String s = a + b; \n</code></pre>\n\n<p>will be (generally) interpreted as</p>\n\n<pre><code>String s = new StringBuffer(a).append(b).toString();\n</code></pre>\n\n<p>While not bad on it's own, when performed in a loop, a new StringBuffer (or the newer StringBuilder) object will be created on every loop iteration, which is usually sub-optimal.</p>\n\n<p>When you want to build a String up from pieces, consider storing the result in a StringBuilder object (created outside of the loop) as you go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T22:47:37.163",
"Id": "17937",
"ParentId": "17932",
"Score": "5"
}
},
{
"body": "<p>I'd use <a href=\"http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#replace%28java.lang.String,%20java.lang.String,%20java.lang.String%29\" rel=\"nofollow\"><code>StringUtils.replace</code></a> from <a href=\"http://commons.apache.org/lang/\" rel=\"nofollow\">Apache Commons Lang</a> instead. It's open source, so you can check <a href=\"http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/main/java/org/apache/commons/lang3/StringUtils.java?view=markup#l3764\" rel=\"nofollow\">its source</a> and its <a href=\"http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/test/java/org/apache/commons/lang3/StringUtilsTest.java?view=markup#l968\" rel=\"nofollow\">unit tests</a> too. <a href=\"http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#replaceEach%28java.lang.String,%20java.lang.String%5b%5d,%20java.lang.String%5b%5d%29\" rel=\"nofollow\"><code>StringUtils.replaceEach</code></a> also could be useful.</p>\n\n<blockquote>\n <p>By using a standard library,\n you take advantage of the knowledge of the experts who wrote it and the\n experience of those who used it before you.</p>\n</blockquote>\n\n<p>It's from <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> where the author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.</p>\n\n<p>See also: <a href=\"http://c2.com/cgi/wiki?NotInventedHere\" rel=\"nofollow\">Not Invented Here</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T03:24:54.373",
"Id": "17942",
"ParentId": "17932",
"Score": "4"
}
},
{
"body": "<p>Like Corbin said you have to use replace(..), or replaceAll(..) [native Java functions],<br> and test the parameters :</p>\n\n<pre><code>public String strReplave(final String originalStr, final String oldStr, String newStr) {\n // add 'final' if parameters are not changed\n if(null == originalStr || originalStr.isEmpty()) {\n return \"\"; // verify if it is the project solution prerequity\n }\n if(null == oldStr || oldStr.isEmpty()){\n // Send also a message to Console or API logger \n return originalStr ;\n }\n if (null == newStr) {\n newStr = \"\"; // verify if it is the project solution prerequity\n }\n return originalStr.replaceAll(oldStr, newStr);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T11:00:43.543",
"Id": "28570",
"Score": "0",
"body": "It's probably a typo: `originalStr(replaceAll(oldStr, newStr))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T11:57:26.047",
"Id": "28572",
"Score": "1",
"body": "@palacsint Exact! Thanks for pointing it out"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:34:49.227",
"Id": "28621",
"Score": "0",
"body": "I assume this would not take care of especial characters in the string. That they would still through an exception?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T08:41:44.323",
"Id": "28729",
"Score": "0",
"body": "A String is `null` or not; so inside characters can be evaluate and replaced with regex like : \n`Pattern patt = Pattern.compile(regex, flags);\nString result = patt.matcher(input).replaceAll(replacement);`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T07:22:43.890",
"Id": "17947",
"ParentId": "17932",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T20:25:40.680",
"Id": "17932",
"Score": "6",
"Tags": [
"java",
"optimization",
"strings"
],
"Title": "Java string replace"
}
|
17932
|
<p>I have to do a table like this one:</p>
<pre><code>+-------+-------+-------+-------+-------+-------+
| th 1 | th 2 | th 3 | th 4 |
+-------+-------+-------+-------+-------+-------+
| | | | td 1 | td 2 | td 3 |
| | | th 7 +-------+-------+-------+
| | | | td 4 | td 5 | td 6 |
| | th 6 +-------+-------+-------+-------+
| | | | td 7 | td 8 | td 9 |
| | | th 8 +-------+-------+-------+
| | | | td 10 | td 11 | td 12 |
| th 5 +-------+-------+-------+-------+-------+
| | | | td 13 | td 14 | td 15 |
| | | th 10 +-------+-------+-------+
| | | | td 16 | td 17 | td 18 |
| | th 9 +-------+-------+-------+-------+
| | | | td 19 | td 20 | td 21 |
| | | th 11 +-------+-------+-------+
| | | | td 22 | td 23 | td 24 |
+-------+-------+-------+-------+-------+-------+
</code></pre>
<p>The way I'm doing it right now is</p>
<pre><code><table>
<thead>
<tr>
<th colspan="3">th 1</th>
<th>th 2</th>
<th>th 3</th>
<th>th 4</th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="8">th 5</th>
<th rowspan="4">th 6</th>
<th rowspan="2">th 7</th>
<td>td 1</td>
<td>td 2</td>
<td>td 3</td>
</tr>
<tr>
<td>td 4</td>
<td>td 5</td>
<td>td 6</td>
</tr>
<tr>
<th rowspan="2">th 8</th>
<td>td 7</td>
<td>td 8</td>
<td>td 9</td>
</tr>
<tr>
<td>td 10</td>
<td>td 11</td>
<td>td 12</td>
</tr>
<tr>
<th rowspan="4">th 9</th>
<th rowspan="2">th 10</th>
<td>td 13</td>
<td>td 14</td>
<td>td 15</td>
</tr>
<tr>
<td>td 16</td>
<td>td 17</td>
<td>td 18</td>
</tr>
<tr>
<th rowspan="2">th 11</th>
<td>td 19</td>
<td>td 20</td>
<td>td 21</td>
</tr>
<tr>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
</tbody>
</table>
</code></pre>
<p>What I want to know is if there is another, cleaner way to construct the same structure, like having the <code>td</code> in <code>tr</code> different than the same in which the <code>th</code> are constructed to have them separated.</p>
<p>I created a jsfiddle if anyone knows a better way to do it.
<a href="http://jsfiddle.net/mkhuete/ehX7X/1/" rel="noreferrer">http://jsfiddle.net/mkhuete/ehX7X/1/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T21:02:20.900",
"Id": "28552",
"Score": "3",
"body": "Looks fine to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T21:32:17.703",
"Id": "28553",
"Score": "2",
"body": "The structure looks OK. Nothing has been said about semantics (i.e., meanings) involved. The question “if there is another way, more clean to construct these same structure, like having the td in tr differents than the same in which the th are constructed to have them separated” just does not parse, still less make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:12:50.023",
"Id": "35737",
"Score": "0",
"body": "Because of the clean, it looks clean I like the table \"colgroup\" tag and maybe this link will help a little too http://stackoverflow.com/questions/1006089/setting-rowspan-on-colgroup"
}
] |
[
{
"body": "<p>I can't fault your tags at all. The only problem is that due to your table being quite complex, assistive technology may not be able to figure out the structure of your table.</p>\n\n<p>I was going to recommend using <code>scope</code> but according to <a href=\"http://www.w3.org/TR/WCAG20-TECHS/H63.html\">W3C</a> there are some inconsistency issues.</p>\n\n<blockquote>\n <p>The row and col values of the scope attribute are currently supported\n to a large extent by most current versions of JAWS. However, <strong>there are\n still some problems and WindowEyes support for scope is inconsistent</strong>.\n The same is true for Japanese versions of these screen readers.\n Versions of JAWS prior to version 5 and older versions of Window-Eyes\n have inconsistent support for scope.</p>\n</blockquote>\n\n<p>Using <code>scope</code> would look like this, with <code>scope=\"col\"</code> in all <code><th></code> elements in the first row and <code>scope=\"row\"</code> for all other <code><th></code> elements.</p>\n\n<pre><code><table>\n <thead>\n <tr>\n <th colspan=\"3\" scope=\"col\">th 1</th>\n <th scope=\"col\">th 2</th>\n <th scope=\"col\">th 3</th>\n <th scope=\"col\">th 4</th>\n </tr> \n </thead>\n <tbody>\n <tr>\n <th rowspan=\"8\" scope=\"row\">th 5</th>\n <th rowspan=\"4\" scope=\"row\">th 6</th>\n <th rowspan=\"2\" scope=\"row\">th 7</th>\n <td>td 1</td>\n <td>td 2</td>\n <td>td 3</td>\n </tr>\n <tr>\n <td>td 4</td>\n <td>td 5</td>\n <td>td 6</td>\n </tr>\n <tr>\n <th rowspan=\"2\" scope=\"row\">th 8</th>\n <td>td 7</td>\n <td>td 8</td>\n <td>td 9</td>\n </tr>\n <tr>\n <td>td 10</td>\n <td>td 11</td>\n <td>td 12</td>\n </tr>\n <tr>\n <th rowspan=\"4\" scope=\"row\">th 9</th>\n <th rowspan=\"2\" scope=\"row\">th 10</th>\n <td>td 13</td>\n <td>td 14</td>\n <td>td 15</td>\n </tr>\n <tr>\n <td>td 16</td>\n <td>td 17</td>\n <td>td 18</td>\n </tr>\n <tr>\n <th rowspan=\"2\" scope=\"row\">th 11</th>\n <td>td 19</td>\n <td>td 20</td>\n <td>td 21</td>\n </tr>\n <tr>\n <td>td 22</td>\n <td>td 23</td>\n <td>td 24</td>\n </tr>\n </tbody>\n</table>\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/CY66k/1/.\">JSFiddle for scope method</a></p>\n\n<p>This is W3C's recommendation:</p>\n\n<blockquote>\n <p>At the current time, <strong>those who want to ensure consistent support\n across Assistive Technologies for tables</strong> where the headers are not in\n the first row/column may want to use the technique for complex tables\n <strong>H43: <a href=\"http://www.w3.org/TR/WCAG20-TECHS/H43.html\">Using id and headers attributes</strong> to associate data cells with\n header cells in data tables</a>. For simple tables that have headers in\n the first column or row we recommend the use of the th and td\n elements.</p>\n</blockquote>\n\n<p>Let me just start off by saying this is a complete pain in order to be completely accessibly and scope will probably be fine in most cases. Here is the table using the <code>id</code>/<code>header</code> method (<em>shudder</em>):</p>\n\n<pre><code><table>\n <thead>\n <tr>\n <th colspan=\"3\" id=\"th1\">th 1</th>\n <th id=\"th2\">th 2</th>\n <th id=\"th3\">th 3</th>\n <th id=\"th4\">th 4</th>\n </tr> \n </thead>\n <tbody>\n <tr>\n <th rowspan=\"8\" id=\"th5\" headers=\"th1\">th 5</th>\n <th rowspan=\"4\" id=\"th6\" headers=\"th1 th5\">th 6</th>\n <th rowspan=\"2\" id=\"th7\" headers=\"th1 th5 th6\">th 7</th>\n <td headers=\"th2 th5 th6 th7\">td 1</td>\n <td headers=\"th3 th5 th6 th7\">td 2</td>\n <td headers=\"th4 th5 th6 th7\">td 3</td>\n </tr>\n <tr>\n <td headers=\"th2 th5 th6 th7\">td 4</td>\n <td headers=\"th3 th5 th6 th7\">td 5</td>\n <td headers=\"th4 th5 th6 th7\">td 6</td>\n </tr>\n <tr>\n <th rowspan=\"2\" id=\"th8\" headers=\"th1 th5 th6\">th 8</th>\n <td headers=\"th2 th5 th6 th8\">td 7</td>\n <td headers=\"th3 th5 th6 th8\">td 8</td>\n <td headers=\"th4 th5 th6 th8\">td 9</td>\n </tr>\n <tr>\n <td headers=\"th2 th5 th6 th8\">td 10</td>\n <td headers=\"th3 th5 th6 th8\">td 11</td>\n <td headers=\"th4 th5 th6 th8\">td 12</td>\n </tr>\n <tr>\n <th rowspan=\"4\" id=\"th9\" headers=\"th1 th5\">th 9</th>\n <th rowspan=\"2\" id=\"th10\" headers=\"th1 th5 th9\">th 10</th>\n <td headers=\"th2 th5 th9 th10\">td 13</td>\n <td headers=\"th3 th5 th9 th10\">td 14</td>\n <td headers=\"th4 th5 th9 th10\">td 15</td>\n </tr>\n <tr>\n <td headers=\"th2 th5 th9 th10\">td 16</td>\n <td headers=\"th3 th5 th9 th10\">td 17</td>\n <td headers=\"th4 th5 th9 th10\">td 18</td>\n </tr>\n <tr>\n <th rowspan=\"2\" id=\"th11\" headers=\"th1 th5 th9\">th 11</th>\n <td headers=\"th2 th5 th9 th11\">td 19</td>\n <td headers=\"th3 th5 th9 th11\">td 20</td>\n <td headers=\"th4 th5 th9 th11\">td 21</td>\n </tr>\n <tr>\n <td headers=\"th2 th5 th9 th11\">td 22</td>\n <td headers=\"th3 th5 th9 th11\">td 23</td>\n <td headers=\"th4 th5 th9 th11\">td 24</td>\n </tr>\n </tbody>\n</table>\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/ehX7X/9/\">JSFiddle for id/headers</a></p>\n\n<p>What is comes down to in the end in my opinion is an accessible solution that is also maintainable in the back end. Realistically JAWS and WindowEyes will eventually fix up their bugs and using <code>scope</code> will be fine even for tables as complex as this. Unless you expect many users to use assistive technologies and require strict adherence to WCAG, go with <code>scope</code>. Markup needs to be beautiful too :)</p>\n\n<p>There is also the <a href=\"http://docs.webplatform.org/wiki/html/elements/colgroup\"><code><colgroup></code></a> element which is relevant but support for it isn't great currently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-10T08:33:02.207",
"Id": "36526",
"Score": "0",
"body": "Thanks! it's an interesting approach, thanks for helping me"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T06:40:33.373",
"Id": "23101",
"ParentId": "17936",
"Score": "10"
}
},
{
"body": "<p>Plan it out on paper with percentages, and then take it row by row in an editor, inserting the content as you go. Otherwise you can't do it at all. And the more cells and custom rowspan/colspan you use with coding non-CSS table design, the time taken to code it all increases exponentially.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T16:44:16.267",
"Id": "82787",
"Score": "0",
"body": "The author has already sketched the layout, and the `rowspan` and `colspan` attributes are already correct. Furthermore, the question is about semantics, not layout."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:53:06.767",
"Id": "47251",
"ParentId": "17936",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T20:51:19.173",
"Id": "17936",
"Score": "13",
"Tags": [
"html",
"html5"
],
"Title": "Best way to construct a semantic HTML table?"
}
|
17936
|
<p>I'm still learning Python, so I tried to build a basic MVC app using wxPython and pubsub. While it seems to work fine, the code seems to be getting out of hand.</p>
<p>In model I decided against using traditional (e.g. Java) accessors and went with the more Pythonic approach of properties. I only wanted to set the setters, but ended up needing to set the getters too (because the variable name had to change to prevent recursion). What's the preferred way to do this?</p>
<p>Next, the flow for setting each variable seems a mess. Right now, changing the name in view publishes a message which controller is subscribed to, so it sets the name in model, which publisher another message which controller is subscribed to, which sends a message to view, which finally does something with the values (the last part is not really required at the moment, but should be in many cases). Is this all peachy, or am I missing something?</p>
<p>As for any other blunders, I'd be happy to hear them!</p>
<p>I mostly followed <a href="http://wiki.wxpython.org/ModelViewController#Code_Sample" rel="nofollow noreferrer">Mike Rooney's Code Sample</a>.</p>
<pre><code>"""
A simple attempt at a pubsub-driven MVC application with wxPython
"""
import wx
import wx.lib.pubsub
# this seems to be required -- bug?
pub = wx.lib.pubsub.Publisher()
class Model(object):
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
pub.sendMessage("name.changed", self.name)
@property
def age(self):
return self._age
@age.setter
def age(self, value):
self._age = value
pub.sendMessage("age.changed", self.age)
class View(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="MVC test", size=(200, 150))
# setup sizers
self.padding_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer = wx.FlexGridSizer(2, 2, 8, 25)
self.sizer.AddGrowableCol(1, 1) # make the second column fit available space
self.padding_sizer.Add(self.sizer, proportion=1, flag=wx.ALL|wx.EXPAND, border=14)
self.SetSizer(self.padding_sizer)
# setup widgets
# name
self.name_label = wx.StaticText(self, label="Name:")
self.name = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
self.sizer.Add(self.name_label)
self.sizer.Add(self.name, 1, wx.EXPAND)
# age
self.age_label = wx.StaticText(self, label="Age:")
self.age = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
self.sizer.Add(self.age_label)
self.sizer.Add(self.age, 1, wx.EXPAND)
# setters for wx controls
def set_name(self, name):
self.name.SetValue(name)
def set_age(self, age):
self.age.SetValue(str(age))
class Controller(object):
def __init__(self, app):
# controller holds refs to models, app and views
self.model = Model('Goku', 9001)
self.app = app
self.view = View(None)
# set up the view
self.view.set_name(self.model.name)
self.view.set_age(self.model.age)
# bind view events to methods
self.view.name.Bind(wx.EVT_TEXT_ENTER, self.change_name)
self.view.age.Bind(wx.EVT_TEXT_ENTER, self.change_age)
# subscriptions
pub.subscribe(self.name_changed, "name.changed")
pub.subscribe(self.age_changed, "age.changed")
# finally,show the view
self.view.Show()
def change_name(self, evt):
self.model.name = evt.String
print "Name was changed to", self.model.name
def name_changed(self, message):
# unnecessary at the moment, for illustration only
self.view.set_name(message.data)
def change_age(self, evt):
self.model.age = int(evt.String)
print "Age was changed to", self.model.age
def age_changed(self, message):
# unnecessary at the moment, for illustration only
self.view.set_age(message.data)
if __name__ == '__main__':
#create the wx app
app = wx.App(False)
# pass the app to the controller
controller = Controller(app)
# start the app running
app.MainLoop()
</code></pre>
<p><img src="https://i.stack.imgur.com/M5iov.png" alt="Screenshot"></p>
|
[] |
[
{
"body": "<p>It mostly looks pretty good. I have just a couple tweaks to suggest.</p>\n\n<p>You have </p>\n\n<pre><code>import wx.lib.pubsub\n\n# this seems to be required -- bug?\npub = wx.lib.pubsub.Publisher()\n</code></pre>\n\n<p>The example from the wxpython wiki does</p>\n\n<pre><code>from wx.lib.pubsub import Publisher as pub\n</code></pre>\n\n<p>I think using that form of the import will let you drop the line where you instantiate the Publisher.</p>\n\n<p>I like to put my mainline code in a main() routine right after the imports so it's clear where the work begins</p>\n\n<pre><code>def main(args):\n #create the wx app\n app = wx.App(False)\n\n # pass the app to the controller\n controller = Controller(app)\n\n # start the app running\n app.MainLoop()\n</code></pre>\n\n<p>Then at the bottom of the file,</p>\n\n<pre><code>if __name__ == '__main__':\n # call main rather than hiding the payload down here\n main(sys.argv)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T01:06:36.167",
"Id": "48894",
"ParentId": "17939",
"Score": "4"
}
},
{
"body": "<p>The question is if you need your model to be able to notify other subscribers (controllers) about a change of the name or not.</p>\n\n<p>If your controller is the only class interacting with the model (as it seems, since the Model is created in the Controller's <code>__init__</code>), you could get rid of using <code>pubsub</code> in the Model and halve the number of methods in the Controller.</p>\n\n<p>For example, reduced to the methods related to changing the name, you could write:</p>\n\n<pre><code>class Model(object):\ndef __init__(self, name, age):\n self._name = name\n self._age = age\n\n@property\ndef name(self):\n return self._name\n\n@name.setter\ndef name(self, value):\n self._name = value\n # --> pubsub call removed here\n\n# ...\n\nclass Controller(object):\n\n# left remaining methods out\n\ndef change_name(self, evt):\n self.model.name = evt.String\n print \"Name was changed to\", self.model.name\n self.view.set_name(message.data)\n\n# method name_changed not needed any longer\n</code></pre>\n\n<p>Another point worth mentioning is that with your current implementation your Controller class needs to know about the implementation of the View class (i.e. that it is using wxPython and what kind of events it has to subscribe to). \nYou should leave the binding of the events to the view class. Instead of utilizing <code>pubsub</code> in the Model, it would be of much more use in the View class. </p>\n\n<p>Define a callback for the relevant UI events inside your View class and bind it to <code>wx.EVT_TEXT_ENTER</code>. When a new name is entered, the View notifies the Controller with <code>pubsub</code>. The Controller then takes care of your logic like validating the input, updating the Model and if necessary trigger additional actions on the View or Model or dealing with errors like asking the View to display an error message if the name is invalid.</p>\n\n<p>Again using the Name field as example:</p>\n\n<pre><code>from wx.lib.pubsub import Publisher as pub\n\nclass Model(object):\n def __init__(self, name, age):\n self._name = name\n self._age = age\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n\n\nclass View(wx.Frame):\n def __init__(self, parent):\n wx.Frame.__init__(self, parent, title=\"MVC test\", size=(200, 150))\n\n # setup sizers\n self.padding_sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.sizer = wx.FlexGridSizer(2, 2, 8, 25)\n self.sizer.AddGrowableCol(1, 1) # make the second column fit available space\n self.padding_sizer.Add(self.sizer, proportion=1, flag=wx.ALL|wx.EXPAND, border=14)\n self.SetSizer(self.padding_sizer)\n\n # setup widgets\n\n # name\n self.name_label = wx.StaticText(self, label=\"Name:\")\n self.name = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)\n self.sizer.Add(self.name_label)\n self.sizer.Add(self.name, 1, wx.EXPAND)\n # --> NEW: bind event in View class\n self.name.Bind(wx.EVT_TEXT_ENTER, self.on_name_changed)\n\n # setters for wx controls\n def set_name(self, name):\n self.name.SetValue(name)\n\n # callback for UI events\n def on_name_changed(self, event):\n new_name = event.String\n pub.sendMessage(\"name.changed\", new_name)\n\n\nclass Controller(object):\n def __init__(self, app):\n # controller holds refs to models, app and views\n self.model = Model('Goku', 9001)\n self.app = app\n self.view = View(None)\n\n # set up the view\n self.view.set_name(self.model.name)\n self.view.set_age(self.model.age)\n\n # DELETED: Binding of UI events removed\n\n # subscriptions\n pub.subscribe(self.name_changed, \"name.changed\")\n\n # finally,show the view\n self.view.Show()\n\n def name_changed(self, message):\n self.model.name = evt.String\n print \"Name was changed to\", self.model.name\n # unnecessary at the moment, for illustration only\n self.view.set_name(message.data)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T10:01:41.470",
"Id": "216466",
"ParentId": "17939",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T00:32:10.963",
"Id": "17939",
"Score": "4",
"Tags": [
"python",
"mvc",
"wxpython"
],
"Title": "Pubsub-driven MVC application with wxPython"
}
|
17939
|
<p>I more or less asked the same questions on stackoverflow.com, but maybe this is more for this forum. I have a hard time getting to grips with how to implement a top navigation (common for the whole site) and a page specific navigation (common for the current controller). I use <a href="http://www.williamsconcepts.com/ci/codeigniter/libraries/template/reference.html" rel="nofollow">Colin Williams' Template library</a>.</p>
<p>I have written my own <code>MY_Controller</code> which all page controllers should extend, but I do not know if this is the correct way. The page specific navigation is implemented in the code below.</p>
<p><strong>MY_Controller.php</strong></p>
<pre><code>abstract class MY_Controller extends CI_Controller {
private $_nav;
public function __construct() {
parent::__construct();
}
abstract protected function _get_nav();
protected function _load_nav(array $nav = null) {
if ($nav === null) {
$this->_nav = $this->_get_nav();
} else {
$this->_nav = $nav;
}
}
protected function _render() {
if (func_num_args() < 3) {
return false;
}
$args = func_get_args();
$this->template->write('title', array_shift($args));
$data = array_pop($args);
for ($i = 0; $i < count($args); $i++) {
$this->template->write_view('content', array_shift($args), $data);
}
if ($this->_nav === null) {
$this->_load_nav();
}
$this->template->write_view('nav', 'templates/sidebar_nav', array('nav' => $this->_nav));
$this->template->render();
return true;
}
}
</code></pre>
<p><strong>collection.php</strong></p>
<pre><code>class Collection extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('collection_model');
}
protected function _get_nav() {
return $this->config->item('collection_nav');
}
public function index() {
$this->view();
}
public function view() {
$data = array();
$data['list'] = $this->collection_model->get_list();
$this->_render('View Collection', 'collection/view', $data);
}
}
</code></pre>
<p><strong>sidebar_nav.php</strong></p>
<pre><code><ul class="nav nav-list bs-docs-sidenav">
<?php foreach ($nav as $item) : ?>
<?php $class = isset($item['class']) ? ' class="' . $item['class'] . '"' : ''; ?>
<li<?php echo $class; ?>>
<a href="<?php echo $item['href']; ?>"><?php echo $item['value']; ?></a>
</li>
<?php endforeach; ?>
</ul>
</code></pre>
<p>What do you think? Is this the proper way to produce a navigation system?</p>
|
[] |
[
{
"body": "<p>I'm not familiar with CI, but from what I can tell the concept seems alright. At least, what I am able to glean from your code seems to be. There are some improvements you could make however.</p>\n\n<p>The only reason to abstract the setting of the <code>$_nav</code> property with the <code>_load_nav()</code> method would be so that you could inject different navigation schemes to allow for further expansion. However, you do not inject your navigation into it and instead hardcode it, albeit with another method. If you are always going to use the <code>_get_nav()</code> method to \"inject\" your navigation then there is no need for the <code>_load_nav()</code> method as it just adds unnecessary abstraction.</p>\n\n<pre><code>//injection\nprotected function _load_nav( $nav ) {\n $this->_nav = $nav;\n}\n</code></pre>\n\n<p>Another abstraction issue is with the <code>$_nav</code> property itself. Your current implementation creates an associative array container for the navigation array. This is redundant as well as unnecessarily abstract. The only reason to abstract the menu in this way is if you were abstracting submenus and injecting their contents into a main menu container. This is pretty similar to what you are currently doing with your <code>_get_nav()</code> method, though you have combined them all already.</p>\n\n<pre><code>protected function _load_nav( $header, array $nav ) {\n $this->_nav[ $header ] = $nav;\n}\n</code></pre>\n\n<p>In your current implementation of your <code>_render()</code> method you are getting all of the function arguments into an array then, essentially, removing the first element after setting it to the <code>TITLE_REGION</code>. If you use <code>array_shift()</code> to physically remove that first element, then your array will no longer contain that element and you can loop over it more naturally. This also has the added benefit of removing these \"magic\" numbers from your code.</p>\n\n<pre><code>$title = array_shift( $args );\n$this->template->write( self::TITLE_REGION, $title );\n\n$n = count( $args );\nfor( $i = 0; $i < $n; $i++ ) {\n</code></pre>\n\n<p>There is no need to explicitly check the <code>$active</code> variable. If it is NULL, then it will not, or rather should not, be set in the <code>$_nav</code> array. Alternatively, if a variable is NULL then it is considered to be not set, so you can use <code>isset()</code> on both variables to simulate an AND comparison, though again, this is unnecessary in this context.</p>\n\n<pre><code>if( isset( $this->_nav[ 'nav' ] [ $active ] ) ) {\n//Unnecessary Alternative\nif( isset( $active, $this->_nav[ 'nav' ] [ $active ] ) ) {\n</code></pre>\n\n<p>You might want to think about saving your navigation to a separate file so that if you ever need to change it you wont have to change the code directly to do so. This follows the Separation of Concerns, which helps to make your code more extensible. Another benefit is that it will allow you to implement that abstract method in <code>MY_Controller</code> without losing functionality. One method would be to use JSON. There are many other methods you can use, but JSON is the one I'll show you. The method you choose is up to you.</p>\n\n<pre><code>//JSON file\n{ \"collection/view\" : [\n {\n \"href\" : \"collection/view\",\n \"value\" : \"View collection\",\n \"class\" : \"icon-film\"\n },\n //etc...\n] }\n\n//Importing the JSON\nprotected function _get_nav( $file ) {\n $json = file_get_contents( $file );\n return json_decode( $json, TRUE );\n}\n</code></pre>\n\n<p>Your <code>index()</code> method is redundant with your <code>view()</code> method. Seeing as how they are both public, having them both is unnecessary. If one were public and the other private then one could be considered the public wrapper, but unless that wrapper was doing something else then it would still be considered redundant and better if you just changed the scope of the other method to public.</p>\n\n<p>You should define your arrays before trying to append to them. Otherwise you could be editing a global. If you meant to edit said global, then you should know that globals are evil and you should never do such a thing. Defining the array before trying to use it, assuming you aren't using globals, ensures that you aren't accidentally manipulating another array defined earlier or accessing a string through the array syntax. The former may not be as noticeable, but the latter will have vastly different results. Another reason not to do this is to avoid PHP issuing warnings, which it should be doing. If you are not seeing these warnings then you should turn up your error reporting so that you can.</p>\n\n<pre><code>$data = array();\n$data['list'] = $this->collection_model->get_list();\n</code></pre>\n\n<p>Instead of rendering your HTML with PHP, you might want to consider using the templating syntax and just rendering the PHP values you need into your HTML. This makes for cleaner, and thus easier read and edit, HTML. For example:</p>\n\n<pre><code><ul class=\"nav nav-list bs-docs-sidenav\">\n <?php foreach( $nav AS $item ) : ?>\n\n <?php $class = isset( $item[ 'class' ] ) ? $item[ 'class' ] : ''; ?>\n <li class=\"<?php echo $class; ?>\">\n <a href=\"<?php echo $item['href'];?>\">\n\n <?php echo $item[ 'value' ]; ?>\n\n </a>\n </li>\n\n <?php endforeach; ?>\n</ul>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T19:29:25.187",
"Id": "28693",
"Score": "0",
"body": "So: I've updated my code a bit! I haven't really solved how to do the active view thing yet. And the nav arrays are still built in the controller, but I am thinking of either doing it your way (JSON) or by using some config file in CodeIgniter. Otherwise, I think I've fixed all your comments. The reason for the `index()` method (or is it called function inside a class too?) is that when the controller is called without a specific view it should map to my view `view`. I.e., visiting www.mysite.com/collection/ should map to www.mysite.com/collection/view/. Well, how do you like my improved code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T19:29:50.850",
"Id": "28694",
"Score": "0",
"body": "Thanks a bunch for the really detailed answer, by the way! I will give you the correct answer if no one goes into detail about how I've done wrong MVC-wise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T23:13:21.523",
"Id": "28699",
"Score": "0",
"body": "Okay, now `_get_nav()` will return `$this->config->item('collection_nav')`. This array value is loaded from a CI config file."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T16:16:14.683",
"Id": "17965",
"ParentId": "17941",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T00:53:00.720",
"Id": "17941",
"Score": "2",
"Tags": [
"php",
"programming-challenge",
"mvc",
"codeigniter"
],
"Title": "CodeIgniter nav/menu insecurities"
}
|
17941
|
<p>I am trying to learn the absolute best way to program/design classes in PHP. I am hoping that you would be able to review and critique this simple class.</p>
<p>Note: I know that there aren't any comments. Please don't critique me on that.</p>
<pre><code><?php
class VisitorCounter
{
protected $numVisits;
protected $db;
public function __construct($dbh)
{
$this->db = $dbh;
}
public function updateNumVisits()
{
if(!$this->getNumVisits() || !$this->firstTimeHere()){ return false; }
$_SESSION['new_visitor'] = 1;
$sql = "UPDATE stats SET visits=". ++$this->numVisits ." WHERE id=2";
if(!$this->db->query($sql)){
$sql = "INSERT INTO stats (visits) VALUES (". ++$this->numVisits .")";
return $this->db->query($sql)? true : false;
}
return true;
}
protected function firstTimeHere()
{
if(isset($_SESSION['new_visitor'])){
return false;
}
return true;
}
protected function getNumVisits()
{
$result = $this->db->query("SELECT * FROM stats");
if($row = $this->db->fetch_array($result)){
return $this->numVisits = $row['visits'];
}
return false;
}
}
</code></pre>
<h2>Implementation</h2>
<pre><code>$Counter = new VisitorCounter($db);
$Counter->updateNumVisits();
</code></pre>
<h2>Questions</h2>
<ol>
<li><p>Is it ever ok to "for example", to move the <code>$Counter->updateNumVisits()</code> directly into the constructor? Or is that NEVER good to do, even in the simplest of scenarios? I'm reading that it is best only to do simple assignments in the constructor.</p></li>
<li><p>Inside the function <code>updateNumVisits()</code>, I have a conditional that runs a function <code>getNumVisits()</code>. If this is not advisable, when should I call this function so that <code>updateNumVisits()</code> will have access to the latest visit count?</p></li>
<li><p>I read many Code Review posts about not using globals, and so I got rid of my $db global out of the class, and injected it in the constructor. What about <code>$_SESSION</code> and <code>$_POST</code> values? Is it ok to have them inside your class?</p></li>
<li><p>How would you write this class?</p></li>
<li><p>I was also hoping that you might know of a very simple open source PHP project that someone built that I can study and learn from. One that follows all the best practices mentioned here on this website. For instance that uses DI, and follows all the principles of good coding practices. I downloaded the Zend framework and CodeIgnitor but they are too complex and too big for my current understanding.</p></li>
</ol>
|
[] |
[
{
"body": "<ol>\n<li>The construcotr may not contain any business logic/work process</li>\n<li>Your logic is not enough clear to me (hard coded WHERE clause first [id=2] then in getNumVisits() is just a simple select all query, etc.)</li>\n<li>No they should not be used in classes, force to inject them into the worker methods (ISession interface)</li>\n<li>Clarify your logic please</li>\n<li>Just read the common OO and SOLID principles, search for Martin Flowler's name</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T16:22:06.703",
"Id": "28602",
"Score": "0",
"body": "Thx!! **2**. That WHERE clause is checking the database for a table called \"stats\". In that table there is a single record that happens to have an id of 2. That is where the number of unique visitors is being stored. I don't know how best to do this. Georg mentioned that I don't need a numVisits property and the getNumVisits() method anymore which is great! I'm just trying to figure out how a seasoned developer would write this exact simple Counter class. \n\n**5**.I read the SOLID principles yesterday before making this post. Good stuff! I want to find an actual complete small project to study."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T08:02:48.033",
"Id": "17950",
"ParentId": "17944",
"Score": "3"
}
},
{
"body": "<p>In addition to Peters advice, I would recommend:</p>\n\n<p>2) to increase to value in the db without data from a previously read query. This allows race conditions to happen. Imagine what could happen (in this order, may also appear from different tabs with the same user): </p>\n\n<ul>\n<li>user a reading the value 1</li>\n<li>user b also reading 1</li>\n<li>user a updating to 2</li>\n<li>user b updating to 2 </li>\n</ul>\n\n<p>Better use \"UPDATE stats SET visits=visits+1 WHERE id=2\" to let the db increment stuff for you. As a side effect you don't need the <code>$numVisits</code> field anymore. </p>\n\n<p>5) make fields and helper methods private. Search phrase for further reading here is encapsulation.</p>\n\n<p>4) Write a client, which uses the class to see if it works as expected. Usually this is done via unit-test. You may then encounter the problem that you want to somehow mock the db - connection. Often, and as well in this case, simple examples seem to be overloaded when using 'real' separation of concerns, but try to hide the db behind an interface (e.g. Counter) which has one implementation for production (<code>DBCounter</code>) and one for testing (<code>MockCounter</code>). You can inject the counter via constructor and make a private $counter field. Then call $counter.increase or $counter.get in your code and move all the db-related stuff to the db-implementation. This not only allows testing your business-logic separately but also leads to classes more reusable and with higher cohesion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T16:14:48.337",
"Id": "28601",
"Score": "0",
"body": "Thx for the info! \n**2.** I never thought of that! Good idea! Is it advisable to have a hardcoded SQL statement? This class is only reusable if a project has a \"stats\" table, with a record with an id of 2? Should I pass this data into the constructor as \"options\"? I want to do things the way a senior dev would design it. \n\n**4.** I appreciate the info on unit testing, etc, but I'm not ready to learn that yet. I'm just trying to figure out how to write well designed classes.\n\nAlso, **2.**, if getNumVisits() was necessary, would it be ok to run that code in the conditional of a different method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:39:09.180",
"Id": "28639",
"Score": "0",
"body": "**About making the fields and helper methods private.** The only reason I didn't make them private is because I thought that it would be better to make them protected in all my classes so that if I needed to extend them down the road, I wouldn't have to change the properties from private to protected later. Is the proper way to make them all private, and then if you need to extend them later to make them protected? @mseancole"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:34:39.647",
"Id": "28643",
"Score": "0",
"body": "@darga33: If you are absolutely positive that you are going to allow those fields to be extended, then I see no problem with this. Otherwise using private ensures that an element isn't extended when you don't want it to be. Here's some [further reading](http://stackoverflow.com/a/2028629/1015656) on the subject. BTW: tagging me in another's comments isn't going to ping me. I just happened to see the new content and answered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T11:35:32.470",
"Id": "28737",
"Score": "0",
"body": "@darga33 In my Opinion a senior dev would design it writing tests. So this is not a contradiction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T11:43:11.730",
"Id": "28739",
"Score": "0",
"body": "@darga33 If you are pushing the implementation into a DBCounter class, you only have to touch this code if you need another DB structure. It depends on whether you are designing the code the run in one and only one app (where it is unlikely to change and therefore probably best hardcoded in the DBCounter class). Or are you designing a framework api, where the client of the DBCounter wants to have control over the table name and where-clause? Then you probably want to inject this. I do belief design is often not about wrong or right but making considerations about what trade-off fits best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T17:50:08.710",
"Id": "28767",
"Score": "0",
"body": "Yeah, I want to design everything to where it can be reused. That is my goal. :-)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T08:28:06.993",
"Id": "17951",
"ParentId": "17944",
"Score": "4"
}
},
{
"body": "<p>I think the other two answers answered your specific questions adequately. This will instead focus on the content.</p>\n\n<p>Comments missing from a class are not as important as comments missing from an API or interface or abstract class. I wouldn't worry about it here. However, I would eventually expect to see some sort of interface and/or abstract class be implemented. In fact, it is normally considered best practice to start off with these.</p>\n\n<p>Whitespace is your friend. Don't scrunch everything up to one line. You can get away with this if the lines are short, less than 80 characters including whitespace, but even then I would say that adding a newline makes them a little easier to read. This is a preference but one many appreciate.</p>\n\n<pre><code>if(!$this->getNumVisits() || !$this->firstTimeHere()){\n return false;\n}\n</code></pre>\n\n<p>I'm not really familiar with SQL, but your SQL logic looks like it might be plain MySQL. I would consider using PDO or MySQLi instead and taking advantage of the prepared statements. Additionally, as you have previously asked, these SQL statements probably shouldn't be hardcoded into your class. This limits its extensibility, however, I'll leave that open in case anyone else wants to add a more thorough explanation.</p>\n\n<p>If you have a return statement that reflects a boolean value depending on the state of some expression, then you don't have to explicitly define those boolean states. You can just return the expression directly. Doing so may sometimes mean that your return values may not be pure boolean values but with the loose typing PHP has this shouldn't be much of a problem. However, sometimes it is undesirable to have anything other than a pure boolean value. In this case you can typecast the result.</p>\n\n<pre><code>return $this->db->query( $sql );\n//typecasting\nreturn ( bool ) $this->db->query( $sql );\n\n//similarly\nreturn isset( $_SESSION[ 'new_visitor' ] );\n</code></pre>\n\n<p>Overall this looks pretty good, but, as you said, this is a pretty simple class. Good job never-the-less, and I commend your abandoning the globals. The world is a better place because of it. If, as you seem to be implying, you are still using the globals outside of your class, I would strongly urge you to try refactoring to remove them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:54:03.367",
"Id": "28615",
"Score": "0",
"body": "First off, thanks for the answer! I never thought about returning a bool directly without testing for it first.\n\nI was using mysql, but only because I wanted to focus on learning how to build proper classes first. Then I am going to learn either PDO or Mysqli and write a class that can be swapped out. \n\nAlso, I am going to learn docblock notation too. I'm just focusing on class design right now. And as far as the global, I am going to get rid of it completely. It's amazing that you recognized that I still had it hiding! Probably because I didn't write $db = new Db();, is that how you knew?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:54:38.453",
"Id": "28616",
"Score": "0",
"body": "By the way, when I learn PDO, or MySqli which one do you think would be better? I have heard much praise about PDO, so I am leaning towards that! But it seems like it might have a longer learning curve?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:15:04.993",
"Id": "28619",
"Score": "0",
"body": "@darga33: \"...so I got rid of my $db global out of **the class**...\" Was just using the queues from your post. Globals are normally really hard to spot, which is one of the reasons they aren't well liked. A tell-tale sign of a global is usually just a variable that appears out of nowhere. Though that could just as easily be a variable-variable which are equally bad but a little easier to distinguish because they are at least still in the local scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:15:25.820",
"Id": "28620",
"Score": "0",
"body": "From my limited experience PDO is fairly similar to MySQL in syntax and seems to be more popular. But as to which one is better, I think they are both equally good and which one you choose depends on your circumstances and preference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:41:16.540",
"Id": "28640",
"Score": "0",
"body": "Makes perfect sense!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:46:43.067",
"Id": "28649",
"Score": "0",
"body": "It's too bad you can't accept more than one answer! All of the posts were really good! Thx for the further reading link in georg's post!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:17:04.570",
"Id": "28660",
"Score": "0",
"body": "@darga33 Unless you specifically need one of the few capabilities that MySQLi has that PDO doesn't, I would go with PDO. PDO can interact with around a dozen databases with a common API, whereas MySQLi is limited to one. (The dialect of SQL will of course be different though. By just changing the connection, a MSSQL statement won't magically work with MySQL -- though if you stick to standard SQL, mismatches in dialect are relatively rare.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:38:21.023",
"Id": "28663",
"Score": "0",
"body": "Thx corbin! I am going to take a look at both!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T03:23:35.243",
"Id": "28704",
"Score": "0",
"body": "Hey thanks mseancole for that last comment you made in that other answer!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T16:59:38.217",
"Id": "17966",
"ParentId": "17944",
"Score": "2"
}
},
{
"body": "<p>First of all, I started rewriting your class but found many implementation problems design wise that stopped me from rewriting it (because it would be to much for you to learn in one go and would take me a long time to design, code and explain). So I have done a small portion.</p>\n\n<p><strong>Problems Are</strong></p>\n\n<ol>\n<li>No type casting so ANY object could be passed to the constructor</li>\n<li>What if the database object changes? The method calls on the db object inside the <code>VisitorCounter</code> class will break</li>\n<li>You are doing two roles inside the <code>VisitorCounter</code> class, you are both keeping a global visitor count using the database AND trying to keep track of the users visits. Also, you are hard coding it to the <code>$_SESSION</code>! What if you want to use APC or Memcache for example!? Code changes would occur.</li>\n<li>You are not programming to interfaces but instead to concrete classes (and globals i.e. $_SESSION)</li>\n</ol>\n\n<p><strong>Solution</strong></p>\n\n<p>This is a semi pseudo (not complete but will show for demonstration purposes) PHP example just to demonstrate many things for you to learn but i have only taken out the site counter part of your <code>visitorcounter</code> class. You can implement the<code>visitorcounter</code> in exactly the same way I have done for the DB & Site Counter, but instead for Session & Visitor Counter which would be brilliant practice for you! ;)</p>\n\n<p>Read the comments in the comment.</p>\n\n<pre><code>/**\n* by programming to this db interface, you can CHANGE the db class to ANY class you want at any time. As long as the new class\n* implements this interface, the rest of the code will no how to handle the class :) this demonstrates programming to implementations\n* and not to (concrete) classes\n*/\ninterface db_connection {\n public function connected();\n public function query($sql);\n}\n\n/**\n* this will be where the database specific database calls will be made. I have named this one mysql, but I only\n* did this because it means I could have db_oracle (and others), and if I were to pass a db_oracle instace to the visitor counter construct\n* it would still work :D as long as the db_oracle class implemented db_connection. You can then interchange db_mysql and db_oracle as you wish\n*/\nclass db_mysql implements db_connection {\n public function connected() {\n //returns true or false depending on if connected\n }\n public function query($sql) {\n //actually makes the query, returns the result resource if ok, false if it failed\n }\n public function escape($string) {\n //escapes the string to protect from sql injection attacks\n }\n public function result($sql_resource) {\n //if the resource contains results, will return the first field from the first row of the result, FALSE otherwise\n }\n //... and all the other methods you want such as connect() disconnect() ping() etc...\n}\n/**\n* site counter\n*/\nclass site_counter {\n\n private $db = null;\n private $total = 0;\n\n public function __construct(db_connection $db) {\n $this->db = $db;\n }\n\n /**\n * increments the site counter\n */ \n\npublic function increment($step = 1) {\n\n //ensure the step is numeric\n if ( ! is_numeric($step)) {\n throw new Exception(\"Expected a number, got something else!\");\n return false; //didn't work\n }\n\n //notice the limit clause, use this to indicate to SQL that it no longer has to keep searching for more to update\n //you can increment existing fields by using SQL directly, don't do things the long way around as you did as you will also have concurrency issues (another poster I believe explained it)\n $step = $this->db->escape($step); //just to be safe ;)\n if ($this->db->query(\"UPDATE stats SET visits=visits+{$step} LIMIT 1;\")) {\n return true; //worked ok\n }\n\n return false; //didn't work\n\n}\n\n\n /**\n * resets the counter in the database and session\n */\n public function reset($to = 0) {\n if (is_numeric($to)) {\n $to = $this->db->escape($to); //just to be safe ;)\n //notice the limit clause, use this to indicate to SQL that it no longer has to keep searching for more to update\n return $this->db->query(\"UPDATE stats SET visits={$to} LIMIT 1;\");\n } else {\n throw new Exception(\"Expected a number, got something else!\");\n }\n //something went wrong\n return false;\n }\n\n /**\n * resets the counter in the database and session\n */\n public function get_total_hits() {\n //the (int) is called type casting, so false (if the query fails for example) will return 0\n return (int) $this->db->result($this->db->query(\"UPDATE stats SET visits={$to} LIMIT 1;\"));\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:22:27.183",
"Id": "28641",
"Score": "0",
"body": "Ok your answer was awesome! Some things.... \nI was actually only trying to update the user counter if it was that person's first SESSION visit to the site. I wasn't actually trying to keep track of each user's total visits. But I would like to do what you said, but I dont' quite understand what you mean when you said this \"You can implement the visitorcounter in exactly the same way i have done for the DB & Site Counter, but instead for Session & Visitor Counter\" ? But everything else you said, I completely follow, and agree with. All the answers were great but this one went above and beyond!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:32:59.063",
"Id": "28642",
"Score": "0",
"body": "\"You can implement the visitorcou...\" i mean if you want to keep track of how many hits a visitor has made during that specific session you can add that using the same design (with the interface, class, passing an instance of the class through the construct etc) as i did with the site_counter class. But instead of a database, your using a session ;) If you still don't understand, don't worry about it as long as you followed and understood that code i wrote ;) glad it helped."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:34:49.047",
"Id": "28644",
"Score": "0",
"body": "A couple things... In your function get_total_hits(), I think you accidentally forgot to run reset() and in your interface comment I think you meant \"programming to an interface\". I just wanted to mention that for when other people learn from your answer. And one incredibly awesome thing that I read about yesterday is about returning early. I want to start doing that. So for instance, in each one of the functions where we check to see if something is numeric, could we do... if(!is_numeric(){ throw exception return false;}, Then there is less if nesting! I have a lot to learn!!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:38:36.300",
"Id": "28646",
"Score": "0",
"body": "Ok, I see what you mean now! Thanks again!!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:40:09.900",
"Id": "28647",
"Score": "0",
"body": "I'm going to implement all of these things when I write a PDO class, any good PDO class that isn't crazily complicated that you know about that I can take a look at?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:48:22.583",
"Id": "28651",
"Score": "0",
"body": "\", could we do... if(!is_numeric(){ throw exception return false;}\" yes you could, and that would be better. Returning early is always good! It also lets you reduce nested if else conditions to multiple one level if else in many cases. Makes code MUCH easier to read ;) As for the reset, no, that will reset the entire counter to 0. It's purpose is if you want to reset the site counter at any time and start counting hits again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:49:59.457",
"Id": "28652",
"Score": "0",
"body": "There are a few issues. Your interface is incomplete. The implication that you need to create a new class to wrap your database logic is misguided. Most databases are already in a class and therefore should be used directly without the abstraction. Your code is also violating the Arrow Anti-Pattern, try reversing your if statements and dropping the else to return early and avoid the heavy indentation. `if( ! is_numeric( $step ) ) { throw new Exception( '...' ); }` Otherwise +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:50:11.020",
"Id": "28653",
"Score": "0",
"body": "If your using mysql, you could use mysqli which makes things a little simpler than PDO since you're only working with methods/functions that are ment for MySQL instead of a box full of not just mysql, but others as well which can to some such as yourself seem a little confusing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:51:21.483",
"Id": "28654",
"Score": "0",
"body": "Oh... I see you covered it while I was typing nevermind..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:58:56.390",
"Id": "28656",
"Score": "0",
"body": "@mseancole just updated the code (and had a problem with the damn editor Ctrl+K not working so sorry about the indenting). As for the interface not being complete, i know it's not. It's just a \"guide\" to show how to program towards an interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:08:31.230",
"Id": "28658",
"Score": "0",
"body": "Correct me if I am wrong, but when you say \"The implication that you need to create a new class to wrap your database logic is misguided. Most databases are already in a class and therefore should be used directly without the abstraction.\", are you referring to the fact that you can do $dbh = new MySQLi();, and $dbh is already an object and it doesn't need to be wrapped with methods like query(), etc? I have a little problem, I wrote all of the site classes using the interface of the old MySQL extension, so now I must create a wrapper using the same method names!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:09:00.573",
"Id": "28659",
"Score": "0",
"body": "so in this case, I am going to have to write a wrapper for a MySQLi extension using the same method names as I did with the mysql wrapper class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:39:32.547",
"Id": "28664",
"Score": "0",
"body": "@darga33: Typically the APIs match or are really close. See Corbin's comment in my answer. With MySQLi you would either have to create such a wrapper or refactor your entire class. This is why I said \"most databases\". Though looking at my wording that could have been said more clearly. Sorry for the confusion."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:26:57.183",
"Id": "17977",
"ParentId": "17944",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "17977",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T04:31:52.100",
"Id": "17944",
"Score": "8",
"Tags": [
"php"
],
"Title": "Simple VisitorCounter class"
}
|
17944
|
<pre><code>String Name = "yyyy MM DD abjwg kelk.exe"
public static bool IsNameRight(string Name)
{
string[] temp = Name.Split(' ');
string[] de= Name.Split('.');
if (de[1] == "pdf" && temp .Length == 5)
{
if (temp [0].Length == 4
&& temp [1].Length == 2
&& temp [3].Length == 2
&& temp [4] == "abjwg"
&& temp [5] == "kelk.exe")
return true;
else
return false;
}
return false;
}
</code></pre>
<p>I am using .NET 3.5 and C#</p>
<p><strong>EDIT</strong></p>
<p>You could use Regular expressions but I have never used it or know how to use it, and don't know if it is a good practice.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:23:12.730",
"Id": "28637",
"Score": "1",
"body": "What will this code do if given `foo.pdf.exe`?"
}
] |
[
{
"body": "<p>The method name would be better called <code>IsNameValid</code> and the parameter <code>name</code> should be camel cased.</p>\n\n<pre><code>public static bool IsNameValid(string name)\n{\n // firstly always validate parameters, either throw an exception or return false.\n if (name == null) { throw new ArgumentNullException(\"name\"); }\n\n // use more descriptive variable names, what does 'de' mean?\n string[] temp = name.Split(' ');\n string[] de= name.Split('.');\n\n // check that the arrays contain the correct number of values or you will get an exception accessing the indexer.\n if (de.Lengh < 2 || temp.Length < 5) { return false; }\n\n return de[1] == \"pdf\"\n && temp[0].Length == 4\n && temp[1].Length == 2 \n && temp[2].Length == 2\n && temp[3] == \"abjwg\" \n && temp[4] == \"kelk.exe\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:34:15.100",
"Id": "28662",
"Score": "0",
"body": "It also would be better if you wrap the statements after return into another method: \n\nreturn hasValidArgumentAndExtensions(de, temp);"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T08:46:09.297",
"Id": "17952",
"ParentId": "17949",
"Score": "7"
}
},
{
"body": "<pre><code>private static readonly Regex pattern = new Regex(@\"[0-9]{4} [0-9]{2} [0-9]{2} [A-Za-z0-9]{5} [A-Za-z0-9]{4}\\.exe\");\n\npublic static bool IsNameRight(string name)\n{\n return pattern.IsMatch(name);\n}\n</code></pre>\n\n<ul>\n<li><code>[0-9]</code> means a character which is a digit between 0 and 9.</li>\n<li><code>[A-Za-z0-9]</code> means a character which is between A and Z (uppercase) or a and z (lowercase) or a digit between 0-9.</li>\n<li><code>{4}</code> exactly four times</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T12:51:27.740",
"Id": "28576",
"Score": "0",
"body": "if the whole executable name is variable yours is of course better than mine"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T13:00:08.227",
"Id": "28577",
"Score": "0",
"body": "@fix_likes_coding: I believe it is based upon 'As I want to confirm that my string is in this format \"yyyy MM dd ABCDE FGHI.EXE\"'."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T12:40:51.293",
"Id": "17956",
"ParentId": "17949",
"Score": "8"
}
},
{
"body": "<p>I can think of at least few things with the code. Skip some of the redundant <code>else</code> and <code>if</code> clasues.</p>\n\n<pre><code>String name = \"yyyy MM DD abjwg kelk.exe\"\n\npublic static bool IsNameRight(string Name)\n{\n string[] temp = Name.Split(' ');\n string[] de = Name.Split('.');\n\n if (de[1] != \"pdf\" && temp.Length != 5)\n return false;\n\n if (temp [0].Length == 4\n && temp [1].Length == 2 \n && temp [3].Length == 2\n && temp [4] == \"abjwg\" \n && temp [5] == \"kelk.exe\")\n return true;\n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T12:42:08.847",
"Id": "17957",
"ParentId": "17949",
"Score": "2"
}
},
{
"body": "<p>As you wanted to use RegEx I have a recommendation for you:</p>\n\n<pre><code>public static bool IsValidName(string Name)\n{\n if(String.IsNullOrEmpty(Name))\n return new ArgumentNullException();\n\n string pattern = @\"^[0-9]{4} [0-9]{2} [0-9]{2} abjwg kelk\\\\.exe$\";\n return Regex.IsMatch(Name, pattern);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T13:09:37.780",
"Id": "28578",
"Score": "0",
"body": "getting error here \"\\.exe$\" for the decimal"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:27:28.547",
"Id": "28606",
"Score": "2",
"body": "you may want to try to escape the backslash by using another backslash: `kelk\\\\.exe$`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T12:49:42.233",
"Id": "17958",
"ParentId": "17949",
"Score": "15"
}
},
{
"body": "<p>If you are trying to get the extension of a file, I would use</p>\n\n<p>System.Io.Path.GetExtension</p>\n\n<p><strong>Update</strong></p>\n\n<p>Since de seem to only be used for getting the extension.</p>\n\n<pre><code>string[] de= Name.Split('.');\n</code></pre>\n\n<p>could be changed to</p>\n\n<pre><code>string de = System.Io.Path.GetExtension(Name);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T15:52:24.603",
"Id": "28599",
"Score": "1",
"body": "You might want to add a code example of what you are suggesting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T15:29:28.157",
"Id": "17964",
"ParentId": "17949",
"Score": "10"
}
},
{
"body": "<p>Here's another way of improving your code:</p>\n\n<pre><code>String name = \"yyyy MM DD abjwg kelk.exe\"\n\npublic static bool isNameRight( string name )\n{\n string[] de = name.Split( \".\" );\n string[] temp = de[0].Split( \" \" );\n\n if ( ! ( de[1] == \"pdf\" && temp.Length == 5 ) )\n return false;\n\n return ( temp[0].Length == 4\n && temp[1].Length == 2 \n && temp[2].Length == 2\n && temp[3] == \"abjwg\" \n && temp[4] == \"kelk\" );\n}\n</code></pre>\n\n<p>I know this isn't about finding and fixing bugs, but it seemed important to note that given your <strong>name</strong> string and your function logic, it will always return false, because you're testing for <code>temp [5] == \"kelk.exe\"</code> after <code>de[1] == \"pdf\"</code> so in this case, if <strong>de[1]</strong> equals \"pdf\" then <strong>temp[5]</strong> will never have the <strong>.exe</strong> part, it would have <strong>.pdf</strong>. That's also why I removed the extension from <strong>temp[4]</strong> value.</p>\n\n<p>Additionally, I would use @the_lotus way of dealing with the file extension.</p>\n\n<p>I hope you find this helpful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:22:57.870",
"Id": "17970",
"ParentId": "17949",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "17952",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T07:59:08.617",
"Id": "17949",
"Score": "6",
"Tags": [
"c#",
".net"
],
"Title": "Validate that a given string (name) meets certain requirements"
}
|
17949
|
<p>I'm making an avatar creator with jQuery where users can select and change hair, eye and skin colour. The page is a form with different values and when the user clicks on the form options the values are translated to CSS. This allows the avatar options to change. <a href="https://github.com/fgiasson/jquery-enhanced-cookie" rel="nofollow">jQuery enhanced cookie</a> is used to store the data values.</p>
<p>Everything is working fine, except my code is very repetitive.</p>
<p>Here is an extract from my first file:</p>
<pre><code>/* Capture Gender */
$(".gender input").click(function () {
var gender = $(this).val();
var input = 'input[value="hair' + gender + '1"]';
$(input).attr('checked', 'checked');
$("span#hair").removeAttr('class');
$("span#hair").addClass('hair' + gender + '1');
$.cookie(product + "hairstyle", 'hair' + gender + '1');
var classes = $('#container').attr('class').split(' ');
classes[1] = gender;
$('#container').attr('class', classes.join(' '));
$.cookie(product + "gender", gender);
});
/* Capture Hair Style */
$(".hairstyle input").click(function () {
var newhairstyle = $(this).val();
$("span#hair").removeAttr('class');
$("span#hair").addClass(newhairstyle);
$.cookie(product + "hairstyle", newhairstyle);
});
/* Capture Colour-Hair */
$(".haircolour input").click(function () {
var newhaircolour = $(this).val();
var classes = $('#container').attr('class').split(' ');
classes[0] = newhaircolour;
$('#container').attr('class', classes.join(' '));
$.cookie(product + "haircolour", newhaircolour);
});
</code></pre>
<p>(This goes on for several lines (<a href="http://jsfiddle.net/big_smile/qSEGa/2/" rel="nofollow">see here</a>)).</p>
<p>I then have a second file, which repeats some of the code:</p>
<pre><code>var hairstylestorage = $.cookie(product + "hairstyle");
if (hairstylestorage === null) {
$.cookie(product + "hairstyle", defaulthairstyle);
} else {
var newhairstyle = $.cookie(product + "hairstyle");
$("span#hair").removeAttr('class');
$("span#hair").addClass(newhairstyle);
var input = 'input[value="'+ newhairstyle + '"]';
$(input).attr('checked', 'checked');
}
var haircolourstorage = $.cookie(product + "haircolour");
if (haircolourstorage === null) {
$.cookie(product + "haircolour", defaulthaircolour);
} else {
var newhaircolour = $.cookie(product + "haircolour");
var classes = $('#container').attr('class').split(' ');
classes[0] = newhaircolour;
$('#container').attr('class', classes.join(' '));
}
</code></pre>
<p>This also goes on for several lines (<a href="http://jsfiddle.net/big_smile/3C6uY/3/" rel="nofollow">see here</a>).</p>
<p>How can I make it less repeatable? I thought I could use a function as shown on <a href="http://www.jquery4u.com/jquery-functions/5-ways-declare-functions-jquery/#.UIqiL2l25M4" rel="nofollow">here</a> and then pass through the variables that change. However, as a lot of my code uses functions, I'm not sure how to call a function inside of a function. </p>
|
[] |
[
{
"body": "<p>You are perfectly right to be looking at functions as you way out of repetition. In this case the code:</p>\n\n<pre><code>$(\"span#hair\").removeAttr('class');\n$(\"span#hair\").addClass('hair' + gender + '1');\n$.cookie(product + \"hairstyle\", 'hair' + gender + '1');\n</code></pre>\n\n<p>appears one more time with a slightly different class name. You could put this in a function:</p>\n\n<pre><code>var changeHairstyle = function(hairClass){\n $(\"span#hair\").removeAttr('class');\n $(\"span#hair\").addClass(hairClass);\n $.cookie(product + \"hairstyle\", hairClass);\n};\n</code></pre>\n\n<p>and call it (in the second case) with:</p>\n\n<pre><code>$(\".hairstyle input\").click(function () {\n var newhairstyle = $(this).val();\n changeHairstyle(newhairstyle);\n});\n</code></pre>\n\n<p>This example illustrates well how to work with reuse. Look for similarities and put them in functions and you have a good start to writing code more efficiently. There are much more to learn but I think this is one of the most important lessons to learn.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T16:25:59.950",
"Id": "28714",
"Score": "0",
"body": "Thanks for your help! The only problem is that I would have to write a function for each option. I would like to use one function for all options (and then add in the code the changes). I tried using this but it doesn't work: `var personalisation = function(option){\n $(option + \"input\").click(function() {\n var newoption = $(option).val;\n var selectoroption = \"#\"+newoption;\n alert(selectoroption);\n $(\"#\"+option).removeAttr('class');\n $(\"#\"+option).addClass(newoption);\n $.cookie(product + \"option\", newoption);\n });\n};` I'm not sure why, as I followed your example exactly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T16:26:49.230",
"Id": "28715",
"Score": "0",
"body": "Also, do I use `$.fn.` for functions or `var` for functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T19:28:41.807",
"Id": "28718",
"Score": "0",
"body": "`$.fn.` ties the function to the jquery object whereas `var` is just the normal way of defining functions in javascript. To call a normal function you don't need the leading `$.`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T19:32:38.480",
"Id": "28719",
"Score": "0",
"body": "About the non working code. What are you passing into `personalisation`? Is it a string? What problems do you encounter? What is `product`? A tips to sort out this kind of problems is to use firebug in firefox to step through the code. You will be able to see the values of all variables which is good for understanding what is happening."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T21:36:13.673",
"Id": "28722",
"Score": "0",
"body": "This is the code I am passing in `personalisation(hairstyle)` . `product` is a variable at the top of my code which extracts the body class and uses it as a string. Thanks for any help you can offer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T21:50:53.863",
"Id": "28723",
"Score": "0",
"body": "`$(option).val` will likely give you a function object. You need to add () to actually call it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T20:13:38.463",
"Id": "28774",
"Score": "0",
"body": "Thanks for your help. I think I will have to read up more on how jQuery works..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T20:51:52.990",
"Id": "28777",
"Score": "0",
"body": "Actually I was about to write it in pure server side when I saw your javascript tag. If you don't mind a page reload you can just trigger the correct css depending on a parameter to the class. (Also - it is not that hard to the same thing with plain javascript but it is way easier with jquery.)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T15:37:44.737",
"Id": "18015",
"ParentId": "17962",
"Score": "0"
}
},
{
"body": "<p>froderik is correct in that you should start by looking at the code and pick out similarities that can be extracted into functions. Doing this a little bit at a time will make it easier to read and then you will find more and more things to combine.</p>\n\n<p>For instance, this chunk of code: </p>\n\n<pre><code>var classes = $('#container').attr('class').split(' ');\nclasses[0] = newhaircolour;\n$('#container').attr('class', classes.join(' '));\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>function changeContainerClass(ix, value) {\n var classes = $('#container').attr('class').split(' ');\n classes[ix] = value;\n $('#container').attr('class', classes.join(' '));\n}\n</code></pre>\n\n<p>And </p>\n\n<pre><code>$(\"#eyecolour\").removeAttr('class');\n$(\"#eyecolour\").addClass(neweyecolour);\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>function setClass(propName, value) {\n $(\"#\" + propName).removeAttr('class');\n $(\"#\" + propName).addClass(value);\n}\n</code></pre>\n\n<p>After those are replaced in various areas, your code now looks like this:</p>\n\n<pre><code>$(\".eyecolour input\").click(function () {\n var neweyecolour = $(this).val();\n setClass('eyecolour', neweyecolour);\n $.cookie(product + \"eyecolour\", neweyecolour);\n});\n$(\".skincolour input\").click(function () {\n var newskincolour = $(this).val();\n changeContainerClass(2, newskincolour)\n $.cookie(product + \"skincolour\", newskincolour);\n});\n</code></pre>\n\n<p>Not a huge change but you can see a pattern forming.</p>\n\n<ol>\n<li>Add click event to inputs in a div with a class name selector. (<code>.eyecolour inputs</code>)</li>\n<li>Set the class of the div to the value of the clicked input.</li>\n<li>Set the class of the container item.</li>\n<li>Set the cookie.</li>\n</ol>\n\n<p>Numbers 2 and 3 are not done every time but we will work around that. </p>\n\n<p>So let's combine these items (and simplify the class setting):</p>\n\n<pre><code>function addClickHandler(propName, containerIndex) {\n $('.' + propName + ' input').click(function() { \n var value = $(this).val();\n var input = $('#' + propName);\n if (input) { input.removeClass().addClass(value); } // if input exists, removes all classes and then adds new class\n if (containerIndex != null && containerIndex != undefined) { // if containerIndex is defined (can't use the truthy check like input because may be 0)\n changeContainerClass(containerIndex, value);\n }\n $.cookie(product + propName, value); // set cookie\n }\n});\n</code></pre>\n\n<p>Now you can call this function like so:</p>\n\n<pre><code>addClickHandler('haircolour', 0);\naddClickHandler('eyecolour'); // we leave off the containerIndex so it will be undefined and therfore ignored.\n</code></pre>\n\n<p>That is a pretty big savings right there. But we can use an array with these values and then just loop through each to add the handler.</p>\n\n<pre><code> var inputs = [\n { prop: 'hairstyle' },\n { prop: 'haircolour', containerIndex: 0 },\n { prop: 'skincolour', containerIndex: 2 },\n { prop: 'eyecolour' },\n { prop: 'glasses' }\n ];\n\nfor (var i = 0; i < inputs.length; i++) {\n addClickHandler(inputs[i].prop, inputs[i].containerIndex);\n}\n</code></pre>\n\n<p>Okay, now on to the other page. You have similar functionality but instead of pulling from the selected form item, you are pulling from the cookie values.</p>\n\n<pre><code>var newglasses = $.cookie(product + \"glasses\");\n$(\"#glasses\").removeAttr('class');\n$(\"#glasses\").addClass(newglasses);\n$.cookie(product + \"glasses\", newglasses); \n</code></pre>\n\n<p>and </p>\n\n<pre><code>var newhaircolour = $.cookie(product + \"haircolour\"); \nvar classes = $('#container').attr('class').split(' ');\nclasses[0] = newhaircolour;\n$('#container').attr('class', classes.join(' '));\n</code></pre>\n\n<p>Well we have already refactored this stuff. And it is the body of the click event handler above. So lets change that to </p>\n\n<pre><code>function setValue(propName, value, containerIndex) {\n var input = $('#' + propName);\n if (input) { input.removeClass().addClass(value); } // if input exists, removes all classes and then adds new class\n if (containerIndex != null && containerIndex != undefined) { // if containerIndex is defined (can't use the truthy check like input because may be 0)\n changeContainerClass(containerIndex, value);\n }\n $.cookie(product + propName, value); // set cookie\n}\nfunction addClickHandler(propName, containerIndex) {\n $('.' + propName + ' input').click(function() { \n setValue(propName, $(this).val(), containerIndex); \n }\n});\n</code></pre>\n\n<p>Now the cookie functionality becomes </p>\n\n<pre><code>var haircolourstorage = $.cookie(product + \"haircolour\"); \nif (haircolourstorage === null) {\n $.cookie(product + \"haircolour\", defaulthaircolour);\n} else {\n var newhaircolour = $.cookie(product + \"haircolour\"); \n setValue(\"haircolour\", newhaircolour);\n}\n</code></pre>\n\n<p>And (I'm sure you saw this coming by now) that can be refactored into:</p>\n\n<pre><code>function loadFromCookie(prodName, containerIndex) {\n var storage = $.cookie(product + propName);\n if (storage === null) {\n var defaultval = $(\".\" + propName + \" input\").val(); // this follows a standard pattern so we can just use that here.\n $.cookie(product + propName, defaultval);\n } else {\n var newValue = $.cookie(product + propName);\n this.setValue(propName, newValue, containerIndex);\n }\n}\n</code></pre>\n\n<p>And that can be used using the same array as we setup before.</p>\n\n<pre><code>for (var i = 0; i < inputs.length; i++) {\n loadFromCookie(inputs[i].prop, inputs[i].containerIndex);\n}\n</code></pre>\n\n<p>I have been using function declarations. <code>function functionName() {}</code> But there is also function expressions <code>var functionName = function() {};</code>. There are a few differences between these but for our purposes now they are the same (if you are interested, google javascript hoisting for one of the big differences). So I could have declared each of these expressions using that technique and used them exactly the same. In fact I can put these functions into another function and that will accomplish two things.</p>\n\n<ol>\n<li><p>It will move all of these functions out of the global namespace (ALWAYS beneficial). This is not really a problem when you declare them inside jquery's document load function but still useful.</p></li>\n<li><p>I can group these functions together into a \"module\" and stored in a separate file.</p></li>\n</ol>\n\n<p>So that is what I did here:</p>\n\n<pre><code>var AvatarCreator = function (productName) {\n var product = productName;\n var inputs = [\n { prop: 'hairstyle' },\n { prop: 'haircolour', containerIndex: 0 },\n { prop: 'skincolour', containerIndex: 2 },\n { prop: 'eyecolour' },\n { prop: 'glasses' }\n ]; // we declare the array inside the function but it could just as easily be passed in like the product.\n\nreturn { // we return an object so that we can call functions later.\n\n // this function handles the changes to the container class, pass in the index and the value\n changeContainerClass: function (ix, value) {\n var classes = $('#container').attr('class').split(' ');\n classes[ix] = value;\n $('#container').attr('class', classes.join(' '));\n },\n // sets the value of a given property\n setValue: function (propName, value, containerIndex) {\n var input = $('#' + propName);\n if (input) { input.removeClass().addClass(value); } // if input exists, removes all classes and then adds new class\n if (containerIndex != null && containerIndex != undefined) { // if containerIndex is defined (can't use the truthy check like input because may be 0)\n this.changeContainerClass(containerIndex, value);\n }\n $.cookie(product + propName, value); // set cookie\n },\n addClickHandler: function (propName, containerIndex) { // this function adds the click event handler to the input.\n var that = this; // store the current object in temp function (otherwise we cannot access the setValue function) This is a common practice.\n $('.' + propName + ' input').click(function () {\n that.setValue(propName, $(this).val(), containerIndex);\n });\n },\n loadFromCookie: function (propName, containerIndex) { // this handles the cookie retrieval (or storing of the default values)\n var storage = $.cookie(product + propName);\n if (storage === null) {\n //console.log(product + propName + ' not found.');\n var defaultval = $(\".\" + propName + \" input\").val();\n $.cookie(product + propName, defaultval);\n } else {\n var newValue = $.cookie(product + propName);\n this.setValue(propName, newValue, containerIndex);\n //console.log(product + propName + 'found with value - ' + newValue);\n }\n },\n loadAllFromCookies: function () { \n for (var i = 0; i < inputs.length; i++) {\n this.loadFromCookie(inputs[i].prop, inputs[i].containerIndex);\n }\n },\n addAllClickHandlers: function () {\n for (var i = 0; i < inputs.length; i++) {\n this.addClickHandler(inputs[i].prop, inputs[i].containerIndex);\n }\n }\n\n};\n}\n</code></pre>\n\n<p>That function can be stored in a separate file (AvatarCreator.js) and then included on the page as needed.</p>\n\n<pre><code>var product = $('body').attr(\"class\");\n\nvar avatar = new AvatarCreator(product);\navatar.loadAllFromCookies();\n// and/or\navatar.addAllClickHandlers();\n</code></pre>\n\n<p>I did not touch on the personal message, name, and a few others that you had in your code but did not have on the page. But with a few changes to the html to conform to the conventions we have now set up you can easily add those to the array and it will automatically take care of those as well. </p>\n\n<p>The gender selector has a little extra functionality that needs to occur. You can leave that out of the array and handle it completely separately. You could pass that field into the constructor and handle is special within the module (this is probably what I would recommend). or you could even add a callback method to the array objects. </p>\n\n<p>But I will leave that up to you. I think I have given you enough to think about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T14:53:21.223",
"Id": "28995",
"Score": "0",
"body": "@nickies80 Thanks! Your advice has greatly enriched my understanding of jQuery and has been in invaluable help in making me a better coder. I think I will have to learn more about Jquery to get the most out of your advice, but it is already a massive help and has opened up my understanding to new methods and concepts. Thank you very much!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T16:04:32.653",
"Id": "18083",
"ParentId": "17962",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18083",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T15:00:17.353",
"Id": "17962",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"form"
],
"Title": "Avatar creator form"
}
|
17962
|
<p>I'm looking for a way to simplify this code, because I could develop more overloads for <code>TryThis</code> I made the string and int both of class <code>Nullable</code> so that in each overloaded function, the catch block could return the same value. </p>
<p>The problem is I need, if possible, no overloads of <code>TryThis</code>. The function overloads are both identical, except for the type of delegate they are passed. Is there some kind of variable that would encompass any delegate that can be executed? </p>
<pre><code>class Program
{
delegate int MyIntReturn();
delegate string MyStringReturn();
static private MyIntReturn ReadInt = () => {return int.Parse(Console.ReadLine()); };
static private MyStringReturn ReadString = () => { return Console.ReadLine(); };
static private Nullable<int> TryThis(MyIntReturn MyAction)
{
try
{
return MyAction();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
private static Nullable<string> TryThis(MyStringReturn MyAction)
{
try
{
return MyAction();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
</code></pre>
<p>}</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:12:49.733",
"Id": "28603",
"Score": "6",
"body": "fyi, theres no such thing as a `Nullable<string>`. `string` is a reference type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:13:30.120",
"Id": "28604",
"Score": "0",
"body": "`string` is a ref type so `Nullable` doesn't make any sense here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:28:11.960",
"Id": "28607",
"Score": "2",
"body": "Turning exceptions into nulls is *almost never* a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:31:49.357",
"Id": "28609",
"Score": "0",
"body": "@codesparkle Why do you say that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:36:02.927",
"Id": "28610",
"Score": "1",
"body": "Because exceptions need to be *handled*, not *hidden*, in nearly every case. If an exception happens, it tells you what went wrong. If null is returned, you have no idea what went wrong."
}
] |
[
{
"body": "<p>You can use the generic delegate <code>Func<></code>:</p>\n\n<pre><code>static private T TryThis<T>(Func<T> MyAction) {\n try {\n return MyAction();\n } catch (Exception ex) {\n Console.WriteLine(ex.ToString());\n return default(T);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:44:37.203",
"Id": "28612",
"Score": "0",
"body": "If I'm understanding this correctly, is T inferred to be a return type because it is put in angle brackets after `TryThis`? If so, I didn't realize C# could infer the the return type like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:46:55.350",
"Id": "28614",
"Score": "1",
"body": "@ArmorCode: Yes, from C# 4 it can infer the type from what you return from the delegate."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:15:50.133",
"Id": "17969",
"ParentId": "17968",
"Score": "5"
}
},
{
"body": "<p>Generics and Delegates. Note that you can't return null in this modified version of TryThis, so we use the default(T) method to return whatever's most sensible. </p>\n\n<pre><code>class Program\n{\n private delegate T TypeReturn<T>();\n static private TypeReturn<int> ReadInt = () => int.Parse(Console.ReadLine());\n static private TypeReturn<string> ReadString = () => Console.ReadLine(); \n static private T TryThis<T>(TypeReturn<T> MyAction )\n {\n try\n {\n return MyAction() ;\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n return default (T);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:53:00.470",
"Id": "28667",
"Score": "0",
"body": "I am trying to call the code you produced with `selection = TryThis(ReadInt()); // selection is defined as int earlier in code` and i get the error: The type arguments for method 'ConsoleApplication1.Program.TryThis<T>(ConsoleApplication1.Program.DelTypeReturn<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.\n\nI thought that C# can infer that it is of type int..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T22:02:45.840",
"Id": "28668",
"Score": "0",
"body": "`selection = TryThis<int>(ReadInt); // This code worked`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:33:24.347",
"Id": "17972",
"ParentId": "17968",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "17972",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:10:33.307",
"Id": "17968",
"Score": "4",
"Tags": [
"c#",
"delegates"
],
"Title": "How to simplify these delegate functions?"
}
|
17968
|
<p>I'm modeling a reflection-based controller. I would like to know if you agree with my implementation and about what could be enhanced.</p>
<p>I'm starting with reflection and I would like to know if I'm using good practices.</p>
<pre><code>public class StartController extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String vars = req.getParameter("mvc");
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
MainController main = new MainController();
main.RESTProcess(req, resp, context, vars);
}
}
public class MainController extends Controller {
public void RESTProcess(HttpServletRequest req, HttpServletResponse resp, ApplicationContext context, String vars)
throws IOException, ServletException
{
String[] url;
int nvars;
String controller = null;
String action = null;;
String[] params = null;
int i;
int n;
String controllerName;
String actionName;
if(vars == null || "".equals(vars.trim()))
{
this.redirect(resp,"home");
}
else
{
url = vars.split("/");
nvars = url.length;
if(nvars > 0)
{
controller = url[0].trim(); //users
if(nvars > 1)
{
action = url[1].trim(); //edit
if(nvars > 2)
{
n = 0;
params = new String[nvars - 2]; //array[0] = 5 (iduser)
for(i = 2; i < nvars; i++)
{
params[n] = url[i];
n++;
}
}
}
controllerName = this.getFirstUpper(controller) + "Controller"; //HomeController, UserController pattern
if(!controllerName.equals("Controller"))
{
actionName = "action" + this.getFirstUpper(action); //actionIndex, actionEdit pattern
if(!action.equals("action"))
{
try
{
Class classe = Class.forName("com.sample.controller." + controllerName);
try
{
Constructor c = classe.getConstructor(HttpServletRequest.class, HttpServletResponse.class, String[].class);
try
{
Object obj = c.newInstance(req, resp, context, params);
Method m = classe.getMethod(actionName, null);
m.invoke(obj, null);
System.out.println(obj.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
else
{
this.redirect(resp,"home");
}
}
}
public String getFirstUpper(String str)
{
Integer x = str.length();
str = str.substring(0,1).toUpperCase().concat(str.substring(1, x));
return str;
}
}
public class UserController extends Controller {
private HttpServletRequest req;
private HttpServletResponse resp;
private ApplicationContext context;
private String[] params;
public UserController(HttpServletRequest req, HttpServletResponse resp, ApplicationContext context, String[] params)
{
this.req = req;
this.resp = resp;
this.context = context;
this.params = params;
}
public void actionEdit()
{
Long id = Long.valueOf(this.params[0]);
System.out.println("/home/edit");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Only few general comments from me:</p>\n\n<ol>\n<li><p>Start your method names with lowercase.</p></li>\n<li><p>Remove excess <code>try</code> keywords.</p></li>\n<li><p>Catch only specific type of <code>Exception</code>s!</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-08T18:06:30.013",
"Id": "107336",
"Score": "1",
"body": "Please elaborate a bit more on the reasoning behind your proposals. While they are all good, the motto of CR is *\"teach a man how to fish\"* and not *\"give a man a fish\"* ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T13:22:25.637",
"Id": "18043",
"ParentId": "17971",
"Score": "1"
}
},
{
"body": "<p>I would make some changes to <code>getFirstUpper()</code>:</p>\n\n<blockquote>\n<pre><code>public String getFirstUpper(String str)\n{\n Integer x = str.length();\n str = str.substring(0,1).toUpperCase().concat(str.substring(1, x));\n\n return str;\n}\n</code></pre>\n</blockquote>\n\n<p>The name <code>x</code> is not a very good name as it's only a single character. I'm not even sure if a separate variable is needed for this, but if so, consider renaming it to <code>stringLength</code>. The type should also be <code>int</code> instead, which is the return type of <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#length%28%29\" rel=\"nofollow\"><code>String.length()</code></a>. Either way, you can just pass <code>length()</code> directly into <code>substring()</code> (in place of <code>x</code>).</p>\n\n<p>It's also unnecessary to create a <code>str</code> variable if the inner function's return value is just going to be returned right away. Plus, it's already known that this method is supposed to return a <code>String</code>.</p>\n\n<pre><code>return str.substring(0,1).toUpperCase().concat(str.substring(1, str.length()));\n</code></pre>\n\n<p>I also have a general comment regarding curly braces:</p>\n\n<p><a href=\"https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.1.2-blocks-k-r-style\" rel=\"nofollow\">The Java standard dictates the use of \"Egyptian braces,\"</a> which involves putting the opening brace on the same line as the statement, rather than the next line by itself:</p>\n\n<pre><code>public String getFirstUpper(String str) {\n // ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-08T17:47:59.920",
"Id": "59528",
"ParentId": "17971",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:30:01.693",
"Id": "17971",
"Score": "7",
"Tags": [
"java",
"mvc",
"reflection",
"controller"
],
"Title": "Action based controller using reflections"
}
|
17971
|
<p>This is just a fun little exercise I had to do for a homework once (in Java rather than Clojure though). Basically, the goal is to find the number of different coin stacks you can build with the coins 1,2,5 and 10 to form a number N (I believe a closed form solution for this exists, but this isn't what this is about).</p>
<p>My solution here works, but I'm not quite happy with it:</p>
<ul>
<li>Explicit loop. Not sure how to do away with it though.</li>
<li>A few functions there that I think should be core functions, but I can't find them.</li>
<li>Even if they aren't in core, my functions could probably be written somewhat more concisely</li>
</ul>
<p>Anyways, here's my code (by the way, the function is called "fast-iterative" because the exercise was about calculating these values recursively. Which I think is insane due to the branching factor, but whatever):</p>
<pre><code>(ns test.coin-stacks)
(def maximum (partial reduce max))
(defn shift-vector
"Shifts v one to the left, insert shift-val at the right"
[v shift-val]
(conj (vec (rest v)) shift-val))
(defn update
"Updates ks in m with f applied to ks.
I can't believe I have to write this myself."
[m ks f]
(apply assoc m (interleave ks (map (comp f m) ks))))
(defn fast-iterative-coinstacks
"Returns the number of ways to form a coin stack with a total
value of n with coins"
[n coins]
(let [max-coin (maximum coins)
initial-stacks (apply conj [1] (repeat max-coin 0))]
(loop [stacks initial-stacks iteration 0]
(if-not (< iteration n)
(first stacks)
(recur (shift-vector (update stacks coins (partial +' (stacks 0))) 0)
(inc iteration))))))
</code></pre>
|
[] |
[
{
"body": "<p>I would write <code>(def maximum (partial reduce max))</code> as:</p>\n\n<pre><code>(defn max-coll [coll] (apply max coll)) \n</code></pre>\n\n<p>although writing a special function for <code>(apply max coll)</code> seems a bit overdone in my taste.</p>\n\n<p>Another minor rewrite:</p>\n\n<pre><code>(apply conj [1] (repeat max-coin 0))\n=>\n(into [1] (repeat max-coin 0))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T18:41:15.990",
"Id": "17997",
"ParentId": "17973",
"Score": "2"
}
},
{
"body": "<p>How about something like this:</p>\n\n<pre><code>(defn shift-vector\n \"Shifts v one to the left, insert shift-val at the right\"\n [v shift-val]\n (conj (subvec v 1) shift-val))\n\n(defn update-in-all\n \"Updates ks in m with f applied for each value at k.\"\n [m ks f]\n (reduce (fn [m' k] (update-in m' [k] f)) m ks))\n\n(defn fast-iterative-coinstacks\n \"Returns the number of ways to form a coin stack with a total\n value of n with coins\"\n [n coins]\n (let [max-coin (reduce max coins)\n initial-stacks (into [1] (repeat max-coin 0))\n process-stacks (fn [stacks]\n (-> stacks\n (update-in-all coins (partial + (first stacks)))\n (shift-vector 0)))]\n (-> (iterate process-stacks initial-stacks)\n (nth n)\n first)))\n</code></pre>\n\n<p>Some explanations:</p>\n\n<ul>\n<li><p><code>update-in</code> works both with vectors and maps, and can update nested values as well,</p></li>\n<li><p>the threading macro <code>-></code> makes the flow of your code easier to follow,</p></li>\n<li><p>iterate is a really convenient function that given <code>f</code> and <code>x</code> returns a lazy sequence of <code>x</code>, <code>(f x)</code>, <code>(f (f x))</code>...</p></li>\n<li><p>you can do a lot of things with <code>reduce</code>!</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T00:06:25.083",
"Id": "18003",
"ParentId": "17973",
"Score": "4"
}
},
{
"body": "<p>There's a nice recursive solution to this problem:</p>\n\n<pre><code>(defn options [total available-coins]\n (if (seq available-coins) ;; have we got any coins left?\n (let [[[coin max-available] & more-coins] (seq available-coins)\n needed (quot total coin)\n rem (mod total coin)]\n (mapcat \n (fn [n]\n (map #(if (> n 0) (merge % {coin n}) %) \n (options (- total (* coin n)) more-coins))) ;; recursive call\n (range 0 (inc (min needed max-available))))) ;; all possible quantities\n (if (== total 0)\n [{}] ;; empty solution, no coins required\n []))) ;; no solution\n</code></pre>\n\n<p>This outputs the solutions for making a total using a map of coins -> count e.g.</p>\n\n<pre><code>(options 50 {10 3 20 3})\n=> ({10 1, 20 2} \n {10 3, 20 1})\n</code></pre>\n\n<p>Obviously, you can just count the number of solutions if you want the number of different stacks that could be made.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T09:26:42.563",
"Id": "28732",
"Score": "0",
"body": "I don't understand this one, what do you pass to this function and what do you return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T13:03:27.023",
"Id": "28743",
"Score": "0",
"body": "@Cubic: You pass 1) value of the wanted coin stack (`total`) and 2) _\"a map of coins -> count\"_ (`available-coins`) and return a list of map of coins -> count."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:04:27.790",
"Id": "28746",
"Score": "0",
"body": "In that case, this really doesn't solve the same problem. The problem I described doesn't actually put any limits on the coins that can be used, and the ordering of the coins in the stack matters (hence the metaphor of a stack)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T04:12:03.963",
"Id": "18027",
"ParentId": "17973",
"Score": "0"
}
},
{
"body": "<p>Your guess is almost right.\nBecause your <code>shift-vector</code> function simply performs dequeue and enqueue,\nit can be rewritten using <code>clojure.lang.PersistentQueue</code>.</p>\n\n<pre><code>(defn shift-vector\n [q x]\n (-> q pop (conj x)))\n</code></pre>\n\n<p>You can use Clojure queues by starting with <code>clojure.lang.PersistentQeueue/EMPTY</code>.</p>\n\n<p>By the way,\nyour task seems to be a typical DP problem,\nsince you mentioned that the order of coins mattered.\nI may show you another solution of O(n) DP using an array destructively.</p>\n\n<pre><code>(defn solve\n [n coins]\n (let [dp (doto (long-array (inc n))\n (aset 0 1))]\n (loop [i 0]\n (if (< i n)\n (do\n (doseq [c coins]\n (let [j (+ i c)]\n (if (<= j n)\n (aset dp j (+ (aget dp i)\n (aget dp j))))))\n (recur (inc i)))\n (aget dp n)))))\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>user> (solve 1 [1 2 5 10])\n1\nuser> (solve 2 [1 2 5 10])\n2\nuser> (solve 5 [1 2 5 10])\n9\nuser> (solve 82 [1 2 5 10])\n7637778505022614185\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T16:10:59.533",
"Id": "28874",
"Score": "0",
"body": "I didn't use `PersistentQueue` because I wanted random access for my algorithm. I also didn't want to use more space than strictly necessary (this might be an unnecessary concern, since it takes pretty long with a million elements anyways), so I create a smaller vector than you do. I don't know what a \"dp\" is or how your solution is different from mine though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T11:10:36.263",
"Id": "18113",
"ParentId": "17973",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "18003",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T17:50:42.387",
"Id": "17973",
"Score": "6",
"Tags": [
"algorithm",
"clojure"
],
"Title": "Counting ways to form an amount using coins"
}
|
17973
|
<pre><code>var ContentEditingHelper;
$(ContentEditingHelper = function () {
var costCenterSelector = '#CostCenter';
var projectSubcodeSelector = '#ProjectSubcode';
var incidentNumberSelector = '#IncidentNumber';
//This bit of code affects the 'Add New Order' dialog. It works on the 'Incident Number', 'Project Subcode', and 'Cost Center' input fields.
//Since only one of these fields is allowed to be populated at a time -- use jQuery to disable the other fields when typing is detected in one.
$(this).on('keyup', '#CostCenter, #ProjectSubcode, #IncidentNumber', function () {
if ($(this).val() === '') {
$(costCenterSelector).prop('disabled', false);
$(projectSubcodeSelector).prop('disabled', false);
$(incidentNumberSelector).prop('disabled', false);
}
else {
switch (this.id) {
case 'CostCenter':
$(projectSubcodeSelector).prop('disabled', true);
$(incidentNumberSelector).prop('disabled', true);
break;
case 'ProjectSubcode':
$(costCenterSelector).prop('disabled', true);
$(incidentNumberSelector).prop('disabled', true);
break;
case 'IncidentNumber':
$(costCenterSelector).prop('disabled', true);
$(projectSubcodeSelector).prop('disabled', true);
break;
}
}
});
//Public methods go here.
return {
};
} ());
</code></pre>
<p>So I've got this and it works. There are some clear code smells and some not-so-clear. I would like to be able to be able to reuse my selector names as much as possible. Is it possible to use them in my declaration of on? And how should I handle my case statements?</p>
<p>Furthermore, is there an overall easier way to achieve my goal?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:41:32.933",
"Id": "28622",
"Score": "0",
"body": "I *really* don't understand the `var ContentEditingHelper; $(ContentEditingHelper = function () {` purpose. `var ContentEditingHelper = function () { ... }; $(ContentEditingHelper);` OR `function ContentEditingHelper () { ... }; $(ContentEditingHelper);` will do *almost* the same thing, but neater."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:46:43.023",
"Id": "28623",
"Score": "0",
"body": "It's hard to tell exactly what you mean from code in a comment, but my intention was to expose a ContentEditingHelper object globally (I intend for it to have public methods in the future) while not leaking private code outside of its scope. Feel free to post a pastebin/gist of what you're describing and we can discuss."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:51:45.297",
"Id": "28624",
"Score": "0",
"body": "Ok to do that simple, in your code: You declare `ContentEditingHelper` globally, you auto-execute a function, you assign the undefined result to `ContentEditingHelper` and then you pass that to the fancy \"jQuery documentReady\"... it's like doing `var ContentEditingHelper = (function() { }()); $(document).ready(undefined)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:57:59.127",
"Id": "28625",
"Score": "0",
"body": "Won't that execute the anonymous function before document ready, though? The code I currently have assigns to ContentEditingHelper after document ready."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:25:22.990",
"Id": "28638",
"Score": "0",
"body": "Your function is executed before the dom is ready because you tell it to. Look at what is between `$()` -» `ContentEditingHelper = function() { ... }()` so it execute itself, and THEN it is passed to `$()`. What you putted in `$()`is an expression. It will execute the expression, and then pass the result of this expression to `$()`"
}
] |
[
{
"body": "<pre><code>var $inputs = $('#CostCenter, #ProjectSubcode, #IncidentNumber');\n\n$inputs.on('keyup', function() {\n $inputs.not(this).prop('disabled', this.value !== '');\n});\n</code></pre>\n\n<hr>\n\n<p>If your elements are not available at document ready, use this:</p>\n\n<pre><code>var selector = '#CostCenter, #ProjectSubcode, #IncidentNumber';\n\n$(document).on('keyup', selector, function() {\n $(selector).not(this).prop('disabled', this.value !== '');\n});\n</code></pre>\n\n<p>Just keep in mind that this will query the DOM on <em>every single <code>keyup</code></em>!! Are you sure you can't somehow do this differently?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:06:36.047",
"Id": "28626",
"Score": "0",
"body": "This works slightly differently than my code. The inputs do not exist at the time the code is ran. Your code will only bind to elements which already exist in the DOM tree, but I do see where you are going with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:08:36.157",
"Id": "28627",
"Score": "0",
"body": "@SeanAnderson - Just added a code snippet for that too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:09:47.947",
"Id": "28628",
"Score": "0",
"body": "Thanks. That helped. jQuery is better at working with collections of selectors than I thought :o"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:11:08.310",
"Id": "28629",
"Score": "0",
"body": "The `not(this)` won't work, since it refers to `document`. Use `$(e.target)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:12:17.447",
"Id": "28630",
"Score": "0",
"body": "Huh? It works fine. this changes scope inside of the function to reference the element firing the keyup event."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:12:54.593",
"Id": "28631",
"Score": "0",
"body": "I meant in the second solution when he uses `$(document).on`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:13:09.207",
"Id": "28632",
"Score": "0",
"body": "@FlorianMargaine - [Why would you say that](http://jsfiddle.net/BzYzL/)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:13:40.630",
"Id": "28633",
"Score": "0",
"body": "Oh, my. jQuery does way too much magic for me to remember everything. My bad!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:17:31.983",
"Id": "28635",
"Score": "0",
"body": "I'm not crazy, jQuery does the magic: http://jsfiddle.net/55fvA/2/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:19:11.097",
"Id": "28636",
"Score": "0",
"body": "@FlorianMargaine - That's just event bubbling. jQuery is doing event delegation..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T02:23:25.583",
"Id": "28726",
"Score": "0",
"body": "A user can also change an input's value with the context menu and drag-and-drop, neither of which fire `keyup`. `input` catches everything (and, as a bonus, doesn't fire for non-changing keystrokes like arrow keys), but isn't compatible with IE<9."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:02:32.620",
"Id": "17975",
"ParentId": "17974",
"Score": "1"
}
},
{
"body": "<pre><code>var ContentEditingHelper = {};\n\n// Apply the right class there.\n$(document).on('keyup', '.inputs', function (e) {\n\n // First, disable all the fields.\n $('.inputs').prop('disabled', true);\n\n // Then, enable the one that was clicked.\n $(e.target).prop('disabled', false);\n});\n</code></pre>\n\n<p>Also, there is no need to declare this in your <code>ContentEditingHelper</code>. I didn't surround the jQuery code by an IIFE because there is no variable declared, but you could just use this if necessary:</p>\n\n<pre><code>(function() {\n $(document).on...\n}());\n</code></pre>\n\n<p>Only put in the <code>ContentEditingHelper</code> object what's needed. This is commonly called a namespace by the way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T19:09:41.963",
"Id": "17976",
"ParentId": "17974",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "17975",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T18:23:09.593",
"Id": "17974",
"Score": "-1",
"Tags": [
"javascript",
"jquery"
],
"Title": "I have three input fields. When one has any information in it, the others should be disabled. Can I express this more succinctly?"
}
|
17974
|
<p>I have created an SslStream Abstract Class for my Client and i want you to review and enhance it for me if needed</p>
<p>SecureStream.cs</p>
<pre><code>using System;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Program.Connections.Packets;
using Program.Core.Misc;
namespace Program.Connections.Network
{
public abstract class SecureStream
{
private static readonly byte[] Buffer = new byte[0x1f80];
private const string IpAddress = "192.168.1.65";
private readonly int _port;
private readonly Socket _socket;
private SslStream _sslStream;
public abstract void Receive(byte[] buffer);
public abstract void Error(Exception e);
protected SecureStream(int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
_port = port;
}
public void Connect()
{
_socket.BeginConnect(new IPEndPoint(IPAddress.Parse(IpAddress), _port), Authenticate, null);
}
private async void Authenticate(IAsyncResult ar)
{
try
{
var onCertificateValidationCallBack =
new RemoteCertificateValidationCallback(
OnCertificateValidation);
_sslStream = new SslStream(new NetworkStream(_socket, true), false, onCertificateValidationCallBack);
await _sslStream.AuthenticateAsClientAsync(IpAddress);
if (!_sslStream.IsAuthenticated) throw new Exception("not^authenticated");
do
{
var size = await _sslStream.ReadAsync(Buffer, 0, Buffer.Length);
if (size == 0) throw new Exception("invalid^size");
var buffer = new byte[size];
Native.MemoryCopy(Buffer, buffer, (uint)buffer.Length);
Receive(buffer);
Array.Clear(Buffer, 0, Buffer.Length);
} while (_sslStream.CanRead);
}
catch (Exception e)
{
Error(e);
}
}
internal async Task Send(PacketWriter writer)
{
var buffer = writer.GetWorkspace();
await _sslStream.WriteAsync(buffer, 0, buffer.Length);
}
private static bool OnCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
{
return true;
}
}
}
</code></pre>
<p>CoreServer.cs</p>
<pre><code>using System;
using System.Windows.Forms;
namespace Program.Connections.Network
{
public sealed class CoreServer : SecureStream
{
public CoreServer(int p) : base(p) { }
public override void Receive(byte[] buffer)
{
//TODO: Handle The Buffer
}
public override void Error(Exception e)
{
//TODO: Add Error Writer.
MessageBox.Show(
string.Format("Disconnected from the server."),
string.Format("Connection Error"), MessageBoxButtons.OK,
MessageBoxIcon.Error);
Environment.Exit(1);
}
}
}
</code></pre>
<p>And i Simply Execute it using </p>
<pre><code>var coreServer = new CoreServer(/*port*/);
coreServer.Connect();
</code></pre>
|
[] |
[
{
"body": "<pre><code>new byte[0x1f80]\n</code></pre>\n\n<p>I think using decimal would be more readable here. And I don't understand why is your buffer 8096 bytes, usual sizes are powers of two, like 8192.</p>\n\n<pre><code>IpAddress = \"192.168.1.65\"\n</code></pre>\n\n<p>This looks like a perfect example of something that should be configurable, not set in stone. You should accept the IP address in the constructor, like you already do with port number.</p>\n\n<pre><code>public abstract void Receive(byte[] buffer);\npublic abstract void Error(Exception e);\n</code></pre>\n\n<p>I'm not sure I like the use of inheritance here. I think using events, or something like that would make more sense here.</p>\n\n<pre><code>_socket.BeginConnect(…)\n</code></pre>\n\n<p>I don't like that you're using the old Asynchronous Programming Model when you could (and do in other parts of your code) use <code>async</code>-<code>await</code>. Unfortunately, <code>Socket</code> doesn't expose <code>await</code>able methods, but <a href=\"http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx\" rel=\"nofollow\">there are ways around that</a>.</p>\n\n<pre><code>private async void Authenticate(IAsyncResult ar)\n</code></pre>\n\n<p>I think <code>Authenticate</code> is not a very good name for this method, it does much more than just authentication.</p>\n\n<pre><code>throw new Exception(\"not^authenticated\")\n</code></pre>\n\n<p>You shouldn't throw <code>Exception</code>, you should instead create a custom class that derives from <code>Exception</code> and use that. And the exception message should be human-readable, not some error code like it seems in your case. If you need to differentiate different errors, either have different exception types for them, or add a property for that to your custom exception.</p>\n\n<pre><code>if (size == 0) throw new Exception(\"invalid^size\");\n</code></pre>\n\n<p>When <code>ReadAsync()</code> returns 0, it's not invalid size, it means the end of the stream was reached, so you should act accordingly.</p>\n\n<pre><code>Native.MemoryCopy(Buffer, buffer, (uint)buffer.Length);\n</code></pre>\n\n<p>Why are using some custom memory copying method here? Do you have some reason for not using <a href=\"http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx\" rel=\"nofollow\"><code>Buffer.BlockCopy()</code></a>? Also, why are you even doing the copying here? It seems you class is intended only for limited use (since you have a constant IP address), so couldn't you make sure the buffer isn't used after <code>Receive()</code> returns, so you didn't have to copy at all?</p>\n\n<pre><code>return true;\n</code></pre>\n\n<p>I'm no expert on security, but I think you should perform at least some checks of the certificate here. Otherwise, your class isn't really a “secure stream”.</p>\n\n<pre><code>MessageBox.Show(…);\n</code></pre>\n\n<p>You shouldn't mix code like this with GUI code, they should be separated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T20:04:15.737",
"Id": "28696",
"Score": "0",
"body": "i am throwing an exception on reading 0 because it means that it is disconnected. Also i am using MemoryCopy because it is much faster than regular BlockCopy"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-13T15:33:59.977",
"Id": "293750",
"Score": "0",
"body": "Instead of always returning `true` from `OnCertificateValidation` it's better to return `sslpolicyerrors == SslPolicyErrors.None`. Example here: https://msdn.microsoft.com/en-us/library/system.net.security.remotecertificatevalidationcallback(v=vs.110).aspx"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T19:53:51.530",
"Id": "18000",
"ParentId": "17978",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18000",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:01:30.180",
"Id": "17978",
"Score": "10",
"Tags": [
"c#"
],
"Title": "SslStream Class Review"
}
|
17978
|
<p>I am working on a Java project for college that involves us setting up a TCP Server and Client. I have that part working and now to add more of a feel to my project I want to add a GUI.</p>
<p>We have not begun learning about GUI's in Java yet. However I want to try as I think it would be a useful exercise. I have a very basic GUI set up and the appropriate ActionListener set for the button. My next problem is positioning my panels so they look neat and tidy on the Frame...</p>
<p>At the moment I have all the components in one panel as seen below:</p>
<pre><code>public ClientGUI(){
//Initialise Frame
frame = new JFrame("TCP Client");
//Initialise Panel 1 & Components
p1 = new JPanel();
//Set Layout
p1.setLayout(new GridLayout(1,2));
//Label 1 - For TextArea
l1 = new JLabel("Chat Log");
p1.add(l1);
//TextArea - To display conversation
t1 = new JTextArea(10,10);
p1.add(t1);
//Label 2 - For TextField
l2 = new JLabel("Message");
p1.add(l2);
//Message Box - For user input
t2 = new JTextField(10);
p1.add(t2);
//Button 1 - To send message
b1 = new JButton("Send");
p1.add(b1);
//Add panels to frame
frame.add(p1);
//Frame properties...
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
//Add Event listener to button
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
//do something
t1.setText(t2.getText());
}
});
</code></pre>
<p>I have a wireframe drawn up of what I'd like it to look like but unfortunately I cannot upload as my reputation is not high enough. Basically something like this...</p>
<p>Label on top of a TextArea.
Label and TextField below.
Button below.</p>
<p>I'd appreciate any feedback anyone might have! Thanks very much.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:50:19.940",
"Id": "73063",
"Score": "0",
"body": "This question appears to be off-topic because it is primarily a design review."
}
] |
[
{
"body": "<p>What you want is called the <strong>BoxLayout</strong>, which feeds UI elements in columns or rows. And then you can nest them one inside another, e.g. have one horizontal box layout panel as an element in another that is vertical (kind of like nested HTML tables). <a href=\"http://zetcode.com/tutorials/javaswingtutorial/swinglayoutmanagement/\" rel=\"nofollow\">Here</a> is a pretty decent tutorial about layout managers and it includes the BoxLayout.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:46:01.107",
"Id": "17981",
"ParentId": "17980",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "17981",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:42:46.660",
"Id": "17980",
"Score": "1",
"Tags": [
"java",
"swing",
"layout"
],
"Title": "Java Swing Panel layout"
}
|
17980
|
<p>This isn't urgent, it is more along the lines of trivia or a challenge. The solution works fine as it is, but I suspect it could be better.</p>
<p>What follows is a method I came up with a while back in a rather ugly situation where I need to make a "best effort" to try casting an object of an unrestricted unknown type TO an unrestricted unknown type. The code has just been bugging me. It seems that there should be a more elegant way to do this, but I wanted to get that "Best Effort" part right.</p>
<p>The methods follows the "Try" convention. It accepts an object "value" and an out param of type T, "result." It attempts to cast value into result as type T. If it succeeds, it returns true. If it cannot, it sets result = default(T) and returns false.</p>
<p>It feels like I'm going to lots of trouble in the method. I'd be open to suggestions to streamline this a bit. Comments included here are mostly not in the original... just to explain why a few things were done the way they were done.</p>
<pre><code>/// <summary>
/// Tries to cast <paramref name="value" /> to an instance of type <typeparamref name="T" /> .
/// </summary>
/// <typeparam name="T"> The type of the instance to return. </typeparam>
/// <param name="value"> The value to cast. </param>
/// <param name="result"> When this method returns true, contains <paramref name="value" /> cast as an instance of <typeparamref
/// name="T" /> . When the method returns false, contains default(T). </param>
/// <returns> True if <paramref name="value" /> is an instance of type <typeparamref name="T" /> ; otherwise, false. </returns>
public static bool TryCast<T>(this object value, out T result)
{
var destinationType = typeof(T);
var inputIsNull = (value == null || value == DBNull.Value);
/*
* If the given value is null, we'd normally set result to null and be done with it.
* HOWEVER, if T is not a nullable type, then we can't REALLY cast null to that type, so
* TryCast should return false.
*/
if (inputIsNull)
{
// If T is nullable, this will result in a null value in result.
// Otherwise this will result in a default instance in result.
result = default(T);
// If the input is null and T is nullable, we report success. Otherwise we report failure.
return destinationType.IsNullable();
}
// Convert.ChangeType fails when the destination type is nullable. If T is nullable we use the underlying type.
var underlyingType = Nullable.GetUnderlyingType(destinationType) ?? destinationType;
try
{
/*
* At the moment I cannot remember why I handled Guid as a separate case, but
* I must have been having problems with it at the time or I'd not have bothered.
*/
if (underlyingType == typeof(Guid))
{
if (value is string)
{
value = new Guid(value as string);
}
if (value is byte[])
{
value = new Guid(value as byte[]);
}
result = (T)Convert.ChangeType(value, underlyingType);
return true;
}
result = (T)Convert.ChangeType(value, underlyingType);
return true;
}
catch (Exception ex)
{
// This was originally used to help me figure out why some types weren't casting in Convert.ChangeType.
// It could be removed, but you never know, somebody might comment on a better way to do THAT to.
var traceMessage = ex is InvalidCastException || ex is FormatException || ex is OverflowException
? string.Format("The given value {0} could not be cast as Type {1}.", value, underlyingType.FullName)
: ex.Message;
Trace.WriteLine(traceMessage);
result = default(T);
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T20:01:04.657",
"Id": "28695",
"Score": "3",
"body": "If you think some of the things in your code need explaining, why didn't you include those comments in your original code? If you expect that we would be confused by your code, why do you think your coworkers wouldn't?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-17T18:44:31.427",
"Id": "122207",
"Score": "0",
"body": "Just for comparison, check out the general conversion extensions that I wrote. We have tests for these and it seems to work very well: http://goo.gl/CoE8Xx There's no `Try` version because we have a generalized Attempt mechanism: http://goo.gl/DfWwYe"
}
] |
[
{
"body": "<p>For casting, I have a much simpler method in mind:</p>\n\n<pre><code>public static bool TryCast<T>(this object obj, out T result)\n{\n if (obj is T)\n {\n result = (T)obj;\n return true;\n }\n\n result = default(T);\n return false;\n}\n</code></pre>\n\n<p>You don't need to detect <code>nullable</code> types manually since <code>is</code> operator already checks for it: <code>5 is int?</code> returns true, so the following code writes <code>5</code> to the console.</p>\n\n<pre><code>int value = 5;\nint? result;\nif (value.TryCast(out result))\n Console.WriteLine(result);\n</code></pre>\n\n<p>The following writes nothing because <code>TryCast</code> returns false.</p>\n\n<pre><code>string value = \"5\";\nint? test;\nif (value.TryCast(out test))\n Console.WriteLine(test);\n</code></pre>\n\n<p>Lastly, the following should write two lines that are \"test 1\" and \"test 2\".</p>\n\n<pre><code>var list = new List<string>();\nlist.Add(\"test 1\");\nlist.Add(\"test 2\");\n\nIEnumerable<string> enumerable;\nif (list.TryCast(out enumerable))\n foreach (var item in enumerable)\n Console.WriteLine(item);\n</code></pre>\n\n<p>I'm really against this approach:</p>\n\n<pre><code>if (underlyingType == typeof(Guid))\n{\n if (value is string)\n {\n value = new Guid(value as string);\n }\n else if (value is byte[])\n {\n value = new Guid(value as byte[]);\n }\n\n //...\n</code></pre>\n\n<p>If you want this kind of custom conversion features, my suggestion would be to keep your converters in a static, thread-safe <code>Converter</code> collection. A sample converter class can be like this:</p>\n\n<pre><code>public abstract class Converter\n{\n private readonly Type from; // Type of the instance to convert.\n private readonly Type to; // Type that the instance will be converted to.\n\n // Internal, because we'll provide the only implementation...\n // ...that's also why we don't check if the arguments are null.\n internal Converter(Type from, Type to)\n {\n this.from = from;\n this.to = to;\n }\n\n public Type From { get { return this.from; } }\n public Type To { get { return this.to; } }\n\n public abstract object Convert(object obj);\n}\n</code></pre>\n\n<p>And the implementation is:</p>\n\n<pre><code>// Sealed, because this is meant to be the only implementation.\npublic sealed class Converter<TFrom, TTo> : Converter\n{\n Func<TFrom, TTo> converter; // Converter is strongly typed.\n\n public Converter(Func<TFrom, TTo> converter)\n : base(typeof(TFrom), typeof(TTo)) // Can't send null types to the base.\n {\n if (converter == null)\n throw new ArgumentNullException(\"converter\", \"Converter must not be null.\");\n\n this.converter = converter;\n }\n\n public override object Convert(object obj)\n {\n if (!(obj is TFrom))\n {\n var msg = string.Format(\"Object is not of the type {0}.\", this.From.FullName);\n throw new ArgumentException(msg, \"obj\");\n }\n\n // Can throw exception, it's ok.\n return this.converter.Invoke((TFrom)obj);\n }\n}\n</code></pre>\n\n<p>To initialize it:</p>\n\n<pre><code>var int32ToString = new Converter<int, string>(i => i.ToString());\nvar stringToInt32 = new Converter<string, int>(s => int.Parse(s));\n\n// Converters should be a thread-safe collection of our abstract `Converter` type.\nConverters.Add(int32ToString);\nConverters.Add(stringToInt32);\n</code></pre>\n\n<p>With support for the custom converters, the final <code>TryCast</code> method becomes this:</p>\n\n<pre><code>public static bool TryCast<T>(this object obj, out T result)\n{\n if (obj is T)\n {\n result = (T)obj;\n return true;\n }\n\n // If it's null, we can't get the type.\n if (obj != null)\n {\n var converter = Converters.FirstOrDefault(c =>\n c.From == obj.GetType() && c.To == typeof(T));\n\n // Use the converter if there is one.\n if (converter != null)\n try\n {\n result = (T)converter.Convert(obj);\n return true;\n }\n catch (Exception)\n {\n // Ignore - \"Try*\" methods don't throw exceptions.\n }\n }\n\n result = default(T);\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-25T18:16:33.517",
"Id": "219348",
"Score": "0",
"body": "You can use the \"as\" keyword to simplify your `TryCast<T>` implementation to just two lines. `bool TryCast<T>(this object obj, out T result) { result = obj as T; return result != default(T); }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-28T09:46:12.733",
"Id": "219868",
"Score": "4",
"body": "@user2023861 you can't use `as` unless `where T : class` if I remember correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-15T09:42:59.140",
"Id": "378610",
"Score": "0",
"body": "@user2023861 additionally, result being equal to default value is not a reliable indication, that cast has failed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T10:18:17.610",
"Id": "18036",
"ParentId": "17982",
"Score": "29"
}
},
{
"body": "<p>There are built-in converters in <code>System.ComponentModel.TypeDescriptor</code> namespace (System.dll). You don't have to write your own array and you have access to a bunch of pre-existing converters as well.</p>\n\n<p>This is a modified version to account for this:</p>\n\n<pre><code>public static bool TryCast<T>(object obj, out T result)\n{\n result = default(T);\n if (obj is T)\n {\n result = (T)obj;\n return true;\n }\n\n // If it's null, we can't get the type.\n if (obj != null)\n {\n var converter = TypeDescriptor.GetConverter(typeof (T));\n if(converter.CanConvertFrom(obj.GetType()))\n result = (T) converter.ConvertFrom(obj);\n else\n return false;\n\n return true;\n }\n\n //Be permissive if the object was null and the target is a ref-type\n return !typeof(T).IsValueType; \n}\n</code></pre>\n\n<p>(of course the permissiveness depends on how you plan yo use it, I rather not have a try around the conversion, since I check for it)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-25T17:10:07.027",
"Id": "219331",
"Score": "3",
"body": "Welcome to Code Review! This looks like a valuable answer! Even if your advice was just *\"There are build in converters in System.ComponentModel.TypeDescriptor namespace (System.dll), you dont have to write your own array and you have access to a bunch of pre-existing converters as well.\"* then that would be a valuable review. Even small pieces of feedback are worth posting as reviews."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-12T10:45:52.833",
"Id": "315157",
"Score": "0",
"body": "I believe your `TryCast` method will sometimes throw exceptions. I think an exception will be thrown not for going to `Byte` from `(Int32)1` or `(Int32)999` or `(String)\"1\"` but will for `(String)\"999\"`. I don't know if this is a problem for anyone, but perhaps that specific case could be avoided?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-13T17:53:32.523",
"Id": "315388",
"Score": "0",
"body": "@captainjamie You mean something like TryCast<Byte>(\"999\", out b) ?\n\nperhaps the usage of get converter can be improved, feel free to update my question or add the right try-catch\n\n\nAlso it's worth noting that you can check converters both ways:\n`TypeConverter targetConverter = TypeDescriptor.GetConverter(typeof(T));\n TypeConverter sourceConverter = TypeDescriptor.GetConverter(obj.GetType());`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-14T10:39:02.753",
"Id": "315469",
"Score": "0",
"body": "@GettnDer `TryCast<Byte>(\"999\", out b)` is exactly what I mean. And the correct try-catch would be `catch(Exception)` because the converter throws the base class. It's a difficult problem to fix, there seems to be no good solution."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-25T17:03:14.297",
"Id": "117863",
"ParentId": "17982",
"Score": "9"
}
},
{
"body": "<p>I used GettnDer's answer and updated it to make use of the c# 8 language features eliminating some of the need for casting as well as show how one can enable "123" to be parsed and test for type, same goes for IP addresses etc, lots of things support parsing. I have an interface that denotes something implements IParse so I test if</p>\n<pre><code>if(T is IParse parse)\n{\n return parse.TryParse<T>(obj.ToString(),out result );\n}\n</code></pre>\n<p>There are lots of "helpers" you can think of...\nThe tryCast method that I think solves the question and most comments using the new features efficiently could be like:</p>\n<pre><code>public static bool TryCast<T>(object obj, out T result)\n{\n //will cover 99%\n if (obj is T value)\n {\n result = value;\n return true;\n }\n\n // will cover most plausible data type\n if (obj is not null)\n {\n var str = obj.ToString();\n switch (true)\n {\n case var _ when typeof(T) == typeof(string):\n result = (T)obj;\n return true;\n case var _ when typeof(T) == typeof(int) && int.TryParse(str, out var aValue):\n result = (T)(object)aValue;\n return true;\n case var _ when typeof(T) == typeof(long) && long.TryParse(str, out var aValue):\n result = (T)(object)aValue;\n return true;\n case var _ when typeof(T) == typeof(DateTime) && DateTime.TryParse(str, out var aValue):\n result = (T)(object)aValue;\n return true;\n case var _ when typeof(T) == typeof(byte) && byte.TryParse(str, out var aValue):\n result = (T)(object)aValue;\n return true;\n case var _ when typeof(T) == typeof(short) && short.TryParse(str, out var aValue):\n result = (T)(object)aValue;\n return true;\n }\n\n }\n</code></pre>\n<p>This will work in all frameworks that support c# 8 so .net core 3.1 Net 5.0 and .net standard 2.1</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T08:20:47.377",
"Id": "253888",
"ParentId": "17982",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "18036",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T23:09:53.730",
"Id": "17982",
"Score": "29",
"Tags": [
"c#",
"casting"
],
"Title": "TryCast<T> method"
}
|
17982
|
<p>It might be a bit redundant, and I'm not experienced enough to wrap it all into one function. But,
I'm aiming for unicode email adresses and a quick loose but secure validation. How can I improve this?</p>
<p>note: I'm using PDO, so I'm mainly focusing on preventing HTML injection. Is this an issue ether way if I'm outputting user input in htmlspecialchars?</p>
<pre><code>$email = "<strong>Bàt mâ'n</strong>@çupærman.dc";
function isValid($email) {
return !preg_match('/[^ ]+@[^ ]+\.[^ ]{2,7}/', $email);
}
$encoded_email = htmlspecialchars($email, ENT_COMPAT, 'UTF-8');
if (isValid($email)) {
echo $encoded_email. " is not valid!";
} else {
if ($encoded_email===$email) {
echo $encoded_email. " is valid!";
} else {
echo $encoded_email. " is not valid!";
}
}
</code></pre>
|
[] |
[
{
"body": "<p>How about this? </p>\n\n<pre><code>$email = \"<strong>Bàt mâ'n</strong>@çupærman.dc\";\n\nfunction validateEmail($email){\n $encoded_email = htmlspecialchars($email, ENT_COMPAT, 'UTF-8');\n $is_valid = !preg_match('/[^ ]+@[^ ]+\\.[^ ]{2,7}/', $email);\n\n if( $is_valid || $encoded_email === $email ) $end = \" is \";\n else $end = \" is not \";\n\n return $encoded_email . $end . \" valid.\";\n}\n</code></pre>\n\n<p>I absconded the preg_match() to return within the function INTO a variable - as it is less expensive than a function call within a function call (however, if you're doing more than just a preg_match() to validate, then revert it back to the isValid() function. </p>\n\n<p>I also reworked your if/else/if/else into an (if|if)/else statement - higher readability and saves you one else call. </p>\n\n<p>Also, I put your code into a function and made it return once, rather than echo three times. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T08:21:50.673",
"Id": "28728",
"Score": "0",
"body": "Superb! Tanks, I'm really new to all of this, and a graphics designer so it's not even my mindset. Helped out quite a bit. Naturally I've also implemented email validation by sending a confirmation link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T21:20:27.637",
"Id": "28779",
"Score": "0",
"body": "Also see AD7six's answer below, I completely forgot about the filter_var() func."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T22:32:54.917",
"Id": "18021",
"ParentId": "17986",
"Score": "1"
}
},
{
"body": "<h2>Use filters</h2>\n\n<p>You are a lot better off just using the built in <a href=\"http://php.net/manual/en/filter.examples.validation.php\" rel=\"nofollow noreferrer\">validation filters</a>:</p>\n\n<pre><code>$email_a = 'joe@example.com';\n$email_b = 'bogus';\n\nif (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {\n echo \"This (email_a) email address is considered valid.\";\n}\nif (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {\n echo \"This (email_b) email address is considered valid.\";\n}\n</code></pre>\n\n<h2>Handling International email addresses</h2>\n\n<p>International domain names are not really UTF-8 - they are <a href=\"http://en.wikipedia.org/wiki/Punycode\" rel=\"nofollow noreferrer\">punycode</a> encoded strings (ascii). A UTF-8 local name isn't considered valid by most servers - i.e.</p>\n\n<ul>\n<li>foo@çupærman.dc valid (after converting the domain to punycode)</li>\n<li>foo@xn--uprman-quaf.dc valid (this is the above puny code converted)</li>\n<li>çupærman@foo.dc INvalid</li>\n</ul>\n\n<p>if you just want to prevent injection - run the email address through striptags before processing; you could also follow <a href=\"https://stackoverflow.com/q/5219848/761202\">this advice</a> and use loose validation and simply send a mail to confirm the mail exists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T21:20:55.890",
"Id": "28780",
"Score": "0",
"body": "Completely forgot about filter_var(). Great point made, hopefully OP will see this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T22:17:01.333",
"Id": "28782",
"Score": "0",
"body": "I'll be going with this solution, and I'll be confirming the email as well to prevent impersonation and doing front end validation for better user experience. I actually looked into the filters before making this post but wasn't happy with the unicode handling on the first email part, but at this point it just make more sense to use it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T08:30:53.580",
"Id": "18030",
"ParentId": "17986",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18030",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T10:36:39.277",
"Id": "17986",
"Score": "2",
"Tags": [
"php"
],
"Title": "Is this PHP email validation comprehensive and complete?"
}
|
17986
|
<p>I wrote this code for reversing a doubly linked list containing words in each node, which <strong>works perfectly fine</strong>. My teacher says the algorithm is difficult to understand and the code as a whole could be made more efficient(reducing overhead and memory consumption).</p>
<ol>
<li>What changes can i make to the code/the reversing algorithm?</li>
<li>Also is there a way I could input the sentence without having to ask the number of words in advance?</li>
</ol>
<p>Here is the code:</p>
<pre><code>#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct NODE
{
char *item;
struct NODE *next;
struct NODE *prev;
}NODE;
void Insert(char data[],NODE **List)
{
NODE *temp,*last;
last=(*List);
temp=(NODE*)malloc(sizeof(NODE));
temp->item=(char*)malloc(strlen(data));
temp->item=data;
temp->next=NULL;
temp->prev=NULL;
if((*List)->item==NULL)
(*List)=temp;
else
{
while(last->next!=NULL)
last=last->next;
temp->prev=last;
last->next=temp;
last=temp;
}
}
void Reverse(NODE **List)
{
int flag1=0;
NODE *temp,*temp1,*last,*flag;
temp1=(NODE*)malloc(sizeof(NODE));
last=(*List);
while(last->next!=NULL)
last=last->next;
temp=last;
while(temp->prev!=NULL)
{
temp1->item=temp->item;
temp1->next=temp->next;
temp1->prev=temp->prev;
temp->next=temp->prev; //swap prev and next links
temp->prev=temp1->next;
temp=temp->next;
if(flag1==0) //record the last node which becomes the first node in new list
{
flag1++;
flag=temp;
}
}
temp1->item=temp->item;
temp1->next=temp->next;
temp1->prev=temp->prev;
temp->next=NULL;
temp->prev=temp1->next;
(*List)=flag->prev; //give control of the first node
free(temp1);
};
void display(NODE *List)
{
if(List->next==NULL)
{
printf("%s",List->item);
return;
}
NODE *temp;
temp=List;
do
{
printf("%s<-->",temp->item);
temp=temp->next;
}while(temp->next!=NULL);
printf("%s\n",temp->item);
}
int main()
{
int i=0,n;
char s[10][50];
NODE *List;
List=(NODE*)malloc(sizeof(NODE));
List->item=NULL;
List->next=NULL;
List->prev=NULL;
printf("Provide number of words(max 10): ");
scanf("%d",&n);
printf("Enter string of words for the list: ");
while(i<n)
{
scanf("%s",s[i]);
Insert(s[i],&List);
i++;
}
printf("\nOriginal List is: ");
display(List);
Reverse(&List);
printf("\nReversed List is: ");
display(List);
getch();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>For the part where you don't need to ask the user for the number of words perhaps ask the user to terminate it with a full stop and take the input until a '.' is encountered.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T13:34:29.613",
"Id": "17988",
"ParentId": "17987",
"Score": "3"
}
},
{
"body": "<p>Your code is fine overall, but there are a few things to notice:</p>\n\n<ol>\n<li><code>conio.h</code> is a properitary header that is not available on all systems. Avoid using it. There is a function similiar to <code>getch</code> available in the standard headers, where it is called <code>getchar</code>.</li>\n<li>Include <code>stdlib.h</code> for <code>malloc</code></li>\n<li>Don't append semicolons to the closing brace of a function definition (as in <code>Reverse</code>)</li>\n<li><p>Always turn on warnings when compiling. I compiled your code with the GNU C compiler (gcc) which gave me the following warnings:</p>\n\n<pre>\nreverse.c: In function 'main':\nreverse.c:88:10: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result [-Wunused-result]\nreverse.c:92:14: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result [-Wunused-result]\nreverse.c: In function 'Reverse':\nreverse.c:59:17: warning: 'flag' may be used uninitialized in this function [-Wuninitialized]\n</pre>\n\n<p>The first warning is about the fact that you don't check the return values of your calls to <code>scanf</code>. What happens if the user doesn't input a number? Better check for that case. The other warning is about your function <code>Reverse</code>. What happens if <code>temp->prev==0</code> from the beginning on? In that case, you while-loop is never executed and <code>flag</code> remains undefined, probably letting your program crash.</p>\n\n<p>Checking for such things is important to catch subtile errors. If the compiler issues a warning but you're sure that it's errorneous, making a comment is a good idea.</p></li>\n</ol>\n\n<p>To request only a certain amount of words, you could consider terminating the input with an empty line; when you encounter the sequence <code>\\n\\n</code>, terminate the input.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T13:35:30.560",
"Id": "17989",
"ParentId": "17987",
"Score": "2"
}
},
{
"body": "<p>Two minor changes will help reduce the amount of code you are writing and make it a little more efficient. This is how your code assumes the structure should be.</p>\n\n<pre><code>----------\n| Start |\n----------\n ||\n \\/\n---------- ----------- ---------- ----------\n| First | <==> | Second | <==> | Third | <==> | Last |\n---------- ----------- ---------- ----------\n</code></pre>\n\n<p>Instead you can do this, maintain a pointer to the last node and add a parameter to Reverse method that accepts what direction you want to traverse in.</p>\n\n<pre><code>---------- ----------\n| Start | | End |\n---------- ----------\n || ||\n \\/ \\/\n---------- ----------- ---------- ----------\n| First | <==> | Second | <==> | Third | <==> | Last |\n---------- ----------- ---------- ----------\n</code></pre>\n\n<p>So making these changes you will end up with a last node pointer that are set in your main and insert method.</p>\n\n<p>NODE *last;</p>\n\n<p>Now the reverse method should be fairly easy, just traversing in either direction based on the second parameter. If you teacher insists on this as not truly reversing the list you can use the last node to simplify the reverse logic you currently have. Also notice when you are inserting a new node you don't need to traverse all the way to the end.</p>\n\n<p>The rest of the code looks fine. You may want to pay attention to bounds checking, for example will the display code work for an empty list, a list with just one node. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T17:58:32.393",
"Id": "17995",
"ParentId": "17987",
"Score": "3"
}
},
{
"body": "<p>Your code has some issues from my perspective. The first that jumps out is that you are passing a pointer to a pointer to a list. This is one level of indirection too many. Just pass a pointer to the list. To make this easier, your list pointer in main() should just be a pointer to the first entry in the list; it should <strong>not be</strong> the first entry. In other words don't malloc space for a NODE in main().</p>\n\n<p>So when you construct the list it will look like this:</p>\n\n<pre><code> first _____\n |\n v\n ------- ------- ------- -------\n NULL <-- |p | <--- |p | <--- |p | <--- |p |\n | n| ---> | n| ---> | n| ---> | n| ---> NULL\n ------- ------- ------- -------\n</code></pre>\n\n<p>To reverse this list, you could take the approach given by @iaimtomisbehave, from earlier. But this has two notable points: It needs a <code>last</code> pointer to the end of the list (this might be a plus) as well as <code>first</code> (or start/end); if you just swap <code>last</code> and <code>first</code> then you haven't really reversed the list because to traverse the list you now have to follow the <code>prev</code> pointers instead of following the <code>next</code> pointers. But there is a simple solution: just swap the <code>prev</code> and <code>next</code> pointers of each node as well as swapping <code>first</code> and <code>last</code>.</p>\n\n<p>Some other points:</p>\n\n<ol>\n<li><p>Naming: upper case names are usually reserved for constants. So call NODE something else: eg. Node or node.</p></li>\n<li><p>malloc should not be cast</p></li>\n<li><p>you malloced the string and then didn't use it.(Insert() line 5/6))</p></li>\n<li><p>you have code to find the end of the list twice. It is a simple loop that belongs in a separate function.</p></li>\n<li><p>Add some space to make the code look less cramped. Note that <code>while</code>, <code>for</code>, <code>if</code> etc are special and deserve to be followed by an extra space: eg <code>while (condition)</code> (this is just my preference; others may disagree).</p></li>\n<li><p>One variable per line.</p></li>\n</ol>\n\n<p>That's enough I think :-) Here is my version of your program, for what it is worth.</p>\n\n<pre><code>#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\ntypedef struct Node\n{\n char *item;\n struct Node *next;\n struct Node *prev;\n} Node;\n\nstatic Node *last_node(Node *list)\n{\n while (list->next != NULL) {\n list = list->next;\n }\n return list;\n}\n\nstatic Node *insert(char *data, Node *list)\n{\n Node *node = malloc(sizeof(Node));\n /* should handle malloc/strdup failure... */\n node->item = strdup(data);\n node->next = NULL;\n\n if (list == NULL) {\n list = node;\n node->prev = NULL;\n }\n else {\n Node *last = last_node(list);\n node->prev=last;\n last->next=node;\n last = node;\n }\n return list;\n}\n\nstatic Node *reverse(Node *list)\n{\n Node *last = NULL;\n\n for (;list != NULL; list = list->prev) {\n Node *prev = list->prev;\n list->prev = list->next;\n list->next = prev;\n last = list;\n }\n return last;\n}\n\nstatic void display(const char *msg, Node *list)\n{\n printf(\"%s\\n\", msg);\n\n for (;list != NULL; list = list->next) {\n if (list->prev != NULL) {\n printf(\"<-->\");\n }\n printf(\"%s\", list->item);\n }\n printf(\"\\n\");\n}\n\nint main(int argc, char ** argv)\n{\n char s[50];\n Node *list = NULL;\n (void) argc;\n (void) argv;\n\n printf(\"Enter string of words for the list. \"\n \"End the list with a full-stop on a blank line: \");\n while ((scanf(\"%49s\", s) == 1) && strcmp(s, \".\")) {\n list = insert(s, list);\n }\n\n display(\"Original List is: \", list);\n list = reverse(list);\n display(\"Reversed List is: \", list);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T02:26:44.043",
"Id": "18006",
"ParentId": "17987",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "18006",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T12:57:20.690",
"Id": "17987",
"Score": "3",
"Tags": [
"c",
"linked-list"
],
"Title": "Simpler and faster code for reversing list?"
}
|
17987
|
<p>I am hoping someone can help me tidy up my code (for a practical for university). The practical is to use the random number generator to produce 100 integers (all between 1 and 10) and store them in an array. We then need to scan the array and print out how often each number appears. Following this, we needed to create a horizontal bar chart using asterisks to show how often each number appears, before finally printing out which number appeared the most.</p>
<p>My code works and produces the correct results:</p>
<pre><code>import java.util.Random;
public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random ();
int[] arrayOfGenerator = new int[100];
int[] countOfArray = new int[10];
int count;
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
{
count = numberGenerator.nextInt(10);
countOfArray[count]++;
arrayOfGenerator[countOfGenerator] = count + 1;
}
int countOfNumbersOnLine = 0;
for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
{
if (countOfNumbersOnLine == 10)
{
System.out.println("");
countOfNumbersOnLine = 0;
countOfOutput--;
}
else
{
if (arrayOfGenerator[countOfOutput] == 10)
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
else
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
}
}
System.out.println("");
System.out.println("");
// This section
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
System.out.println("The number " + (countOfNumbers + 1) + " occurs " + countOfArray[countOfNumbers] + " times.");
System.out.println("");
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
if (countOfNumbers != 9)
System.out.print((countOfNumbers + 1) + " ");
else
System.out.print((countOfNumbers + 1) + " ");
for (int a = 0; a < countOfArray[countOfNumbers]; a++)
{
System.out.print("*");
}
System.out.println("");
}
// To this section
System.out.println("");
int max = 0;
int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] > max)
{
max = countOfArray[counter];
test = counter + 1;
}
}
System.out.println("The number that appears the most is " + test);
}
}
</code></pre>
<p>However, I know that the section that tells how often a number occurs and the section that prints out the asterisks both start with the same for statement (I have marked them off in the code with comments). Can anyone advise me how I could do this using just one for statement? It seems quite straightforward, and yet I just can't get it to work!</p>
<p>Additionally, I am sure there are plenty of other areas that the code could be improved on. Feel free to suggest any improvements!</p>
|
[] |
[
{
"body": "<p>There is much to say about this piece of code. I'll just focus on some parts of it.</p>\n\n<p><strong>One long method</strong></p>\n\n<p>There is one long main method. It makes it hard to get an overview of what is happening. Consider breaking the main method into several methods that each does its piece. Something like.</p>\n\n<pre><code>public static void main(String...args){\n int[] randomNumbers = generateNumbers();\n String result = format(randomNumbers);\n result += formatNumberOfOccurences(randomNumbers);\n result += formatGraph(randomNumber);\n System.out.println(result);\n}\n\n// 4 methods omitted....\n</code></pre>\n\n<p>In this way you will get smaller chunks that is easier to understand. Each of these methods except the number generator is also easy to unit test since the outcome is the same for each argument. The code you have now is hard to unit test.</p>\n\n<p><strong>Printing with System.out</strong></p>\n\n<p>This is handy in many ways. But this is the main reason you need two loops for the code you have highlighted. Since you want to print the occurrence count first and then the graph you ned to do it in separate loops. If you instead store the intermediate result in a local variable then you can do it in one loop. Something like:</p>\n\n<pre><code>String occurrencesReport = \"\";\nString graph = \"\";\n\nfor (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)\n{\n occurrencesReport += \"The number \" + (countOfNumbers + 1) + \n \" occurs \" + countOfArray[countOfNumbers] + \" times.\";\n\n if (countOfNumbers != 9)\n graph += (countOfNumbers + 1) + \" \";\n else\n graph += (countOfNumbers + 1) + \" \";\n\n for (int a = 0; a < countOfArray[countOfNumbers]; a++)\n {\n graph += \"*\";\n }\n graph += \"\\n\";\n}\n\nSystem.out.println(occurrencesReport);\nSystem.out.println(graph);\n</code></pre>\n\n<p><strong>Readability example</strong></p>\n\n<p>This little piece:</p>\n\n<pre><code>if (countOfNumbers != 9)\n graph += (countOfNumbers + 1) + \" \";\nelse\n graph += (countOfNumbers + 1) + \" \";\n</code></pre>\n\n<p>can be simplified like so:</p>\n\n<pre><code>graph += (countOfNumbers + 1) + \" \";\nif (countOfNumbers != 9) graph += \" \";\n</code></pre>\n\n<p>this makes it easier to understand what is going on. (On a side note - most people dislike the absence of curly braces in this code snippet. If you add a statement yo your if-block it will actually be outside if curly braces are omitted. I tend to do ifs on one line when they are short. But people don't like that either....) This example can be applied to at least one more piece of the code where there is unnecessary repetition.</p>\n\n<p>Better stop now - just some bits and pieces I hope you can use to improve!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T21:37:06.993",
"Id": "28698",
"Score": "0",
"body": "I'll read through your comments and apply them to my code to try and tidy it up. Thanks very much for taking the time to go through it so thoroughly!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T17:53:15.177",
"Id": "28716",
"Score": "1",
"body": "@froderik, excellent answer, but consider that `printNumberOfOccurences` and `printGraph` don't actually print anything. What do you think of less misleading names (such as `formatNumberOfOccurrences` and `formatGraph`, or something along those lines)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T18:24:37.283",
"Id": "28717",
"Score": "0",
"body": "@codesparkle: Can I ask how you would set up methods with arrays in them? For example, the formatNumberOfOccurrences method I could create - what is the syntax to do so?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T19:35:16.090",
"Id": "28720",
"Score": "0",
"body": "@codesparkle: excellent naming suggestion. I am not sure about _format_ but it sure is better than _print_!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T19:39:20.873",
"Id": "28721",
"Score": "0",
"body": "@AndrewMartin: are you asking how a method that accepts an array looks like? \n`public String formatGraph(int[] array){ \n /* code here */ \n}`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T20:27:32.180",
"Id": "18001",
"ParentId": "17992",
"Score": "6"
}
},
{
"body": "<p>Andrew, welcome to Code Review. Froderik already suggested some excellent improvements. </p>\n\n<blockquote>\n <p><strong>Warning</strong><br>\n You're about to read a rather radical review. \n Proceed with caution (and, optionally, a cup of coffee). </p>\n</blockquote>\n\n<h1>An Architectural Perspective</h1>\n\n<h2>Red flags</h2>\n\n<p>The code is:</p>\n\n<ul>\n<li>within a single class: <code>Practical4_Assessed</code></li>\n<li>within a single method: <code>main</code></li>\n<li>deeply nested</li>\n<li>full of magic numbers</li>\n</ul>\n\n<p>These <em>code smells</em> indicate that <em>refactoring</em> is needed to achieve a more expressive result.</p>\n\n<h2>Single Responsibility Principle<sup><a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">1</a></sup> and Separation of Concerns<sup><a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">2</a></sup></h2>\n\n<p>A good way to start off is to count the number of responsibilities of your class <code>Practical4_Assessed</code>:</p>\n\n<ul>\n<li>Entry point of the program</li>\n<li>Generate random data</li>\n<li>Count occurrences of data</li>\n<li>Print a visualization of the data</li>\n</ul>\n\n<p>These responsibilities should be <em>separated</em> into one class per <em>concern</em>:</p>\n\n<ul>\n<li><code>Main</code>: entry point, instantiates objects and gets the system going</li>\n<li><code>RandomDataSource</code>: generates random data</li>\n<li><code>Counter</code>: counts the number of occurrences of the data </li>\n<li><code>CountPrinter</code>: prints the visualization</li>\n</ul>\n\n<p>But that's not enough: these classes have to be divided into sensibly-sized methods. Each one of those methods should <em>do one thing:</em> just a level of abstraction further down.</p>\n\n<h2>Code re-use</h2>\n\n<p>Counting some data is a rather common task. It's safe to say that you'll eventually need to count other things than <code>int</code>s. But you won't be able to, because your program only supports a single data type.</p>\n\n<p>In other words, your code is not reusable. This can be solved by using <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/types.html\" rel=\"nofollow noreferrer\"><em>generics</em></a>: defining a data structure that can deal with <em>any</em> type of data. </p>\n\n<hr>\n\n<h1>Refactoring</h1>\n\n<p>Let's start by thinking about how to best represent the concept of a source of random data.</p>\n\n<h2>Data sources</h2>\n\n<p>There will be different data sources for different types, but all will adhere to the same contract and all will require a source of randomness. To accommodate these requirements, an abstract, generic base class is needed:</p>\n\n<pre><code>public abstract class RandomDataSource<T> {\n\n protected static final Random random = new Random();\n\n public abstract T nextElement();\n\n public Iterable<T> nextElements(int numberOfElements) {\n Collection<T> elements = new ArrayList<>(numberOfElements);\n for (int i = 0; i < numberOfElements; i++) {\n elements.add(nextElement());\n }\n return elements;\n }\n}\n</code></pre>\n\n<p>Note that:</p>\n\n<ul>\n<li><p>the contract is <em>narrow</em>: there are only two methods, </p>\n\n<ul>\n<li><code>nextElement</code>, which is abstract and needs to be implemented by deriving classes;</li>\n<li><code>nextElements(int numberOfElements)</code>, which is a convenience method;</li>\n</ul></li>\n<li><p>the most general interface that is appropriate (<code>Iterable<T></code>) is returned in order to preserve flexibility and decouple the implementation from the interface.</p></li>\n</ul>\n\n<p>To generate the random numbers, create a subclass where <code>nextElement</code> is overridden to return a random Integer between the specified bounds:</p>\n\n<pre><code>public class RandomNumberSource extends RandomDataSource<Integer> {\n\n private final int elements;\n private final int offset;\n\n public RandomNumberSource(int lowerBound, int upperBound) {\n elements = upperBound - lowerBound + 1;\n offset = lowerBound;\n }\n\n @Override\n public Integer nextElement() {\n return random.nextInt(elements) + offset;\n }\n}\n</code></pre>\n\n<p>And to generate random names, a randomly chosen name chosen from an array of names is returned:</p>\n\n<pre><code>public class RandomNameSource extends RandomDataSource<String> {\n\n private final String[] names;\n\n public RandomNameSource(String... someNames) {\n names = someNames;\n }\n\n @Override\n public String nextElement() {\n return names[random.nextInt(names.length)];\n }\n}\n</code></pre>\n\n<p>If you need to count a different type of elements (maybe complex objects), you can now easily create another subclass to generate them.</p>\n\n<h2>Entry point</h2>\n\n<p>Your <code>main</code> method (in the class <code>Main</code>) is now rather short. It creates the data sources:</p>\n\n<pre><code>public static void main(String[] args) {\n String[] names = { \"Adam\", \"David\", \"Eve\", \"Frank\", \"John\" };\n visualize(new RandomNumberSource(1, 10), 100);\n visualize(new RandomNameSource(names), 50);\n}\n</code></pre>\n\n<p>Then, it creates a <code>Counter</code> to count them and fills that <code>Counter</code> with elements from the data source:</p>\n\n<pre><code>private static <T> void visualize(RandomDataSource<T> dataSource, int elementCount) {\n Counter<T> counter = new Counter<>();\n for (T element : dataSource.nextElements(elementCount)) {\n counter.increment(element);\n }\n print(counter);\n}\n</code></pre>\n\n<p>Finally, it prints the occurrences using a <code>CountPrinter</code>:</p>\n\n<pre><code>private static <T> void print(Counter<T> counter) {\n CountPrinter<T> printer = new CountPrinter<>(counter, System.out);\n printer.printOccurences();\n printer.printChart();\n printer.printLargest();\n}\n</code></pre>\n\n<p>Note that every class clearly has a single responsibility. Let's take a look at <code>Counter<T></code> first.</p>\n\n<h2>Counting occurrences</h2>\n\n<p>We are going to want to iterate over the results, so we'll make our counting class implement <code>Iterable</code>. It uses a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\"><code>Map</code></a> to store the elements and their counts as key-value-pairs. In this implementation, a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html\" rel=\"nofollow noreferrer\"><code>HashMap</code></a> is used; replace it with a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html\" rel=\"nofollow noreferrer\"><code>TreeMap</code></a> if you want to iterate in the natural ordering of <code>T</code>, or a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html\" rel=\"nofollow noreferrer\"><code>LinkedHashMap</code></a> if you want to preserve insertion order.</p>\n\n<p><code>increment</code> adds the specified element to the map if it doesn't yet exist; otherwise, it increments the count.</p>\n\n<p>One of the problems with your assignment is that <em>multiple elements can have the same count</em>, so <em>\"which number appeared the most\"</em> is undefined. Instead, you should return all the elements with the maximum count, as shown in <code>getLargestElements</code>.</p>\n\n<pre><code>public class Counter<T> implements Iterable<T> {\n\n private Map<T, Integer> map = new HashMap<>();\n\n public void increment(T element) {\n int count = map.containsKey(element) ? map.get(element) : 0;\n map.put(element, count + 1);\n }\n\n public int getCount(T element) {\n return map.get(element);\n }\n\n public Iterable<T> getLargestElements() {\n int largest = Collections.max(map.values());\n Collection<T> keys = new ArrayList<>();\n for (T key : map.keySet()) {\n if (map.get(key) == largest) {\n keys.add(key);\n }\n }\n return keys;\n }\n\n @Override\n public Iterator<T> iterator() {\n return map.keySet().iterator();\n }\n}\n</code></pre>\n\n<h2>Printing the results</h2>\n\n<p>The output code is isolated in a single class that takes a <code>Counter<T></code> and a <code>PrintStream</code>, for instance <code>System.out</code>, but it could just as well be a file or a socket stream. Instead of manually adding spaces to smooth out and align the numbers, you can <a href=\"https://stackoverflow.com/a/7602731/1106367\"><em>specify a minimum width</em></a> in Java format strings. For instance, <code>%5s</code> will pad the text to maintain a width of 5 spaces.</p>\n\n<p>To visualize the bars of the bar graph, simply use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#fill%28char%5B%5D,%20char%29\" rel=\"nofollow noreferrer\"><code>Arrays.fill</code></a> to create a bar of <code>*</code>. </p>\n\n<pre><code>public class CountPrinter<T> {\n\n private final Counter<T> counter;\n private final PrintStream out;\n\n public CountPrinter(Counter<T> source, PrintStream target) {\n counter = source;\n out = target;\n }\n\n public void printOccurences() {\n for (T entry : counter) {\n out.printf(\"%5s occurs %2s times.\\n\", entry, counter.getCount(entry));\n }\n }\n\n public void printChart() {\n for (T entry : counter) {\n char[] bar = new char[counter.getCount(entry)];\n Arrays.fill(bar, '*');\n out.printf(\"%5s: %s\\n\", entry, new String(bar));\n }\n }\n\n public void printLargest() {\n out.println(\"most occurrences:\");\n for (T element : counter.getLargestElements()) {\n out.println(element);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>Output</h1>\n\n<p><strong>Numbers:</strong></p>\n\n<pre>\n 1 occurs 7 times.\n 2 occurs 10 times.\n 3 occurs 16 times.\n 4 occurs 13 times.\n 5 occurs 10 times.\n 6 occurs 12 times.\n 7 occurs 9 times.\n 8 occurs 10 times.\n 9 occurs 6 times.\n 10 occurs 7 times.\n 1: *******\n 2: **********\n 3: ****************\n 4: *************\n 5: **********\n 6: ************\n 7: *********\n 8: **********\n 9: ******\n 10: *******\nmost occurrences:\n3\n</pre>\n\n<p><strong>Names:</strong></p>\n\n<pre>\nDavid occurs 5 times.\nFrank occurs 13 times.\n Adam occurs 13 times.\n John occurs 8 times.\n Eve occurs 11 times.\nDavid: *****\nFrank: *************\n Adam: *************\n John: ********\n Eve: ***********\nmost occurrences:\nFrank\nAdam\n</pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T16:14:07.893",
"Id": "28762",
"Score": "1",
"body": "I think 'wow' is appropriate. I'll work my way through all your suggestions and amend my work appropriately - but it'll take me quite a while! I'm not at all familiar with things like HashMap, TreeMap or Array Lists.\nThank you so much for taking the time to provide all of this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T16:26:54.760",
"Id": "28764",
"Score": "1",
"body": "Thank you for the kind words. You may find this [introduction to Java Collections](http://docs.oracle.com/javase/tutorial/collections/index.html) helpful. There's also a [Wikipedia article](http://en.wikipedia.org/wiki/Java_collections_framework) and an [extensive tutorial](http://www.javamex.com/tutorials/collections/) ([this page](http://www.javamex.com/tutorials/collections/how_to_choose.shtml) is the most helpful as an overview)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T17:38:40.980",
"Id": "30214",
"Score": "0",
"body": "I promised to write a comment, so here we go. I will keep it short for limited space.\nSoC is a good thing, but I would use it carefully, not force it. Sometime, it is harder to understand code if it is divided across all the places.\nUsing generics if you need only one case is not advised. Do not code for undefined future usage.\nI would keep the Random private & provide getter. Or do not provide it at all, because implementation is done in the subclass.\nThe countPrinter approach looks rather fine.\nOverall, from my view it is a nice and clean approach."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:54:47.977",
"Id": "18051",
"ParentId": "17992",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "18001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T14:31:37.160",
"Id": "17992",
"Score": "8",
"Tags": [
"java",
"random"
],
"Title": "Tidy up number counting code"
}
|
17992
|
<p>I am using the Python module <code>urllib3</code>. It occurs to me that there is a better way to design a good class when I rebuild my last site crawler.</p>
<pre><code>class Global:
host = 'http://xxx.org/'
proxy=True
proxyHost='http://127.0.0.1:8087/'
opts=AttrDict(
method='GET',
headers={'Host':'xxxx.org',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'en-us;q=0.5,en;q=0.3',
'Accept-Encoding':'gzip, deflate',
'Connection':'keep-alive',
'Cookie':'xxxxxxx',
'Cache-Control':'max-age=0'
},
assert_same_host=False
)
def getPool(self,proxy=None):
if proxy is None:
proxy = self.proxy
if(self.proxy):
http_pool = urllib3.proxy_from_url(self.proxyHost)
else:
http_pool = urllib3.connection_from_url(self.host)
return http_pool
class Conn:
def __init__(self, proxy):
self.proxy= proxy
self.pool = Global().getPool(self.proxy)
def swith(self):
self.pool = Global().getPool(not self.proxy)
def get(url, opts=Global.opts):
try:
self.pool.urlopen(
method=opts.method,
url= url,
headers= opts.headers,
assert_same_host=opts.assert_same_host
)
except TimeoutError, e:
print()
except MaxRetryError, e:
# ..
</code></pre>
<p>I try to make class contains all global configs and data for others to call,
just like I do in JavaScript. But, are these classes too tightly coupled? Should I just merge them together?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T05:28:23.103",
"Id": "28686",
"Score": "0",
"body": "I think that those two are really parts of the same class. And should be combined."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T05:32:31.560",
"Id": "28687",
"Score": "0",
"body": "Does anyone need access to this stuff besides `Conn`? If not, it probably belongs in `Conn`. If you're worried about creating a separate copy of all of these constants in every `Conn` instance, you can make them class variables instance of instance variables. (And you may want to make `getPool` a `@classmethod`, too.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T06:00:29.350",
"Id": "28688",
"Score": "0",
"body": "Actually I just need change configs and grab rules for every specifical site, merge the two class together means I should create a lot of different Conns and make code lager.I just wonder is it deserved?"
}
] |
[
{
"body": "<h3>Class design</h3>\n\n<p>A good class in general is one that corresponds to an <em>Abstract Data Type</em>,\nwhich is a collection of data and operations that work on that data.\nA good ADT should have a single, clear responsibility.</p>\n\n<p>The <code>Global</code> class is not a good ADT:</p>\n\n<ul>\n<li>It does two unrelated things:\n<ul>\n<li>Contain configuration information</li>\n<li>Manage a proxy pool</li>\n</ul></li>\n<li>Possibly as a consequence of the previous point, it is poorly named</li>\n</ul>\n\n<p>It would be better to split this class into two:</p>\n\n<ul>\n<li><code>Configuration</code> or <code>Config</code>: contain configuration information</li>\n<li><code>ProxyPoolManager</code>: manage a proxy pool</li>\n</ul>\n\n<p>Note that <code>ProxyPoolManager</code> should not reference <code>Configuration</code> directly:\nit will be best to pass to it the <code>proxyHost</code> and <code>proxy</code> as constructor parameters.</p>\n\n<p>As the poorly named <code>Conn</code> class already does half of the proxy pool management,\nit would be better to rename it to <code>ProxyPoolManager</code> and move <code>getPool</code> method into it and rename <code>Global</code> to <code>Configuration</code>.</p>\n\n<h3>Coding style</h3>\n\n<p>You have several coding style violations, not conforming to <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>:</p>\n\n<ul>\n<li>Use spaces around <code>=</code> in variable assignments, for example:\n<ul>\n<li><code>proxy = True</code> instead of <code>proxy=True</code></li>\n<li><code>opts = AttrDict(...)</code> instead of <code>opts=AttrDict(...)</code></li>\n</ul></li>\n<li>No need to put parentheses in <code>if(self.proxy):</code></li>\n<li>There should be one blank line in front of method definitions of a class: put a blank line in front of <code>get</code> and <code>switch</code> methods in the <code>Conn</code> class</li>\n<li>You mistyped <code>switch</code> as <code>swith</code></li>\n</ul>\n\n<h3>Other issues</h3>\n\n<p>This code doesn't compile:</p>\n\n<blockquote>\n<pre><code>class Conn:\n def get(url, opts=Global.opts):\n try:\n self.pool.urlopen(...)\n</code></pre>\n</blockquote>\n\n<p>Because it makes a reference to <code>self</code> which was not passed in as method parameter.</p>\n\n<hr>\n\n<p>This is a bit hard to understand,\nbecause of reusing the name \"proxy\" both as method parameter and as attribute:</p>\n\n<blockquote>\n<pre><code>def getPool(self,proxy=None):\n if proxy is None:\n proxy = self.proxy\n if(self.proxy):\n http_pool = urllib3.proxy_from_url(self.proxyHost)\n else:\n http_pool = urllib3.connection_from_url(self.host)\n return http_pool\n</code></pre>\n</blockquote>\n\n<p>The purpose of this method would be more clear if you used a different name for the method parameter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-20T09:50:13.377",
"Id": "74256",
"ParentId": "17993",
"Score": "6"
}
},
{
"body": "<p><code>getPool()</code> doesn't use the <code>proxy</code> argument. The method starts by using the class value to set a default value. However, the if statement just uses the class value and ignores the argument it just assigned a default value to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-20T10:23:08.613",
"Id": "74258",
"ParentId": "17993",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "74256",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T04:57:12.143",
"Id": "17993",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"http"
],
"Title": "Two Python classes for a web crawler"
}
|
17993
|
<p>How could I improve this code to make it shorter and more functional?</p>
<pre><code>#!usr/bin/python
import time
integer = 0
print("The current integer is set at " + str(integer) + ".")
print("\n")
time.sleep(2)
prompt = raw_input("Would you like to change the integer? (Y/N) ")
print("\n")
if prompt == 'y':
integer = int(raw_input("Insert the new integer here: "))
print("\n")
print("You have changed the integer to " + str(integer) + ".")
print("\n")
print("\n")
time.sleep(1)
print("1. Add / 2. Subtract / 3. Multiply / 4. Divide")
print("\n")
new_int = raw_input("What would you like to do with your new integer? (Choose a number) ")
print("\n")
if new_int == '1':
added_int = int(raw_input("What number would you like to add to your integer (" + str(integer) + ") by?"))
outcome1 = integer + added_int
print("\n")
print("The sum of " + str(integer) + " + " + str(added_int) + " is " + str(outcome1))
if new_int == '2':
subtracted_int = int(raw_input("What number would you like to subtract your integer (" + str(integer) + ") by?"))
outcome2 = integer - subtracted_int
print("\n")
print("The difference of " + str(integer) + " - " + str(subtracted_int) + " is " + str(outcome2))
if new_int == '3':
multiplied_int = int(raw_input("What number would you like to multiply your integer (" + str(integer) + ") by?"))
outcome3 = integer * multiplied_int
print("\n")
print("The product of " + str(integer) + " x " + str(multiplied_int) + " is " + str(outcome3))
if new_int == '4':
divided_int = int(raw_input("What number would you like to divide your integer (" + str(integer) + ") by?"))
outcome4 = integer / divided_int
print("\n")
print("The quotient of " + str(integer) + " / " + str(divided_int) + " is " + str(outcome4))
elif prompt == "n":
print("The integer will stay the same.")
time.sleep(2)
print("Press any key to exit...")
else:
print("Invalid input.")
raw_input()
</code></pre>
|
[] |
[
{
"body": "<p>How about something like this?</p>\n\n<pre><code>import time\n\ndef add_num(x):\n added_int = int(raw_input(\"What number would you like to add to your integer (%s) by?\" % x))\n outcome = x + added_int\n print(\"\\nThe sum of %s + %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef sub_num(x):\n sub_int = int(raw_input(\"What number would you like to subtract to your integer (%s) by?\" % x))\n outcome = x - sub_int\n print(\"\\nThe subtract of %s - %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef mul_num(x):\n mul_int = int(raw_input(\"What number would you like to multiply your integer (%s) by?\" % x))\n outcome = x * mul_int\n print(\"\\nThe multiplication of %s * %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef div_num(x):\n div_num = int(raw_input(\"What number would you like to divide your integer (%s) by?\" % x))\n outcome = x / float(div_num)\n print(\"\\nThe divider of %s / %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef main():\n op_map = {\"1\":add_num, \"2\":sub_num, \"3\":mul_num, \"4\":div_num}\n number = 0\n print(\"The current integer is set at %s .\" % number)\n while True:\n prompt = raw_input(\"Would you like to change the number? (Y/N)\").lower()\n if prompt == \"y\":\n number = int(raw_input(\"Insert the new integer here: \"))\n print(\"\\nYou have changed the integer to %s .\\n\\n\" % number)\n time.sleep(1)\n print(\"1. Add / 2. Subtract / 3. Multiply / 4. Divide\\n\")\n\n op = raw_input(\"What would you like to do with your new integer? (Choose a number) \\n\")\n if op is not None:\n operation = op_map.get(op)\n number = operation(number)\n\n elif prompt == \"n\":\n print(\"The integer will stay the same.\")\n time.sleep(2)\n raw_input(\"Press enter key to exit...\")\n break\n else:\n print(\"Invalid response\")\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T12:37:20.373",
"Id": "28741",
"Score": "0",
"body": "You shouldn't define a function `div_num()` and then inside it use a variable also called `div_num`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T20:24:42.240",
"Id": "28775",
"Score": "0",
"body": "@Matt eh good spot but really? function local namespace rarely matters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T22:28:29.303",
"Id": "28783",
"Score": "3",
"body": "It makes the code harder to understand if you use the same name for two different things like that. In general it is bad practice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T18:48:17.997",
"Id": "17998",
"ParentId": "17996",
"Score": "1"
}
},
{
"body": "<p>Here is a less verbose script that does the basic operations like you are doing.\nIt may be a little advanced for you based on what you wrote, but I thought you might be interested in having a look.</p>\n\n<pre><code>import re\n\npat = re.compile(r'\\s*(\\-?\\d+\\.?\\d*)\\s*([+-/*])\\s*(\\-?\\d+\\.?\\d*)\\s*')\n\nwhile True:\n print 'Input a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:'\n user_input = raw_input()\n if user_input == '-1':\n break\n\n m = pat.match(user_input)\n if m:\n try:\n result = eval(m.group())\n except ZeroDivisionError:\n print 'Cannot divide by zero.',\n continue\n\n print m.group(1), m.group(2), m.group(3), '=', result\n else:\n print 'Invalid expression.',\n</code></pre>\n\n<p>Sample Output from running the script:</p>\n\n<pre><code>>>>Input a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:\n-2 * 1\n-2 * 1 = -2\nInput a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:\n-4 / 0\nCannot divide by zero. Input a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:\n5 /2\n5 / 2 = 2\nInput a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:\n5/2.0\n5 / 2.0 = 2.5\nInput a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:\n78--2\n78 - -2 = 80\nInput a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:\n90+2\n90 + 2 = 92\nInput a basic expression (ex: 12 * 4, 3.24+3, 19/2, etc) or -1 to exit:\n-1\n>>>\n</code></pre>\n\n<p>Here's a little breakdown in case you don't understand what's going on. The script uses regular expressions, hence <code>import re</code>, to extract a simple equation. A simple equation meaning a number followed by an operation followed by another number.</p>\n\n<pre><code>'\\s*(\\-?\\d+\\.?\\d*)\\s*([+-/*])\\s*(\\-?\\d+\\.?\\d*)\\s*'\n</code></pre>\n\n<p>is the regular expression.</p>\n\n<pre><code>\\s* means 0 or more spaces\n\\-? means there may or may not be a - (for negative numbers)\n\\d+ means 1 or more digits\n\\.? means there may or may not be a . (for decimal numbers)\n\\d* means 0 or more digits\n[+-/*] means one of those symbols\n</code></pre>\n\n<p>So lets look at what is being grouped in the brackets ()</p>\n\n<pre><code>(\\-?\\d+\\.?\\d*) which means a positive or negative number that could be an integer or a decimal\n([+-/*]) which picks the operation to be performed on the numbers\n(\\-?\\d+\\.?\\d*) which is the same as the first\n</code></pre>\n\n<p>Each of these expressions in brackets are separated with a <code>\\s*</code> and since <code>match(string)</code> only keeps what's in the brackets, all the spacing is ignored.</p>\n\n<p>The regular expression is then compiled and you can use that pattern variable (which I called <code>pat</code>) to match against input (which I stored in <code>m</code> in the line <code>m = pat.match(user_input)</code>).</p>\n\n<p>As I said above, <code>match</code> only keeps what's in the brackets, and it puts them into groups.</p>\n\n<pre><code>m.group(0) #is everything ex) 10*10.5\nm.group(1) #is the first brackets contents. ex) 10\nm.group(2) #is the second brackets contents. ex) *\nm.group(3) #is the third brackets contents. ex) 10.5 \n</code></pre>\n\n<p>You can see how I printed out the equation with the result using <code>m.group()</code>. Also, I should say that when <code>match(input)</code> doesn't find a match, it returns <code>None</code> so <code>if m:</code> in the code passes if a match is found and fails if one isn't.</p>\n\n<p>Finally, <code>eval()</code> will evaluate the expression inside of it which is how we get the result.</p>\n\n<p>You can also see that I used a <code>try/except</code> statement to catch division by zero. Oh and if you put an <strong>r</strong> in front of a string like <code>r'hello world\\n'</code>, it is a \"raw string\" and ignores escaped characters (ie: things like new line \\n) and just stores the characters as is.</p>\n\n<p>Even if this isn't exactly what you were looking for, I hope you found it interesting and perhaps learned something from it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-10T03:17:58.873",
"Id": "18435",
"ParentId": "17996",
"Score": "1"
}
},
{
"body": "<p>@Jackob wrote a better solution, but I can still see much duplication, here you can see a DRY version using higher order functions:</p>\n\n<pre><code>def user_interface_operation(start, operation):\n b = int(raw_input(\"What is x in {} {} x ?\".format(start, operation.__name__)))\n outcome = operation(start, b)\n print(\"The result is {}\".format(outcome))\n return outcome\n\nadd_num = lambda start: user_interface_operation(start, op.add)\nsub_num = lambda start: user_interface_operation(start, op.sub)\nmul_num = lambda start: user_interface_operation(start, op.mul)\ndiv_num = lambda start: user_interface_operation(start, op.div)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-24T13:06:13.313",
"Id": "87846",
"ParentId": "17996",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T18:12:31.087",
"Id": "17996",
"Score": "4",
"Tags": [
"python",
"calculator"
],
"Title": "Performing calculations with updated integer"
}
|
17996
|
<p>I would like to get some general comments on style and use of STL in particular. This is some code I wrote to do machine learning classification (logistic regression). Any suggestions would be very appreciated!</p>
<p>A record containing an individual training example:</p>
<pre><code>/*
* A class representing a single record to be used for training or evaluation
* of a classifier. This record contains a vector of predictors which are
* observations used to predict an outcome, together with a target outcome for
* that observation. The machine learning algorithm's job is to learn to
* generalize this predictor to target outcome relationship.
*/
#include "Record.h"
using namespace std;
/**
* Construct a record from the provided predictor Vector and target outcome.
*/
Record::Record(const Vector& predictor, double target) :
predictor_(predictor), target_(target) {
}
/**
* Construct a record by parsing the provided string. The string must contain
* a set of space seperated values, with the target outcome in column kTargetCol
* and the predictor vector starting on column kPredictorCol. Note that each
* element of the predictor vector is preceeded by an index and a colon. So
* the string looks has the following form:
* <label> <target_outcome> 1:<predictor_element1> 2:<predictor_element2> ...
*/
Record::Record(const string& line) {
Init(line);
}
void Record::Init(const string& line) {
stringstream line_stream(line);
string token;
for (int i = 0; getline(line_stream, token, ' '); ++i) {
if (i == kTargetCol) {
istringstream istream(token);
double target;
istream >> target;
target_ = target;
}
if (i >= kPredictorCol) {
istringstream istream(token.substr(token.find(':') + 1));
double element;
istream >> element;
predictor_.push_back(element);
}
}
}
/** Convert a record into a string suitable for display */
string Record::String() const {
ostringstream sstream;
sstream << target_;
return sstream.str() + ", " + predictor_.String();
}
</code></pre>
<p>A collection of training examples:</p>
<pre><code>/*
* A class representing a collection of records to be used for training or
* evaluation of a classifier.
*/
#include "RecordList.h"
using namespace std;
/**
* Initialize a list of training/test records from the provided filename.
*/
RecordList::RecordList(const string& filename) {
input_file_.open(filename.c_str(), ios::in);
Init();
}
void RecordList::Init() {
for (string line; getline(input_file_, line);) {
Record record(line);
records_.push_back(record);
}
}
RecordList::~RecordList() {
input_file_.close();
}
/**
* A constant version of an iterator pointing to the beginning of the record
* list. Used for doing read only iterations through the list.
*/
vector<Record>::const_iterator RecordList::const_begin() const {
return records_.begin();
}
/**
* A constant version of an iterator pointing to the end of the record list.
* Used for doing read only iterations through the list.
*/
vector<Record>::const_iterator RecordList::const_end() const {
return records_.end();
}
/**
* A regular version of an iterator pointing to the beginning of the record list.
* Used for doing iterations through the list that modify records.
*/
vector<Record>::iterator RecordList::begin() {
return records_.begin();
}
/**
* A regular version of an iterator pointing to the end of the record list.
* Used for doing iterations through the list that modify records.
*/
vector<Record>::iterator RecordList::end() {
return records_.end();
}
/**
* Get the number of elements in the predictor vectors. Note that this is the
* same for all records;
*/
int RecordList::RecordSize() const {
return records_[0].predictor().size();
}
/** Get the average of the predictors. */
Vector RecordList::Mean() const {
Vector mean(RecordSize());
for (vector<Record>::const_iterator itr = const_begin(); itr != const_end();
++itr) {
mean = mean + itr->predictor();
}
return mean / records_.size();
}
/** Get the variance of the predictors. */
Vector RecordList::SqrtVar() const {
Vector var(RecordSize());
Vector mean = Mean();
for (vector<Record>::const_iterator itr = const_begin(); itr != const_end();
++itr) {
var = var + (itr->predictor() - mean).Square();
}
return (var / records_.size()).Sqrt();
}
/** Convert the record list into a string suitable for display. */
string RecordList::String() const {
string result = "";
int i = 0;
for (vector<Record>::const_iterator itr = records_.begin();
itr != records_.end(); ++itr) {
if (i++ == 10) {
return result + "...\n";
}
result += itr->String() + "\n";
}
return result;
}
</code></pre>
<p>A normalizer used to pre-process each training sample:</p>
<pre><code>/**
* A class for normalizing records.
*/
#include "Normalizer.h"
/**
* Construct a normalizer suitable for the provided RecordList by calculating
* the mean and square root of the underlying predictor Vectors.
*/
Normalizer::Normalizer(const RecordList& recordList)
: mean_(recordList.Mean()), sqrt_var_(recordList.SqrtVar()) {}
/**
* Normalize a RecordList by subtracting the mean from each predictor Vector
* and dividing by the square root of the variance.
*/
void Normalizer::Normalize(RecordList& recordList) const {
for (vector<Record>::iterator itr = recordList.begin();
itr != recordList.end(); ++itr) {
itr->set_predictor(Normalize(itr->predictor()));
}
}
/**
* Normalize an individual predictor Vector.
*/
Vector Normalizer::Normalize(const Vector& v) const {
return (v - mean_) / sqrt_var_;
}
</code></pre>
<p>The classifier itself:</p>
<pre><code>/**
* A class representing a logistic regression classifier. This classifier can
* predict the target outcome for any given predictor Vector. It can also be
* trained by the Trainer class given a suitable training RecordList.
*/
#include "Classifier.h"
using namespace std;
/**
* Construct a classifier for the provided training set and normalizer. This
* initializes the weight Vector to have all zero. A Trainer must be applied
* to the Classifier before it can be used.
*/
Classifier::Classifier(const RecordList& training_set,
const Normalizer& normalizer) :
normalizer_(normalizer),
weights_(Vector(training_set.RecordSize())) {}
/**
* Classify the provided predictor Vector. This provides an estimate of the
* target outcome.
*/
double Classifier::Classify(const Vector& v) const {
Vector vn = normalizer_.Normalize(v);
return 2.0 * Sigmoid(weights_.InnerProduct(vn)) - 1.0;
}
/**
* Calculate the sigmoid (logistic function) of the given value.
*/
double Classifier::Sigmoid(double x) const {
return 1.0 / (1.0 + exp(-x));
}
/**
* Evaluate performance of the classifier using the provided test RecordList.
*/
int Classifier::EvaluatePerformance(const RecordList& test_set) const {
int total = 0;
int correct = 0;
for (vector<Record>::const_iterator itr = test_set.const_begin();
itr != test_set.const_end(); ++itr) {
double result = Classify(itr->predictor());
total++;
if ((result < 0 && itr->target() < 0)
|| (result > 0 && itr->target() > 0)) {
correct++;
}
}
return (100*correct) / total;
}
</code></pre>
<p>A class for training the classifier:</p>
<pre><code>/**
* A class for training a classifier.
*/
#include "Trainer.h"
using namespace std;
static const double kTrainingRate = 0.01;
static const string kTrainingFile = "data/training.txt";
static const string kTestFile = "data/test.txt";
/**
* Construct a Trainer using the provided training rate. Higher training rates
* will lead to faster convergence but higher asymptotic error.
*/
Trainer::Trainer(double training_rate) : training_rate_(training_rate) {}
/**
* Train a classifier using stochastic gradient descent. At each iteration
* the classifier weights are updated based on the delta between the estimate
* from the classifier and the target outcome.
*/
void Trainer::Train(const RecordList& training_records,
Classifier& classifier) {
Vector delta;
for (vector<Record>::const_iterator itr = training_records.const_begin();
itr != training_records.const_end(); ++itr) {
double estimate = classifier.Classify(itr->predictor());
double estimation_error = estimate - itr->target();
delta = itr->predictor() * (training_rate_ * estimation_error);
classifier.set_weights(classifier.weights() - delta);
}
}
/**
* The main program. Loads a set of training records and normalizes them. It
* then uses these records to train a classifier before evaluating the
* classifier's performance on a second set of test records.
*/
int main() {
RecordList training_records(kTrainingFile);
Normalizer normalizer(training_records);
Classifier classifier(training_records, normalizer);
Trainer trainer(kTrainingRate);
trainer.Train(training_records, classifier);
RecordList test_records(kTestFile);
printf("Percentage of correct classifications: %d%%\n",
classifier.EvaluatePerformance(test_records));
}
</code></pre>
<p>And finally a class for representing mathematical vectors (essentially just arrays of doubles):</p>
<pre><code>/**
* A class to represent a vector which is an array of doubles. Supports various
* calculations like addition, subtraction and inner product.
*/
#include "Vector.h"
using namespace std;
Vector::Vector() : elements(vector<double>()) {}
Vector::Vector(int size) : elements(vector<double>(size, 0)) {}
Vector::Vector(const vector<double>& values) : elements(values) {}
int Vector::size() const {
return elements.size();
}
double Vector::operator[](int index) const {
return elements[index];
}
/**
* A constant version of an iterator pointing ot the beginning of the vector.
* Used for doing a read only iteration through the vector.
*/
vector<double>::const_iterator Vector::const_begin() const {
return elements.begin();
}
/**
* A constant version of an iterator pointing ot the end of the vector.
* Used for doing a read only iteration through the vector.
*/
vector<double>::const_iterator Vector::const_end() const {
return elements.end();
}
/**
* A regular version of an iterator pointing to the beginning of the vector.
* Used for doing iterations through the vector that modify elements.
*/
vector<double>::iterator Vector::begin() {
return elements.begin();
}
/**
* A regular version of an iterator pointing to the end of the vector.
* Used for doing iterations through the vector that modify elements.
*/
vector<double>::iterator Vector::end() {
return elements.end();
}
/** Convert a Vector into a string suitable for display. */
string Vector::String() const {
string result = "[ ";
for (vector<double>::const_iterator itr = elements.begin();
itr != elements.end(); ++itr) {
ostringstream sstream;
sstream << *itr;
result += sstream.str() + " ";
}
result += ("]");
if (result.size() > 50) {
return result.substr(0, 47) + " ... ]";
}
return result;
}
void Vector::push_back(double value) {
elements.push_back(value);
}
/**
* Calculate the inner product of two Vectors by taking the sum of the products
* of the corresponding elements.
*/
double Vector::InnerProduct(const Vector& operand) const {
return inner_product(const_begin(), const_end(), operand.const_begin(), 0);
}
Vector Vector::operator+(const Vector& operand) const {
Vector result(size());
transform(const_begin(), const_end(), operand.const_begin(), result.begin(),
plus<double>());
return result;
}
Vector Vector::operator-(const Vector& operand) const {
Vector result(size());
transform(const_begin(), const_end(), operand.const_begin(), result.begin(),
minus<double>());
return result;
}
/** Functor for multiplying a Vector by a scalar. */
struct MultiplyScalar {
public:
MultiplyScalar(double scalar) : scalar(scalar) {}
double operator()(double x) {
return x * scalar;
}
private:
double scalar;
};
Vector Vector::operator*(double multiplier) const {
Vector result(size());
transform(elements.begin(), elements.end(), result.elements.begin(),
MultiplyScalar(multiplier));
return result;
}
Vector Vector::operator/(const Vector& divisor) const {
Vector result(size());
transform(const_begin(), const_end(), divisor.const_begin(), result.begin(),
divides<double>());
return result;
}
/** Functor for dividing a Vector by a scalar. */
struct DivideScalar {
public:
DivideScalar(double scalar) : scalar(scalar) {}
double operator()(double x) {
return x / scalar;
}
private:
double scalar;
};
Vector Vector::operator/(double divisor) const {
Vector result(size());
transform(elements.begin(), elements.end(), result.elements.begin(),
DivideScalar(divisor));
return result;
}
double OpSquare(double x) {
return x*x;
}
/** Calculate the element-wise square of a Vector. */
Vector Vector::Square() const {
Vector result(size());
transform(elements.begin(), elements.end(), result.elements.begin(),
OpSquare);
return result;
}
/** Calculate the element-wise square root of a Vector. */
Vector Vector::Sqrt() const {
Vector result(size());
transform(elements.begin(), elements.end(), result.elements.begin(),
sqrt);
return result;
}
double OpSigmoid(double z) {
return 1.0 / (1.0 + exp(-z));
}
/** Calculate the element-wise sigmoid of a Vector. */
Vector Vector::Sigmoid() const{
Vector result(size());
transform(elements.begin(), elements.end(), result.elements.begin(),
OpSigmoid);
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>Have you considered passing output arguments using pointers instead of by reference?</p>\n\n<p>That way it's clearer in your method call what the input and output arguments are, e.g instead of</p>\n\n<pre><code>trainer.Train(training_records, classifier);\n</code></pre>\n\n<p>you would have</p>\n\n<pre><code>trainer.Train(training_records, &classifier);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T04:15:47.403",
"Id": "28792",
"Score": "0",
"body": "Don't agree with that at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T07:50:38.050",
"Id": "28801",
"Score": "1",
"body": "Please elaborate."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T23:19:50.413",
"Id": "18063",
"ParentId": "18002",
"Score": "1"
}
},
{
"body": "<h2>Edit (based on the large number of additions) I am re-writing this:</h2>\n<h3>General Notes:</h3>\n<p>You should add header guards to all your *.h files.</p>\n<h3>Vector.h</h3>\n<p>Don't like your use of string conversion methods. Very Java like and not C++ like at all. Prefer to write stream operators which are much more versatile.</p>\n<pre><code> string String() const;\n\n // Prefer\n\n friend std::ostream& operator<<(std::ostream stream, Vector const& data)\n {\n return stream;\n }\n</code></pre>\n<p>Hide your implementation details by using local typedefs. Also it is more traditional to just call the method to get a const iterator <code>begin()</code> rather than <code>const_begin()</code> etc.</p>\n<pre><code> vector<double>::const_iterator const_begin() const;\n vector<double>::iterator begin();\n\n // Prefer\n typedef std::vector<double> Container;\n typedef Container::iterator iterator;\n typedef Container::const_iterator const_iterator;\n\n iterator begin();\n const_iterator begin() const;\n</code></pre>\n<p>This works but it also allows some expressions that don't do much;</p>\n<pre><code> double operator[](int index) const;\n\n // Now the compiler will allow:\n\n Vector x;\n x[5] = 6; // Will compile but not do anything.\n // I would prefer this fails to compile so that the\n // user of the class will know that they have done\n // something wrong immediately.\n\n // Thus I would prefer this declaration:\n double const& operator[](std::size_t index) const;\n</code></pre>\n<p>Not totally convinced that setting up these operators will make using the class easier to read.</p>\n<pre><code> Vector operator+(const Vector& operand) const;\n Vector operator-(double scalar) const;\n Vector operator-(const Vector& operand) const;\n Vector operator*(double scalar) const;\n Vector operator/(double scalar) const;\n Vector operator/(const Vector& operand) const;\n</code></pre>\n<p>Surprised this compiles at all here:</p>\n<pre><code>private:\n vector<double> elements;\n</code></pre>\n<p>The header file should include all the header files it need to make the required types available. There is no <code>#include <vector></code> in this file. Also you do not prefix <code>vector</code> with <code>std::</code> so how does it know where it is defined.</p>\n<p>There are a couple of explanations to both these problems none of them good.</p>\n<p><strong>NEVER</strong> put <code>using namespace std;</code> in a header file.<br />\n<strong>NEVER</strong> make a header file depend on being included in the correct order.</p>\n<h3>Vector.cpp</h3>\n<pre><code>Vector::Vector() : elements(vector<double>()) {}\n// Easier to write:\nVector::Vector() : elements() {}\n\n\nVector::Vector(int size) : elements(vector<double>(size, 0)) {} \n// Easier to write\nVector::Vector(int size) : elements(size) {} // Value defaults to 0 \n</code></pre>\n<p>I would use the correct type. here.</p>\n<pre><code>int Vector::size() const {return elements.size();}\n// I would use:\nstd::size_t Vector::size() const {return elements.size();}\n</code></pre>\n<p>As described above I would return by const reference.</p>\n<pre><code>double Vector::operator[](int index) const {\n return elements[index];\n}\n</code></pre>\n<p>Here I would not convert to a string.<br />\nI would a stream operator (then use some algorithms inside to make it cleaner).</p>\n<pre><code>/** Convert a Vector into a string suitable for display. */\nstring Vector::String() const {\n\nfriend std::ostream& operator<<(std::ostream& stream, Vector const& data)\n{\n stream << "[ ";\n std::copy(elements.begin(), elements.end(), std::ostream_iterator<double>(stream," "));\n \n stream << "] ";\n return stream;\n}\n</code></pre>\n<p>I will add more when I get some time.</p>\n<h2>Old review.</h2>\n<p>Rather than write a to_string() method:</p>\n<pre><code>string Record::String() const {\n ostringstream sstream;\n sstream << target_;\n return sstream.str() + ", " + predictor_.String();\n}\n</code></pre>\n<p>Write a stream operator.</p>\n<pre><code>std::ostream& operator<<(std::stream& stream, Record const& data)\n{\n return stream << data.target_ << ", " << data.predictor_;\n}\n</code></pre>\n<p>If you really just want a string use lexical cast:</p>\n<pre><code>Record record(/* Initialization*/);\n\n// lexical_cast use the stream operator.\nstd::string data = boost::lexical_cast<std::string>(record);\n</code></pre>\n<p>I don't see the need for a file-stream member that is kept open for the life of the object. Open it use it then let it fall out of scope:</p>\n<pre><code>RecordList::RecordList(const string& filename) {\n input_file_.open(filename.c_str(), ios::in);\n Init();\n}\n\nvoid RecordList::Init() {\n for (string line; getline(input_file_, line);) {\n Record record(line);\n records_.push_back(record);\n }\n}\n\nRecordList::~RecordList() {\n input_file_.close();\n}\n\nI would just do:\n\nRecordList::RecordList(const string& filename) {\n Init(filename);\n}\n\nvoid RecordList::Init(std::string const& filename) {\n std::ifstream input_file(filename.c_str());\n for (string line; getline(input_file, line);) {\n Record record(line);\n records_.push_back(record);\n }\n}\n\nRecordList::~RecordList() {}\n</code></pre>\n<p>Here you are exposing an implementation detail:</p>\n<pre><code> vector<Record>::const_iterator RecordList::const_begin() const {\n</code></pre>\n<p>The user of your class should not need to know that you are using a vector internal to your class</p>\n<pre><code>class RecordList\n{\n public:\n typedef std::vector<Record> Container;\n typedef Container::iterator iterator;\n typedef Container::const_iterator const_iterator;\n\n const_iterator RecordList::const_begin() const;\n};\n</code></pre>\n<p>Where you can try and use standard algorithms rather than loops:</p>\n<pre><code>Vector mean(RecordSize());\nfor (vector<Record>::const_iterator itr = const_begin(); itr != const_end();\n ++itr) {\n mean = mean + itr->predictor();\n}\n</code></pre>\n<p>I would try and do t for you but I can tell what the type <code>Vector</code> really is. It looks like it should be some container type but you use it like a scaler type on the next line.</p>\n<pre><code>return mean / records_.size();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T03:34:33.600",
"Id": "28788",
"Score": "0",
"body": "Fantastic. The Vector class is at the bottom. I've used operator overloading so you can divide the vector by a scalar (in this case the same scalar is used for every element of the vector). Could you please give it quick sanity check? Thank you again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T04:13:47.660",
"Id": "28789",
"Score": "0",
"body": "@padawan: Same comment as RecordList: \"You are exposing implementation details\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T04:14:21.340",
"Id": "28790",
"Score": "0",
"body": "@padawan: PS. it would be better to include both header and source files. Put the names of the files above each code block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T04:15:12.587",
"Id": "28791",
"Score": "0",
"body": "@padawan: PPS. This is a lot of code for one question. In the future it may be worth spreading it across multiple questions on multiple days. Then you can incorporate feedback in new questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T05:19:50.340",
"Id": "28794",
"Score": "0",
"body": "Thanks Loki. So I should use typedef as above to hide the implementation details?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T05:48:39.390",
"Id": "28795",
"Score": "0",
"body": "One other question, the input file is actually formatted like this:\n\nsomelabel +1 1:0.542 2:0.389 3:0.584 ...\nothrlabel -1 1:0.232 2:0.231 3:0.233 ...\n\nI need to extract the double that follows the colon in each word, not before the colon. Is there a simple way I can do this similar to what you suggested?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T07:40:04.283",
"Id": "28797",
"Score": "0",
"body": "@padawan: Misread that bit of code. I have removed the comment above (but I still think it can be simplified slightly)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T07:46:31.533",
"Id": "28800",
"Score": "0",
"body": "If you can help me use a standard algorithm for the accumulation (and do a quick sanity check of my use of transform in Vector) the bounty is yours. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T08:17:14.973",
"Id": "28804",
"Score": "0",
"body": "@padawan: `sum = std::accumulate(begin, end, 0);` See: http://www.sgi.com/tech/stl/accumulate.html. The transform looks good. Personally I would have used the standard multipler (but that is just taste yours is fine). `transform(elements.begin(), elements.end(), result.elements.begin(), std::bind1st(std::multiplies<double>(), multiplier));`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T01:00:01.143",
"Id": "28940",
"Score": "0",
"body": "Thanks Loki. Could you give some general advice on the use of namespaces. Should I be using anonymous namespaces here instead of using namespace std?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T16:51:35.430",
"Id": "28963",
"Score": "0",
"body": "@padawan: The way you phrase the question indicates you don't quite understand the concept. This might be a question for http://programmers.stackexchange.com . But in general 1) don't use `using namespace XXX;` Put you code in your own namespace (I own the domain plopplop.com (not real) as a result I put all my code into the namespace `plopplop` and create sub namespaces in there). This avoid contention with other code I integrate with. The anonymous namespace is the equivalent to using global static variables (just a preferred technique)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T17:44:22.657",
"Id": "28969",
"Score": "0",
"body": "I meant should I used an anonymous namespace to keep the functors only visible within the files where they are defined?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T18:13:12.820",
"Id": "28970",
"Score": "0",
"body": "@padawan: I would start a discussion on http://programmers.stackexchange.com/ about that topic. It is a bit bigger than I can answer in comments and I am sure you can get more feedback from the people there."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T23:27:11.107",
"Id": "18064",
"ParentId": "18002",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "18064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T21:05:03.863",
"Id": "18002",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"object-oriented",
"stl",
"machine-learning"
],
"Title": "C++ and STL - Machine Learning Problem"
}
|
18002
|
<p>In this program, I have been asked to read an existing textfile (1324passlist) containing a list of passwords, then create a dictionary file with both the password and MD5 hash of the password on the same line. It should also have the user input a password hash, search the created dictionary file and print the corresponding password, if it exists.
I'm not a programmer and it's not pretty, but it runs according to the assignment guidelines.</p>
<p>I would like advice on where I could tidy up and write the code more efficiently.</p>
<pre><code>public class main
{
public static void searchTextFile(String hash) throws IOException
{
File fileName = new File("dictionary.txt");
Scanner scan = new Scanner(fileName);
String line = scan.nextLine();
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens())
{
String word1 = st.nextToken();
String word2 = st.nextToken();
if(word2.equals(hash))
{
System.out.println(word1);
break;
}
if(!st.hasMoreTokens())
{
System.out.println("Hash not found.");
}
}
}
public static String getMd5(String pInput)
{
try
{
MessageDigest lDigest = MessageDigest.getInstance("MD5");
lDigest.update(pInput.getBytes());
BigInteger lHashInt = new BigInteger(1, lDigest.digest());
return String.format("%1$032X", lHashInt);
}
catch(NoSuchAlgorithmException lException)
{
throw new RuntimeException(lException);
}
}
public static void findPassword(String fileName, String hash)
{
try
{
Scanner scanner = new Scanner(new File(fileName));
List<String> pwAndHash = new ArrayList<String>();
while(scanner.hasNext())
{
pwAndHash.add(scanner.next());
}
try
{
String hash1 = hash.toUpperCase();
int hashIndex = pwAndHash.indexOf(hash1);
int passwordIndex = hashIndex - 1;
System.out.println(pwAndHash.get(passwordIndex));
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println("The hash was not found.");
}
}
catch(FileNotFoundException e)
{
}
}
public static String hashPassword(String password)
{
String encrypted = "";
try
{
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] passwordBytes = password.getBytes();
digest.reset();
digest.update(passwordBytes);
byte[] message = digest.digest();
StringBuilder hexString = new StringBuilder();
for ( int i=0; i < message.length; i++)
{
hexString.append(Integer.toHexString(0xFF & message[ i ]));
}
encrypted = hexString.toString();
}
catch(Exception e)
{
}
return encrypted;
}
public static void main(String[]args)
{
File file = new File("1324passlist.txt");
Scanner userInput = new Scanner(System.in);
try
{
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
try
{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("dictionary.txt", true)));
String password = input.nextLine();
out.print(password);
out.flush();
String hashedPassword = getMd5(password);
out.print(" " + hashedPassword + " ");
out.close();
}
catch(IOException d)
{
}
}
}
catch (FileNotFoundException e)
{
}
System.out.println("Enter a hash to search for its corresponding password.");
String hashToSearch = userInput.next();
findPassword("dictionary.txt", hashToSearch);
try
{
searchTextFile(hashToSearch);
}
catch(IOException e)
{
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some comments that don't relate to efficiency:</p>\n<p>Exceptions and exception handling. In a couple of places you are SQUASHING exceptions; e.g.</p>\n<pre><code> catch(FileNotFoundException e)\n {\n }\n</code></pre>\n<p>So, if we can't open the password file, we effectively <em>ignore</em> the error, and ... behave exactly as if the password was correct.</p>\n<pre><code> catch( Exception e ) { }\n</code></pre>\n<p>This is even worse. You are now squashing all exceptions, including any NPEs, class cast exceptions, etc caused by bugs in your code or (hypothetically) in library code you are calling.</p>\n<p><strong>Lesson #1:</strong> - Do not squash exceptions. Any exception that is out of the ordinary should result in <em>at least</em> an error message to report the problem. And if your code is not anticipating the exception, then you should print / log a stack trace.</p>\n<p>This is bad:</p>\n<pre><code> try {\n String hash1 = hash.toUpperCase();\n int hashIndex = pwAndHash.indexOf(hash1);\n int passwordIndex = hashIndex - 1;\n System.out.println(pwAndHash.get(passwordIndex));\n } catch(ArrayIndexOutOfBoundsException a) {\n System.out.println("The hash was not found.");\n }\n</code></pre>\n<p>Reasons:</p>\n<ul>\n<li><p>You are expecting that the <code>ArrayIndexOutOfBoundsException</code> will be thrown in this: <code>pwAndHash.get(passwordIndex)</code>. But that statement won't throw that exception. If the index is wrong is wrong it throws <code>IndexOutOfBoundsException</code>.</p>\n</li>\n<li><p>Supposing it <em>did</em> throw that exception, you still have the problem that <em>other</em> statements in the block could throw that exception ... for a completely different reason. For example, if you were using your own <code>List</code> implementation class, it could be due to an unexpected bug in that class.</p>\n</li>\n<li><p>Throwing and catching an exception in Java is relatively expensive. In this case, there is a simpler, cleaner, more efficient solution:</p>\n<pre><code>String hash1 = hash.toUpperCase();\nint hashIndex = pwAndHash.indexOf(hash1);\nif (hashIndex == -1) {\n System.out.println("The hash was not found.");\n} else {\n int passwordIndex = hashIndex - 1;\n System.out.println(pwAndHash.get(passwordIndex));\n}\n</code></pre>\n</li>\n</ul>\n<p><strong>Lesson #2:</strong> Be really careful when catching unchecked exceptions to make sure that you don't hide bugs ... or introduce new ones by catching the wrong exception.</p>\n<p><strong>Lesson #3:</strong> Don't use exceptions for normal control flow ... unless it really simplifies things. (Some people would say <em>never</em> use exceptions for control flow, but there are limited cases where it is (IMO) justified to use them.)</p>\n<p><strong>Stylistic:</strong></p>\n<ol>\n<li><p>Indent your code properly, and make sure that you are consistent in your use of TAB characters. (Ideally reconfigure your IDE so that it doesn't use them at all!).</p>\n</li>\n<li><p>Be consistent about line breaks, and embedded whitespace.</p>\n</li>\n<li><p>I'd recommend NOT putting opening braces for code blocks on a new line. It wastes vertical screen space ... and goes against Best Practice as set out in the Sun Java Style Guide (see below).</p>\n</li>\n</ol>\n<p><sub>When I am marking student code, they will get severely penalized for poor style. And in a professional situation, poor style results in <strong>rejection</strong> of code on quality grounds. When you write code, you write it for <em>other people</em> to read. If it is not readable, it is not fit for purpose. Period.</sub></p>\n<hr />\n<p>To those who think that placement of braces is a personal preference, the following is quoted from the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#430\" rel=\"nofollow noreferrer\">Sun Java Style Guide</a>:</p>\n<blockquote>\n<p>7.2 Compound Statements</p>\n<p>Compound statements are statements that contain lists of statements enclosed in braces "{ statements }". See the following sections for examples.</p>\n<ul>\n<li>The enclosed statements should be indented one more level than the compound statement.</li>\n<li><strong>The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line and be indented to the beginning of the compound statement.</strong></li>\n<li>Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.</li>\n</ul>\n</blockquote>\n<p>And the Guide has many examples to illustrate what they mean by that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T01:35:12.900",
"Id": "28701",
"Score": "0",
"body": "I've only done one other assignment using exception handling, and I really appreciate your explanation. Will address the stylistic issues too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T01:51:07.310",
"Id": "28702",
"Score": "2",
"body": "Re: Style point #3 - One person's waste of vertical space is another person's improved sense of symmetry. I am the opposite, I feel like not introducing enough vertical space leaves the code less balanced and less readable. You should note which parts are opinions and which parts are more universally considered best practice, because otherwise you make good points."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T04:14:02.763",
"Id": "28706",
"Score": "1",
"body": "@asveikau it was my understanding having curly braces on the same line in java was considered \"best practice\"??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T05:36:54.893",
"Id": "28894",
"Score": "0",
"body": "@asveikau - It is not personal opinion. Please refer to the section of the Sun Java Style Guide quoted in my Answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T06:05:37.897",
"Id": "28896",
"Score": "0",
"body": "@StephenC - Sorry, but Sun (now Oracle) cannot decide how I, you, or anyone else formats their code. It may very well have been Sun's recommendation but it is an *opinion* and not a requirement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T10:29:53.733",
"Id": "28901",
"Score": "2",
"body": "@StephenC the key word there is 'guide' it's a preference from Sun/Oracle, the code will compile either way! I personally find it much easier to read the code if the opening brace is on a new line for a code block, the \"waste of screen space\" argument is pretty weak these days, if you can't see an entire method on a 19\" monitor then your method needs refactoring IMHO!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T10:45:27.347",
"Id": "28902",
"Score": "2",
"body": "@asveikau I, too, *generally* prefer my braces on new lines. But when I code in Java, **I follow the standard** in order to facilitate sharing and teamwork. Following coding standards (including style guidelines) *feels* consistent and makes sure that everyone can focus on the code instead of the formatting. However, what's much more important than following Oracle's standards is to be consistent within the team or project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T11:35:36.267",
"Id": "28906",
"Score": "0",
"body": "@asveikau - Sorry, but following coding standards IS a requirement. Like I said in my original answer **\"When you write code, you write it for other people to read.\"** And that means conforming to the community norms. And if the Sun Style Guide isn't a Java community norm, I don't know what is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T16:05:08.877",
"Id": "28924",
"Score": "1",
"body": "Of course I see the value of keeping style consistent in a team or throughout a code base. I do not however see any value in dogmatically accepting *one* style guide and rejecting that any other be used. So Sun originated the language, OK. K&R created C, and also wrote with braces on the same line, but I don't feel obliged to follow their style. Nor should I. A guide is a guide, not a dictatorial fiat, and one should read it critically and not be afraid to question it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-08T07:42:29.583",
"Id": "168923",
"Score": "0",
"body": "@asveikau - You are comparing apples and oranges. K&R is not a norm because most C programmers don't follow it. The Sun Style Guide is a norm because most Java programmers DO follow it. (Or at least they did, before the Java space got invaded by Android and Minecraft programmers ... who mostly learned to program in a cultural vacuum.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-08T07:45:10.440",
"Id": "168924",
"Score": "0",
"body": "@asveikau - And frankly, if someone posts code here to be reviewed, it is implicit that other people are going to read it."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T01:17:01.703",
"Id": "18005",
"ParentId": "18004",
"Score": "5"
}
},
{
"body": "<p>Handling runtime exceptions is the wrong way of coding. Also embedding all your code in a try-catch is wrong.\nWhat I would do is to handle all the exceptions in the main() method and allow individual methods to throw the checked exceptions. Its obvious that the main() wont be able to continue if any of the sub-methods throws a checked exception so it makes sense. Here is your edited class :</p>\n\n<pre><code>import java.io.BufferedWriter;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.math.BigInteger;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.StringTokenizer;\n\npublic class main {\n\n public static void searchTextFile(String hash) throws IOException {\n File fileName = new File(\"dictionary.txt\");\n Scanner scan = new Scanner(fileName);\n\n String line = scan.nextLine();\n StringTokenizer st = new StringTokenizer(line, \" \");\n\n while (st.hasMoreTokens()) {\n String word1 = st.nextToken();\n String word2 = st.nextToken();\n\n if (word2.equals(hash)) {\n System.out.println(word1);\n break;\n }\n if (!st.hasMoreTokens()) {\n System.out.println(\"Hash not found.\");\n }\n }\n }\n\n public static String getMd5(String pInput) throws NoSuchAlgorithmException {\n\n MessageDigest lDigest = MessageDigest.getInstance(\"MD5\");\n lDigest.update(pInput.getBytes());\n BigInteger lHashInt = new BigInteger(1, lDigest.digest());\n return String.format(\"%1$032X\", lHashInt);\n\n }\n\n public static void findPassword(String fileName, String hash)\n throws FileNotFoundException {\n\n Scanner scanner = new Scanner(new File(fileName));\n List<String> pwAndHash = new ArrayList<String>();\n while (scanner.hasNext())\n pwAndHash.add(scanner.next());\n\n String hash1 = hash.toUpperCase();\n int hashIndex = pwAndHash.indexOf(hash1);\n int passwordIndex = hashIndex - 1;\n\n System.out.println(pwAndHash.get(passwordIndex));\n\n }\n\n public static String hashPassword(String password)\n throws NoSuchAlgorithmException {\n String encrypted = \"\";\n\n MessageDigest digest = MessageDigest.getInstance(\"MD5\");\n byte[] passwordBytes = password.getBytes();\n\n digest.reset();\n digest.update(passwordBytes);\n byte[] message = digest.digest();\n\n StringBuilder hexString = new StringBuilder();\n\n for (int i = 0; i < message.length; i++) {\n hexString.append(Integer.toHexString(0xFF & message[i]));\n }\n encrypted = hexString.toString();\n\n return encrypted;\n }\n\n public static void main(String[] args) {\n File file = new File(\"1324passlist.txt\");\n Scanner userInput = new Scanner(System.in);\n try {\n Scanner input = new Scanner(file);\n\n while (input.hasNextLine()) {\n try {\n PrintWriter out = new PrintWriter(new BufferedWriter(\n new FileWriter(\"dictionary.txt\", true)));\n\n String password = input.nextLine();\n out.print(password);\n out.flush();\n String hashedPassword = getMd5(password);\n\n out.print(\" \" + hashedPassword + \" \");\n out.close();\n System.out\n .println(\"Enter a hash to search for its corresponding password.\");\n String hashToSearch = userInput.next();\n findPassword(\"dictionary.txt\", hashToSearch);\n\n searchTextFile(hashToSearch);\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T17:01:01.800",
"Id": "18019",
"ParentId": "18004",
"Score": "0"
}
},
{
"body": "<p>Many small tips, always talking about the code snippet above the tip. More on form and function, the things others might miss. I know next to nothing about crypto :)</p>\n\n<pre><code> public class main {\n\npublic static void searchTextFile(String hash) throws IOException\n</code></pre>\n\n<p>Poor name. What exactly are we searching this text file for?</p>\n\n<pre><code>{\n File fileName = new File(\"dictionary.txt\");\n</code></pre>\n\n<p>The first thing I would do is check if hash is null and throw an Exception. Is there any reason in continuing?</p>\n\n<pre><code> Scanner scan = new Scanner(fileName);\n String line = scan.nextLine();\n StringTokenizer st = new StringTokenizer(line,\" \");\n\n while(st.hasMoreTokens())\n {\n String word1 = st.nextToken();\n String word2 = st.nextToken();\n</code></pre>\n\n<p>This breaks if there are an odd number of tokens. Probably OK because you write the dictionary file, but it's bad code; which would you rather see: \"NoSuchElementException on line xxx\" or \"Dictionary file is corrupt, doesn't consist of password/hash pairs\"?</p>\n\n<pre><code> if(word2.equals(hash))\n {\n System.out.println(word1);\n break;\n }\n</code></pre>\n\n<p>Separate action from presentation. This would better written as a method which looks up the password, and returns it, and then another very simple method <code>displayPassword</code> which looks it up and prints it to <code>System.out</code>. This way your internal method is reusable should you want to get the password again, and not just want it printed.</p>\n\n<p>Also, don't use break. There are times when it makes sense, but I would argue not here; the code can easily be structured to not need it; <code>while(st.hasMoreTokens && result == null)</code></p>\n\n<pre><code> if(!st.hasMoreTokens())\n {\n System.out.println(\"Hash not found.\");\n }\n</code></pre>\n\n<p>Don't recheck in the loop whether or not <code>st.hasMoreTokens()</code>... it's harder to read. Instead, have a <code>String result = null;</code> which you're looking for, and after the loop completes if it is still null, then decide you didn't find anything. This way you're checking <code>st</code>'s elements in one place, and looping over them.</p>\n\n<pre><code> }\n}\n\npublic static String getMd5(String pInput) \n{ \n try \n {\n MessageDigest lDigest = MessageDigest.getInstance(\"MD5\"); \n lDigest.update(pInput.getBytes()); \n BigInteger lHashInt = new BigInteger(1, lDigest.digest()); \n return String.format(\"%1$032X\", lHashInt); \n</code></pre>\n\n<p>Not commenting as I'm not a security guy, but it looks good to me</p>\n\n<pre><code> } \n catch(NoSuchAlgorithmException lException) \n { \n throw new RuntimeException(lException); \n } \n</code></pre>\n\n<p>I think this is fine. You remember to include the cause (masking exceptions is bad), and if the JVM this is running in can't figure out how to use the provided algorithm, then the whole application should halt (nothing will work anyway).</p>\n\n<pre><code>}\n\n public static void findPassword(String fileName, String hash)\n{\n try\n {Scanner scanner = new Scanner(new File(fileName));\n\n List<String> pwAndHash = new ArrayList<String>();\n while(scanner.hasNext())\n {\n pwAndHash.add(scanner.next());\n }\n</code></pre>\n\n<p>Fine, but here is an important CS tradeoff. Your method is reading in, doing something, and printing out. This means that once you've handled one pwAndHash, you can forget about it. With that knowledge, which is better:</p>\n\n<ul>\n<li>Reading in every thing from the file, then iterating through and printing everything out</li>\n<li>Reading in one thing at a time, doing your thing and printing, and then forgetting it</li>\n</ul>\n\n<p>The answer; it depends, and here you're dealing with small files, so it doesn't matter. But consider a JVM running your code with 256 MB of RAM. What happens when the file you're reading is bigger than that? Your code (everything in, everything out) breaks, but the streaming version works. Not important on the scale you're working, but important to think about.</p>\n\n<pre><code> try\n {\n String hash1 = hash.toUpperCase();\n int hashIndex = pwAndHash.indexOf(hash1);\n int passwordIndex = hashIndex - 1;\n\n System.out.println(pwAndHash.get(passwordIndex));\n }\n catch(ArrayIndexOutOfBoundsException a)\n {\n System.out.println(\"The hash was not found.\");\n }\n</code></pre>\n\n<p>Exceptions are meant for exceptional circumstances. Using one as part of a loop like this is not very performant. Better might be to find where the delimiter is between pw and hash, assume the hash is the rest of that line, and compare to the hash you're searching for.</p>\n\n<pre><code> }\n catch(FileNotFoundException e)\n {\n }\n</code></pre>\n\n<p>Do something with the exception!</p>\n\n<pre><code>}\npublic static String hashPassword(String password)\n{\n String encrypted = \"\";\n\n try \n {\n MessageDigest digest = MessageDigest.getInstance( \"MD5\" ); \n byte[] passwordBytes = password.getBytes( ); \n\n digest.reset( );\n</code></pre>\n\n<p>do we need to reset? Didn't we just initialize it?</p>\n\n<pre><code> digest.update( passwordBytes );\n</code></pre>\n\n<p>If we never use passwordBytes again, why not just <code>digest.update( password.getBytes() );</code>?</p>\n\n<pre><code> byte[] message = digest.digest( );\n\n StringBuilder hexString = new StringBuilder();\n\n for ( int i=0; i < message.length; i++) \n {\n hexString.append( Integer.toHexString\n (0xFF & message[ i ] ) );\n }\n encrypted = hexString.toString();\n</code></pre>\n\n<p>Not commenting on this bit.</p>\n\n<pre><code> }\n catch( Exception e ) { }\n return encrypted;\n}\n\n\n public static void main(String[]args)\n{\n File file = new File(\"1324passlist.txt\");\n Scanner userInput = new Scanner(System.in);\n try \n { \n Scanner input = new Scanner(file);\n\n while (input.hasNextLine()) \n {\n try\n {\nPrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter\n (\"dictionary.txt\", true)));\n\n String password = input.nextLine();\n out.print(password);\n out.flush();\n String hashedPassword = getMd5(password);\n\n out.print(\" \" + hashedPassword + \" \");\n out.close();\n }\n catch(IOException d)\n {\n }\n }\n }\n catch (FileNotFoundException e)\n {\n }\n\n System.out.println(\"Enter a hash to search for its corresponding password.\");\nString hashToSearch = userInput.next();\nfindPassword(\"dictionary.txt\", hashToSearch);\n try\n {\n searchTextFile(hashToSearch);\n }\n catch(IOException e)\n {\n }\n}\n</code></pre>\n\n<p>Not commenting on main method as they are usually just a \"runner\" for what is essentially the guts on the class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T00:23:08.170",
"Id": "18099",
"ParentId": "18004",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T00:20:56.100",
"Id": "18004",
"Score": "7",
"Tags": [
"java",
"optimization",
"cryptography",
"file",
"hash-map"
],
"Title": "Creating and searching a dictionary of passwords and MD5 hashes"
}
|
18004
|
<p>Can someone improve this code? I need to eliminate the <code>for</code> loop.</p>
<pre><code>public bool CheckMobileSim(List<Mobile_Range> numberRange, string MobileNumber)
{
bool SimType = new bool();
string NineDigits = MobileNumber.Substring(0, 9).ToString();
long Number = Convert.ToInt64(NineDigits);
if (numberRange != null)
{
if (numberRange.Count > 0)
{
for (int i = 0; i < numberRange.Count; i++)
{
if ((Number >= numberRange[i].RangeStart && Number < numberRange[i].RangeEnd))
{
SimType = true;
break;
}
}
}
}
return SimType;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T09:06:52.440",
"Id": "28710",
"Score": "6",
"body": "Why do you need to eliminate the loop?"
}
] |
[
{
"body": "<pre><code>public bool CheckMobileSim(List<Mobile_Range> numberRange, string MobileNumber)\n{\n var digits = new List<long>();\n for (int i = 5; i < 10; i++)\n digits.Add(Convert.ToInt64(MobileNumber.Substring(0, i).ToString()));\n\n return numberRange != null &&\n numberRange.Any(nr => digits.Any(n => n >= nr.RangeStart && n < nr.RangeEnd));\n}\n</code></pre>\n\n<p>This way you don't need a loop but there is a loop behind.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T08:26:47.033",
"Id": "28708",
"Score": "0",
"body": "How can i handle different \"Number\" in the same code(9/8/7/6/5 digits)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T09:10:03.473",
"Id": "28711",
"Score": "0",
"body": "Edited my answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T08:08:39.460",
"Id": "18010",
"ParentId": "18008",
"Score": "0"
}
},
{
"body": "<p>Refactoring step 1, remove unnecessary variables and braces and return early</p>\n\n<pre><code>public bool CheckMobileSim(List<Mobile_Range> numberRange, string MobileNumber)\n{\n if(numberRange == null)\n return;\n string NineDigits = MobileNumber.Substring(0, 9).ToString();\n long Number = Convert.ToInt64(NineDigits);\n for (int i = 0; i < numberRange.Count; i++)\n if ((Number >= numberRange[i].RangeStart && Number < numberRange[i].RangeEnd))\n return true;\n\n return false;\n}\n</code></pre>\n\n<p>I realize that breaks with the \"single point of return\" wisdom but I'm not a big fan. When you have small functions like this one, it doesn't make all that much sense.</p>\n\n<p>Refactoring step 2, with that cleaned up it's easy to see how this fits into a simple LINQ query</p>\n\n<pre><code>public bool CheckMobileSim(IEnumerable<Mobile_Range> numberRange, string mobileNumber)\n{\n if(numberRange == null || String.IsNullOrWhitespace(mobleNumber))\n return false;\n\n var nineDigits = mobileNumber.Substring(0, 9);\n var number = Convert.ToInt64(nineDigits);\n\n return numberRange.Any(n => number >= n.RangeStart && number < n.RangeEnd);\n}\n</code></pre>\n\n<p>Since this is a public method I added some checks and downcast List to IEnumerable, which is a looser contract and all you really need here.</p>\n\n<p>By the way, .Net naming conventions are pascalCase for private and local variables CamelCase for public and protected. It's rare to use underscores.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T09:21:22.547",
"Id": "28731",
"Score": "1",
"body": "That's a nice answer but; `String.Substring` method already returns a string, you don't need to call `ToString` after that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T11:35:23.043",
"Id": "28736",
"Score": "0",
"body": "You should a) check that `mobileNumber` is at least 9 characters long or your Substring call is going to throw an exception and b) use `long.TryParse` instead of `Convert.ToInt54` as that can also throw an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T11:38:07.940",
"Id": "28738",
"Score": "1",
"body": "You should use brackets around one-line `for`s, `if`s, etc. Otherwise indentation errors like the one you did will induce errors/bugs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:10:55.300",
"Id": "28747",
"Score": "0",
"body": "@ANeves - You're right, I did have an unnecessary indentation in the first example. Fortunately this is C#, not coffescript, the syntax of this is unambiguous; there will never be an error due to indentation. As for single line vs brackets, I prefer to minimize most noise - especially needless vertical whitespace - which can cause important code to be pushed offscreen. There are of course many, many exceptions but when the choice is between using two semantically meaningless lines or not I prefer to go with the later. I find it powerful when combined with small methods and returning early."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T15:16:45.673",
"Id": "28758",
"Score": "0",
"body": "The syntax is unambiguous, but our reading/understanding of it is not. I understand what you say and you are right, but I prefer the brackets there - I find it adds to the reliability of the code. Microsoft's coding conventions agree with me and suggest to [`use parentheses to make clauses in an expression apparent`](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T15:32:33.340",
"Id": "28759",
"Score": "1",
"body": "@ANeves - that's fair. Like I said, I disagree with the guidance in a majority of the cases but in this one I can agree that use of braces could have helped readability. Then again you're talking about an intermediate step, not the final solution, I almost never would actually use a `for` loop much less an `if` inside of one :P"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T15:20:59.157",
"Id": "18013",
"ParentId": "18008",
"Score": "1"
}
},
{
"body": "<p>You can improve it like this:<br>\n<em>(I talked about why I did the changes I made, below the code)</em></p>\n\n<pre><code>public bool CheckMobileSim(IEnumerable<MobileRange> numberRange, string mobileNumber)\n{\n // Sanity checks: You can return false instead of throwing exceptions if you'd like to.\n if (numberRange == null)\n throw new ArgumentNullException(\"numberRange\");\n\n if (mobileNumber == null)\n throw new ArgumentNullException(\"mobileNumber\");\n\n // More sanity checks: You need to be sure that mobileNumber has at least nine\n // characters that can be converted to a 64 bit integer.\n if (mobileNumber.Length < 9)\n return false;\n\n long number;\n if (!long.TryParse(mobileNumber.Substring(0,9), out number))\n return false;\n\n // You can avoid writing the loop yourself and use LINQ instead.\n return numberRange.Any(r => number >= r.RangeStart && number < r.RangeEnd);\n}\n</code></pre>\n\n<p>Although <code>Enumerable.Any</code> extension method I have used above will <em>essentially</em> do the same thing with:</p>\n\n<pre><code>foreach (var item in numberRange)\n if (number >= item.RangeStart && number < item.RangeEnd)\n return true;\n\nreturn false;\n</code></pre>\n\n<p>Why did I change the type of <code>numberRange</code>?</p>\n\n<ul>\n<li>Because an <code>IList<T></code> is not needed unless you want to manipulate the collection. If all you want to do is to enumerate it, then an <code>IEnumerable<T></code> would be sufficient. With this signature, you can pass your <code>List<T></code> instance <em>or any other <code>IEnumerable<T></code> instance</em> (an array or a <code>HashSet<T></code> for example) to this method.</li>\n</ul>\n\n<p>Why did I threw exceptions in first two sanity checks and returned false in others?</p>\n\n<ul>\n<li>Because <em>most of the time</em> a null parameter means there is something wrong in your code whereas an empty collection does not. I suggest passing the <code>mobileNumber</code> as <code>Int64</code>, avoiding its conversion in this method entirely.</li>\n</ul>\n\n<p>Why did I change your variable names?</p>\n\n<ul>\n<li>For readability:<br>\nSee <a href=\"http://msdn.microsoft.com/en-us/library/x2dbyw72%28v=vs.71%29.aspx\" rel=\"nofollow noreferrer\">Capitalization Styles</a> section in MSDN's <a href=\"http://msdn.microsoft.com/en-us/library/xzf533w0%28v=vs.71%29.aspx\" rel=\"nofollow noreferrer\">Naming Guidelines for Class Library Developers</a> page.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T08:55:29.180",
"Id": "18032",
"ParentId": "18008",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T07:57:36.623",
"Id": "18008",
"Score": "2",
"Tags": [
"c#",
"asp.net",
"validation"
],
"Title": "Checking mobile SIMs"
}
|
18008
|
<p>I am developing a BlackJack game using Java, and it came to a point that I am using <code>instanceof</code> operator to determine if it is a type of some subclass.</p>
<p>Here's an example:</p>
<pre><code>public void checkForBlackJack(Player player) {
Hand fHand = player.getHands().get(0);
if (fHand.getCardScore() == 21) {
fHand.setBlackjack(true);
}
if(player instanceof BlackJackPlayer){
BlackJackPlayer bjplayer = (BlackJackPlayer) player;
if(bjplayer.isSplit()){
//Check the users other hand if it is already blackjacked
}
}
}
</code></pre>
<p>Is using <code>instanceof</code> considered to be bad for such example? Just as an overview, here is my class diagram:</p>
<p><img src="https://i.stack.imgur.com/XnbBK.png" alt="enter image description here"></p>
<p>I've decided to use <code>instanceof</code> to check for blackjack because The Dealer can also get blackjack.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T10:46:48.823",
"Id": "28808",
"Score": "0",
"body": "In the most of the cases you can get rid of `instanceof` by implementing the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern). But this would be a bit over-engineered in your case."
}
] |
[
{
"body": "<p>why don't you declare a function for both types of <code>Player</code>?</p>\n\n<pre><code>public void checkForBlackJack(BlackJackPlayer blackjackplayer) {\n // ....\n }\n\npublic void checkForBlackJack(BlackJackDealer blackjackdealer) {\n // ....\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T10:07:47.973",
"Id": "28713",
"Score": "0",
"body": "if I did that I would be repeating myself, since both has the sample implementation the only difference is that the BlackJackPlayer can Have two hands."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T13:58:51.537",
"Id": "29094",
"Score": "0",
"body": "@user962206 You can extract everything in common into a separate method called from these two."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T08:46:06.283",
"Id": "18011",
"ParentId": "18009",
"Score": "1"
}
},
{
"body": "<p>In this case you could push the <code>isSplit</code> method to the Player class and implement it with <code>return false;</code>. Then the need to <code>instanceof</code> disappears. </p>\n\n<p>I wouldn't say that it is bad to use instanceof but often there are other options that are better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T15:28:51.393",
"Id": "18014",
"ParentId": "18009",
"Score": "4"
}
},
{
"body": "<p>In your case, it seems like the <code>checkForBlackJack</code> method lives in the wrong place (I am guessing a class containing game logic). If you move<sup>1</sup> that method to the Player class you can then get rid of the conditional logic by breaking it out to an abstract method. This is commonly referred to as \"replace-conditional-with-polymorphism\"<sup>2</sup>. In case you have common behaviour in the two subclasses, you can put that behaviour in the base class instead of making that one abstract (so you won't have to repeat yourself).</p>\n\n<p><sup>1</sup>: <a href=\"http://sourcemaking.com/refactoring/move-method\" rel=\"nofollow\">move method</a></p>\n\n<p><sup>2</sup> <a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">replace conditional with polymorphism</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T18:29:45.420",
"Id": "18219",
"ParentId": "18009",
"Score": "2"
}
},
{
"body": "<p>As a first pass at a refactor, I would structure your code like this:</p>\n\n<pre><code>public class Player {\n public boolean hasBlackJack() {\n // Handle stuff outside of your \"if instanceof\" above\n }\n}\n\npublic class BlackJackDealer extends Player {\n // Other methods, not overriding hasBlackJack method\n}\n\npublic class BlackJackPlayer extends Player {\n @Override\n public boolean hasBlackJack() {\n super();\n // Handle stuff inside your \"if instanceof\" above\n }\n}\n</code></pre>\n\n<p>Though this does get rid of the instanceof, the real reason I prefer it is a little deeper. Who is responsible for determining if a Player has a blackjack? The player of course! This is shown in your code when you're doing something like:</p>\n\n<pre><code>Hand fHand = player.getHands().get(0);\n</code></pre>\n\n<p>Woah; why is this Object reaching inside the Player object to get his hands out of there? Instead, ask the player object whether he has a blackjack, and proceed accordingly. Notice you can still have a \"GameRunner\" class responsible for deciding what to do next if the player has a blackjack (payout appropriately, remember betsize, etc), but checking if there is a blackjack is a question you can ask the Player object.</p>\n\n<p>Going a little bit further, this code seems dodgy to me:</p>\n\n<pre><code> if (fHand.getCardScore() == 21) {\n fHand.setBlackjack(true);\n }\n</code></pre>\n\n<p>An external entity shouldn't be telling the Hand that it is a blackjack and then mutating the Hand. Is there a situation where 21 is not a blackjack? If not, you can remove this call entirely and just use <code>getCardScore() == 21</code> to determine if it's a blackjack. If there is, then you can write the method <code>isBlackjack()</code> in the Hand class itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T06:45:37.470",
"Id": "18235",
"ParentId": "18009",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T08:00:21.420",
"Id": "18009",
"Score": "2",
"Tags": [
"java",
"design-patterns",
"playing-cards"
],
"Title": "Using Java's instanceof operator"
}
|
18009
|
<p>I have a <code>Value</code> class that may represent many different types:</p>
<pre><code>private BigInteger fNum;
private BigDecimal fReal;
private ArrayList<StaticValue> fArrayValues;
private int fArrayOffset;
private HashMapArray<String, StaticValue> fRecordValues;
private boolean fIsCharLiteral;
private int fEnumOrd;
private char fCharLiteral;
private File fFile;
private StaticValue fLeft, fRight, fAscending;
private boolean fIsBuiltinBool = false;
private boolean fTruthValue;
</code></pre>
<p>It implements integer, real, vertor, enumeration and boolean. Some of the fields, <code>fIsBuiltinBool</code> and <code>fIsCharLiteral</code> hint which type it implements. Instances are created like:</p>
<pre><code>public StaticValue(ValueBuilder aBuilder) {
super(aBuilder.getType());
fId = aBuilder.getId();
fIsCharLiteral = aBuilder.isCharLiteral();
fCharLiteral = aBuilder.getCharLiteral();
fEnumOrd = aBuilder.getEnumOrd();
fNum = aBuilder.getNum();
fFile = aBuilder.getFile();
fReal = aBuilder.getReal();
fLeft = aBuilder.getLeft();
fRight = aBuilder.getRight();
fAscending = aBuilder.getAscending();
TypeStatic type = aBuilder.getType();
switch (type.getCat()) {
case ARRAY:
fArrayOffset = init ...
fArrayValues = init...
case RECORD:
fRecordValues = new HashMapArray<String, StaticValue>();
init ...
case INTEGER:
if (fNum == null) throw Exception
break;
</code></pre>
<p>and methods are implemented conditionally, like </p>
<pre><code>public String toString() {
if (fIsBuiltinBool) {
return "" + fTruthValue;
}
try {
Type type = getType();
switch (type.getCat()) {
case ARRAY: show fArrayValues
case RECORD:
buf = new StringBuilder();
show fields
</code></pre>
<p>and so on. </p>
<p>Despite <a href="http://c2.com/cgi/wiki?SwitchStatementsSmell" rel="nofollow">promoters of OOP and design patterns state that OOP polymorphism is not any better than procedural case-based one</a>, it looked very ugly to me. Additionally, I felt like polymorphism can eliminate the switch checking overhead and reduce memory footprint. I mean that I have millions of Value objects. When every instance allocates 10 fields, it takes some memory. Because fields are mutually exclusive, 9 of 10 fields are useless for every specific value type, we can save considerable memory. More compact object models better fit the cache, so performance must also improve.</p>
<p>Improved cache efficiency will further improve performance in multithreaded application, where multiple processors compete for the computer bottleneck - the memory bus. The last motivation is debugging - when debugger displays the object fields, it is much easier to focus on substance when irrelevant fields are not shown. </p>
<p>This is how my polymorphic code looks like:</p>
<pre><code>public class StaticValue {
protected StaticValue(ValueBuilder aBuilder) {
type = aBuilder.getType();
fId = aBuilder.getId();
};
public static class INT extends StaticValue {
private BigInteger fNum;
public INT(ValueBuilder aBuilder) {
assert getType().isInteger();
super(aBuilder);
fNum = aBuilder.getNum();
assert fNum != null;
}
public String toString() { return fNum.toString()}
public static class REAL extends StaticValue {
private BigDecimal fReal;
public static class RECORD extends StaticValue {
private List<StaticValue> fields;
</code></pre>
<p>I did not expect any serious performance gain since the project is very large and there are many other objects besides <code>StaticValue</code>. Yet, I still was surprised (experimental results are recorded interleaving between versions, so please do not think that OOP was recorded in another machine state, loaded by another process, and sorted):</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Switches OOP
32.62 34.1
30.32 33.15
30.9 31.9
30.7 31.755
30.9 31.5
30.14 31.45
30.2 31.3
33 31.2
32.4 31.137
30.4 31
30.364 30.36
30.7 29.82
</code></pre>
</blockquote>
<p>Out of 30 seconds per test originally, the new test finished in 31 seconds! It is a miniscule but new test that takes longer! Why is there a penalty? Why does the (JVM/Win/personal) machine prefer the conditional programs? Should I commit the changes into repository and continue refactoring the code into polymorphism?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T23:13:55.490",
"Id": "28724",
"Score": "4",
"body": "Could you show a test too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T09:44:18.160",
"Id": "28733",
"Score": "0",
"body": "It is a set of integration tests of this very large project, http://zamiacad.sourceforge.net. Simulation tests run 30-33 seconds. So, 1 second is within the statistical uncertainty. However, I notice that conditional style fluctuations are generally 1 sec shorter. There is another test, that runs for 80 seconds and I get the same 1 second penalty. It is impossible to believe that this is a cost of loading 7 additional classes. I admit that polymorphism alone can run faster but, in the field, I am getting these results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T07:58:31.223",
"Id": "28944",
"Score": "0",
"body": "does the tests allow for a warm up of the JIT/Hotspot Compiler? If not the values aren't really relevant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T15:40:37.130",
"Id": "29354",
"Score": "0",
"body": "Of course they are irrelevant. Any data that shows something clearly and stably is irrelevant. Actually, it is your benchmark with heat up that is irrelevant. Eliminating heat up time from the benchmark deflects us away from what user will experience. We therefore also want to know whether OOP style favors the heat up time or degrades it ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T00:23:14.740",
"Id": "29592",
"Score": "1",
"body": "Could you please provide a direct WWW-link to this class in the repository, and to some other class where it's used? It'd help to know the full context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-23T10:39:48.900",
"Id": "236280",
"Score": "0",
"body": "Hello @Val! You received five answers. Would you please [accept](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) one of them? This gives you and the person with the accepted answer more reputation and gets this question off the list of unanswered questions. Thanks! :)"
}
] |
[
{
"body": "<p>In a first glance, having <code>StaticValueTypeXXX</code> for each type and puting them in a <em>Obervable/Observer</em> pattern puts the <code>ifTypeIs(..)</code> in the <em>Observers</em>, not in a huge switch in <em>Observable</em>.</p>\n\n<p>So you can reduce size of <em>Observers</em> [each <code>toString()</code> have small job to do with no test] <br>\nand hope for multithreading when <code>notifyObservers()</code> is activated.</p>\n\n<p><em>Edit after comment</em></p>\n\n<p>If the aim is to remove the <code>switch</code>, and with this, to have classes of different types with same named method loosely coupled (in place of one class multi-type, with polymorphism and a single method name), <br><em>Observalbe/Observer</em> is powerful (and speed, and maintenable) in many situations I've experimented when I had intricated <code>if</code> or <code>switch</code> on object's type (not on values), even if it not the the main usage of this pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T12:50:56.743",
"Id": "28742",
"Score": "0",
"body": "wait, Observable is related with event listening. What has it to do with the OOP replacing type switch -> polymorphism? What do I have to listen?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T15:08:47.510",
"Id": "28756",
"Score": "0",
"body": "@Val response in Edit"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T09:28:24.180",
"Id": "18033",
"ParentId": "18016",
"Score": "0"
}
},
{
"body": "<p>You might try making the StaticValue class be abstract, and have it include an abstract toString function. Doing this MAY reduce some internal JVM JiT compiler lookups... however that will depend on the particular JVM implementation and potentially the options you have set for it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T21:41:30.420",
"Id": "18096",
"ParentId": "18016",
"Score": "1"
}
},
{
"body": "<p>There are many possible reasons. I'd look into the following things:</p>\n\n<ul>\n<li><p>Memory footprint: You argued this should go down ... but you are creating extra objects so it might actually go up</p></li>\n<li><p>Lifespan of your objects. Are your objects created and garbage collected often? This might cause a gc overhead with more objects even when the total memory consumption is less.</p></li>\n<li><p>switch produces a pretty optimized byte code, the call to an overwritten method creates different byte code but has to include something similar to the switch as well. No idea which one is faster.</p></li>\n<li><p>Make sure the JVM has enough cycles to warm up. Otherwise any performance benchmarks are pretty much useless.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T14:10:43.150",
"Id": "28960",
"Score": "0",
"body": "Which extra objects I create? I just create appropriate slim object instead of fat ones. Why that should increase the lifetime? Why does warming up dislike OOP?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T12:26:07.770",
"Id": "29042",
"Score": "0",
"body": "The 'more' objects was a misunderstanding on my side. Your code is different so the Hotspot compiler will behave different. That's all. Warming up doesn't dislike OOP."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T08:03:50.893",
"Id": "18148",
"ParentId": "18016",
"Score": "4"
}
},
{
"body": "<p>Have you considered using Generic type attributes?</p>\n\n<pre><code>abstract class StaticValue<T> {\n T payload;\n //...\n}\n\nclass Real extends StaticValue<BigDecimal> { /*...*/ }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T17:24:07.270",
"Id": "29721",
"Score": "0",
"body": "It is a great idea. Though, it will not work if subtypes require type-specific behaviour and, secondly, does not answer my question, which is about performance. Otherwise, the idea is very good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T23:38:58.693",
"Id": "29745",
"Score": "0",
"body": "@Val Why wouldn't this approach work with type-specific behaviour? You just introduce \"`public abstract String doStuff();`\" method in the `StaticValue<T>` class, and then all the classes that extend it must implement their own, type-specific version of the `public String doStuff()` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T05:36:59.130",
"Id": "29768",
"Score": "0",
"body": "You can add type specific behaviour using [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T19:56:25.980",
"Id": "18558",
"ParentId": "18016",
"Score": "5"
}
},
{
"body": "<p>When you say your <code>Value</code> class can represent many data types, why don't you just use an <code>Object</code> class instead? That, too, can represent many data types. Then you could do something like this:</p>\n\n<pre><code>import java.math.BigDecimal;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class ConditionalsVsPolymorphism {\n\n // Here are your \"Values\", as Objects:\n private List values = new ArrayList();\n\n public static void main(String args[]) {\n ConditionalsVsPolymorphism instance = new ConditionalsVsPolymorphism();\n instance.run();\n }\n\n public ConditionalsVsPolymorphism() {\n Map<String, String> testMap = new HashMap<String, String>();\n testMap.put(\"stack\", \"overflow\");\n testMap.put(\"code\", \"review\");\n // Fill the array of values with some test data of different types:\n values.add(42);\n values.add(\"foobar\");\n values.add(true);\n values.add(testMap);\n values.add(new BigDecimal(1234567L));\n }\n\n public void run() {\n // toString works just fine without any tricks:\n for (Object object : values) {\n System.out.println(object.getClass() + \": \" + object);\n }\n\n // Casting the value of the object:\n for (Object object : values) {\n if (object instanceof Integer) {\n int myInt = Integer.class.cast(object);\n System.out.println(\"Cast to integer: \" + myInt);\n } else if (object instanceof String) {\n String myString = String.class.cast(object);\n System.out.println(\"Cast to string: \" + myString);\n } else if (object instanceof Boolean) {\n boolean myBool = Boolean.class.cast(object);\n System.out.println(\"Cast to boolean: \" + myBool);\n } else if (object instanceof Map) {\n Map myMap = Map.class.cast(object);\n System.out.println(\"Cast to map: \" + myMap);\n } else if (object instanceof BigDecimal) {\n BigDecimal myBigDecimal = BigDecimal.class.cast(object);\n System.out.println(\"Cast to BigDecimal: \" + myBigDecimal);\n }\n }\n }\n}\n</code></pre>\n\n<p>The code outputs:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>class java.lang.Integer: 42\nclass java.lang.String: foobar\nclass java.lang.Boolean: true\nclass java.util.HashMap: {code=review, stack=overflow}\nclass java.math.BigDecimal: 1234567\nCast to integer: 42\nCast to string: foobar\nCast to boolean: true\nCast to map: {code=review, stack=overflow}\nCast to BigDecimal: 1234567\n</code></pre>\n\n<p>Alternatively, if you still do want to keep your <code>Value</code> class because it contains some logic, you can do it like this: </p>\n\n<pre><code>public class Value {\n\n private Object value;\n\n public Value(Object val) {\n value = val;\n }\n\n @Override\n public String toString() {\n if (isInteger()) {\n return \"Integer: \" + value;\n } else if (isString()) {\n return \"String: \" + value;\n } else {\n return value.toString();\n }\n }\n\n public boolean isInteger() {\n return value instanceof Integer;\n }\n\n public boolean isString() {\n return value instanceof String;\n }\n\n // A main method for testing this class:\n public static void main(String[] args) {\n Value val1 = new Value(\"Hello\");\n Value val2 = new Value(1234);\n System.out.println(\"val1: \" + val1);\n System.out.println(\"val2: \" + val2);\n }\n}\n</code></pre>\n\n<p>This code outputs:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>val1: String: Hello\nval2: Integer: 1234\n</code></pre>\n\n<p>Finally, if <code>instanceof</code> gives you some performance problems, you may replace <code>object instanceof Integer</code> with <code>Integer.class.equals(object.getClass());</code>. Note, however, that in that case a <code>HashMap</code> does not equal a <code>Map</code>, so you need to test for instantiable types.</p>\n\n<p><strong>Edit/Add:</strong> As to your final wondering \"Why does the (JVM/Win/personal) machine prefer the conditional programs?\": I guess we can only deduce that switches have been optimized better than polymorphism in the VM. The <a href=\"http://docs.oracle.com/javase/specs/jvms/se7/jvms7.pdf\" rel=\"nofollow noreferrer\">JVM7 Specification</a>, for one, says that \"Because of its emphasis on int comparisons, the Java virtual machine provides a rich complement of conditional branch instructions for type int.\" If you read that document more carefully, it might reveal you some interesting details of the differences between the two approaches. In general, I don't think that question is well suited to the Code Review site anyway, I believe you'd be better off posting that one to <a href=\"https://softwareengineering.stackexchange.com/\">Programmers</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T12:39:32.757",
"Id": "29620",
"Score": "0",
"body": "You ask, \"why don't you just use an Object class instead?\" I can tell you that it is not mine design. I just try to fix it by converting into OOP. Ok? Now, can you tell me how your question answers mine?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T21:05:03.943",
"Id": "29660",
"Score": "0",
"body": "@Val Just read my other solution, starting with the sentence \"Alternatively, if you still do want to keep your Value class because it contains some logic, you can do it like this\". :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T17:15:17.760",
"Id": "29720",
"Score": "0",
"body": "Your \"Alternative\" is exactly the code that I want to convert into OOP. To understand that your answer has nothing to do with mine question, you must first look what the \"replace Conditional with Polymorphism\" means!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-15T23:35:10.373",
"Id": "29744",
"Score": "0",
"body": "@Val Yeah, I get that, but what if replacing conditionals with polymorphism isn't the optimal way to go here? You say your main issues with the current way are that it a) is ugly, b) allocates too much memory and c) is hard to debug. I think the approach I have presented in my answer tackles all those problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T00:07:49.897",
"Id": "29747",
"Score": "0",
"body": "@Val Also, please see my answer again, I have added a note to the end about the performance."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T01:12:24.953",
"Id": "18572",
"ParentId": "18016",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T15:44:02.780",
"Id": "18016",
"Score": "7",
"Tags": [
"java",
"performance"
],
"Title": "Value class representing different types"
}
|
18016
|
<p>I've successfully solved the <a href="http://code.google.com/codejam/contest/90101/dashboard#s=p0" rel="nofollow">Alien Languages problem for Google Code Jam</a> in Haskell:</p>
<p>The algorithm is trivial - turn the patterns into regular expressions and see how many of the known words match these expressions.</p>
<p>But - this has taken me far longer than I expected it to, and most of the time I was battling with getting my types correct. Which leaves me wondering whether there is something wrong with my understanding of functional programming.</p>
<pre><code>module Main where
-- http://code.google.com/codejam/contest/90101/dashboard#s=p0
-- Input and output with standard redirection operators
-- Unless otherwise indicated, all modules used are either bundled with
-- the Haskell Platform (http://hackage.haskell.org/platform/) or available
-- as a separate download from Hackage (http://hackage.haskell.org/).
import Data.List
import Text.Regex.Posix
import Data.String.Utils
numberOfMatches :: String -> [String] -> Int
numberOfMatches pattern = foldl' matches 0
where
matches acc word = if word =~ pattern' :: Bool
then acc + 1
else acc
pattern' = replace "(" "[" $ replace ")" "]" pattern
getResult :: String -> ([String], Int, [String]) -> ([String], Int, [String])
getResult pattern (w, count, accum) = (w, count - 1, res : accum)
where res = "Case #" ++ show count ++ ": " ++ show (numberOfMatches pattern w)
main :: IO ()
main = do
(header:xs) <- fmap lines getContents -- IO is a Functor.
let [_, d, n] = map read $ words header
let knownWords = take d xs
let patterns = drop d xs
let (_, _, results) = foldr getResult (knownWords, n, []) patterns
mapM_ putStrLn results
</code></pre>
<p>Which, for a test input of:</p>
<blockquote>
<pre><code>3 5 4
abc
bca
dac
dbc
cba
(ab)(bc)(ca)
abc
(abc)(abc)(abc)
(zyx)bc
</code></pre>
</blockquote>
<p>Yields the results:</p>
<blockquote>
<pre><code>Case #1: 2
Case #2: 1
Case #3: 3
Case #4: 0
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-08T11:53:23.983",
"Id": "29226",
"Score": "0",
"body": "As for \"most of the time I was battling with getting my types correct\" - it's common for beginners. My solution to it was just to keep writing programs until I learned the type system. So don't worry, it's normal."
}
] |
[
{
"body": "<p>A good rule of thumb is that you should only ever use <code>foldr</code> when you're really sure that your fold is not an instance of something simpler. In your case, the fold is doing pretty much exactly two things while traversing the pattern list:</p>\n\n<ol>\n<li>Keeping track of the \"case index\"</li>\n<li>Accumulating the result list</li>\n</ol>\n\n<p>The second should be easily recognisable as a <code>map</code> - maybe less obvious is that the first can just be written as a <code>zip</code> with an enumeration:</p>\n\n<pre><code>getResult :: [String] -> (Int, String) -> String\ngetResult w (count, pattern) =\n \"Case #\" ++ show count ++ \": \" ++ show (numberOfMatches pattern w)\n\nmain :: IO ()\nmain = do\n [...]\n let results = map (getResult knownWords) $ zip [1..n] patterns\n</code></pre>\n\n<p>Which is much easier to understand than trying to bend the fold to do the right thing.</p>\n\n<p>Also, just as a suggestion, here's <code>main</code> implemented in a more \"imperative\" (read: monadic) style. After all, Haskell is said to be the best imperative language ever invented, so we can do that proudly:</p>\n\n<pre><code>main :: IO ()\nmain = do\n [_, d, n] <- fmap (map read . words) getLine\n knownWords <- replicateM d getLine\n forM_ [1..n] $ \\count -> do\n pattern <- getLine\n let matches = numberOfMatches pattern knownWords\n putStrLn $ concat [\"Case #\", show count, \": \", show matches]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T17:22:55.140",
"Id": "28766",
"Score": "0",
"body": "Thanks very much - exactly what I need. You can probably see that I was trying to do something similar to your last suggestion, but I couldn't get the types to match. I should pay more attention to Control.Monad as well. I'm glad I learned about `replicateM` and `forM_`. I actually know the benefit of the underscore suffix as I used to get `[(), (), ()]` outputs when using `mapM` in `main` instead of `mapM_`. Thanks for the effort - I appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T15:51:18.567",
"Id": "18054",
"ParentId": "18017",
"Score": "4"
}
},
{
"body": "<p>You can use list length and an operator section to count matches:</p>\n\n<pre><code>numberOfMatches pattern = length . filter (=~ pattern')\n where\n pattern' = replace \"(\" \"[\" $ replace \")\" \"]\" pattern\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-08T16:11:25.363",
"Id": "18354",
"ParentId": "18017",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18054",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T16:02:11.197",
"Id": "18017",
"Score": "3",
"Tags": [
"haskell",
"programming-challenge"
],
"Title": "Google Code Jam - Alien Language"
}
|
18017
|
<p>Can anyone review my <code>addMatrix()</code> method to see if I am following the instructions correctly?</p>
<p>These are the instructions:</p>
<blockquote>
<p>This is a <code>public</code> method (I'm calling it <code>addMatrix()</code>) that has <em>only one parameter</em> for a <code>DoubleMatrix</code> to add this <code>doubMatrix</code> (not changing this <code>doubMatrix</code>) and the parameter's <code>doubMatrix</code> and return a new <code>DoubleMatrix</code> (you'll need a local 2-dim. array to store the result of adding and pass to the constructor).</p>
<p>Make sure you check if the dimensions of this <code>doubMatrix</code> and the parameter's <code>doubMatrix</code> are the same (if not, return a new <code>DoubleMatrix</code> calling the first constructor passing 1, 1).</p>
</blockquote>
<p>I think I wrote the part where it said calling first constructor passing 1,1 wrong.</p>
<pre><code>package homework3;
public class DoubleMatrix
{
private double[][] doubMatrix;
public DoubleMatrix()
{
int row;
int col;
if(row > 0 && col > 0)
{
makeDoubMatrix(1,1);
}
else
{
row = 1;
col = 1;
}
}
public DoubleMatrix(double[][] tempArray)
{
if(tempArray != null)
{
for(int i = 0; i < tempArray.length-1;i++)
{
if(tempArray[i].length == tempArray[i+1].length)
{
doubMatrix = tempArray;
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
public int getDim1()
{
return doubMatrix.length;
}
public int getDim2()
{
return doubMatrix[0].length;
}
private void makeDoubMatrix(int row, int col)
{
double[][] tempArray = new double[row][col];
for(int i = 0;i < tempArray.length;i++)
for(int j = 0;j < tempArray[i].length;j++)
{
tempArray[i][j] = Math.random() * (100);
} //end for
tempArray = doubMatrix;
}
public double[][] addMatrix(double[][] doubMatrix)
{
this. doubMatrix = doubMatrix;
double[][] tempArray = null;
if(this.doubMatrix.length == doubMatrix.length)
if(this.doubMatrix[0].length == doubMatrix[0].length)
{
for(int i = 0; i< this.doubMatrix.length;i++)
for(int j = 0; j< this.doubMatrix[i].length;j++ )
{
tempArray[i][j] = this.doubMatrix[i][j] + doubMatrix[i][j];// add two matrices
}//end for
}
else
{
return tempArray = new double[1][1];
}
return tempArray;
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>I think you should operate your matrices as objects, not as two-dimensional arrays, so you could change your method</p>\n\n<pre><code>public double[][] addMatrix(double[][] doubMatrix)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>public DoubleMatrix add(DoubleMatrix secondMatrix)\n</code></pre>\n\n<p>and use the object for further operations.</p></li>\n<li><p>Then your method</p>\n\n<pre><code>makeDoubleMatrix(int row, int col)\n</code></pre>\n\n<p>could be just a constructor:</p>\n\n<pre><code>public DoubleMatrix(int row, int col)\n</code></pre></li>\n<li><p>I really can't understand the purpose of the following code:</p>\n\n<pre><code>int row;\nint col;\nif(row > 0 && col > 0)\n</code></pre>\n\n<p>if you have no matrix params defined so:</p>\n\n<pre><code>public DoubleMatrix(){\n this(1,1);\n}\n</code></pre>\n\n<p>assuming that you will transform your <code>makeDoubleMatrix()</code> to constructor.</p></li>\n<li><p>After all this your failed dimension check could just return <code>new DoubleMatrix()</code> which will construct and new a 1x1 <code>DoubleMatrix</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T13:11:28.550",
"Id": "18042",
"ParentId": "18026",
"Score": "4"
}
},
{
"body": "<p>For clarity, I would combine the size check conditional, and further, move it to it's own method to make the code a bit more clear. Working with objects (as @Alex suggested), will make this much easier:</p>\n\n<pre><code>if(this.doubMatrix.length == doubMatrix.length)\n if(this.doubMatrix[0].length == doubMatrix[0].length) {\n // stuff\n}\n</code></pre>\n\n<p>Change to something like:</p>\n\n<pre><code>if(this.isSameSize(doubMatrix))\n{\n //stuff\n}\n\n// ...\n// later\npublic boolean isSameSize(DoubleMatrix doub) {\n return // Comparison of column and rows of backing arrays\n}\n</code></pre>\n\n<ul>\n<li><p>Also in your <code>addMatrix()</code> function, it looks like you are making some confusing/improper assignments:</p>\n\n<pre><code>this.doubMatrix = doubMatrix\n</code></pre>\n\n<p>...is overwriting your current <code>DoubleMatrix</code> backing array with the one you\nare passing into the method (the <code>this</code> keyword refers to the class' scope, not the method's scope). I would suggest simply renaming the <code>addMatrix()</code> parameter to something else so you don't have the confusion of working with <code>this.doubMatrix</code> and <code>doubMatrix</code>.</p></li>\n<li><p>Your <code>addMatrix()</code> result array (<code>tempArray</code>) is also initialized to <code>null</code> and never properly initialized before you start placing values there. That's going to throw a <code>NullPointerException</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T13:38:22.830",
"Id": "18045",
"ParentId": "18026",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18045",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T03:26:56.860",
"Id": "18026",
"Score": "3",
"Tags": [
"java",
"matrix",
"homework"
],
"Title": "addMatrix() method"
}
|
18026
|
<p>Im using Struts2 running in google app engine.</p>
<p>User can use their google and facebook account to login to the site. When a user login, i have:</p>
<pre><code>session.put("email", email);
</code></pre>
<p>When a user log-out, I have</p>
<pre><code>session.remove("email");
</code></pre>
<p>In Struts2 Action, I have the following:</p>
<pre><code>public class ChapterAction extends ActionSupport implements SessionAware{
private static final long serialVersionUID = 1L;
private Map<String, Object> session;
public Map<String, Object> getSession() {
return session;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public String add() throws Exception{
String email = (String) session.get("email");
if ( email == null)
return LOGIN;
//business logic here
return SUCCESS;
}
}
</code></pre>
<p>Please critic my code. Is the above usage of session OK and secure?</p>
<p>Thanks</p>
|
[] |
[
{
"body": "<p>Code looks good, But why not move this Part:</p>\n\n<pre><code>String email = (String) session.get(\"email\");\nif ( email == null)\n return LOGIN; \n</code></pre>\n\n<p>into an Interceptor? Or do you have only one relevant Action?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T12:55:28.190",
"Id": "18114",
"ParentId": "18029",
"Score": "4"
}
},
{
"body": "<p>You can probably drop the <code>getSession()</code> method. Both OGNL and the JSP EL have mechanisms for accessing the session directly and do not require a getter method on the action. I'm guessing that you just generated the getter along with the setter.</p>\n\n<p>Also, as jogep indicated, detecting the need to login would be better suited for an interceptor. <a href=\"https://stackoverflow.com/questions/5509606/sessions-in-struts2-application/5517526#5517526\">This answer on Stack Overflow</a> might help shed some light on how that works.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-08T15:20:16.673",
"Id": "18350",
"ParentId": "18029",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18114",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T06:42:33.070",
"Id": "18029",
"Score": "2",
"Tags": [
"java",
"google-app-engine",
"struts2"
],
"Title": "Session in Struts2 and Google App Engine"
}
|
18029
|
<p>Can you help me optimize the speed and security of my homepage?</p>
<p><em>(Link now dead - 2014/04/10 - <code>http://www.pixel-klicker.de</code>)</em></p>
<pre><code>var aktiv=0;
var red ;
var enable = [];
var count = 1;
var number = 0;
var Jetzt = 0;
var Start = 0;
var codes = [];
var xmlHttp;
function createXMLHttpRequestObject()
{
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = false;
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Fehler beim erzeugen des XMLHttpRequest Objekts");
else
return xmlHttp;
}
function process()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
xmlHttp.open("POST","ses.php",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // WICHTIG FUER POST !!!
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
setTimeout("process()",1000);
}
function setStart()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
var value="zeit="+ Start;
xmlHttp.open("post","set.php",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // WICHTIG FUER POST !!!
xmlHttp.send(value);
}
else
setTimeout("setStart()",1000);
}
function getStart()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
xmlHttp.open("post","get.php",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // WICHTIG FUER POST !!!
xmlHttp.onreadystatechange = handleServerResponse2;
xmlHttp.send(null);
}
else{
setTimeout("getStart()",1000);
}
}
function handleServerResponse2(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
hrgData = xmlDocumentElement.firstChild.data;
var anzahl = document.getElementById("anzahl").value;
if(aktiv==0 && anzahl==0){
if(Start != hrgData){
alert("Du elendiger Betrüger! Fang von vorne an, aber dieses mal ohne zu bescheissen!");
history.back();
}else{
finish();
}
}
}
else{
alert("Problem bei der Server Kommunikation: "+xmlHttp.statusText);
}
}
}
function handleServerResponse(){
var id;
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
hrgData = xmlDocumentElement.firstChild.data;
var bla = hrgData.split(",");
bla[0] = bla[0].substr(1);
bla[bla.length-1]= bla[bla.length-1].substr(0,bla[bla.length-1].length-1);
var foo = [];
for(var i = 0;i < bla.length;i++){
id = document.getElementById(i).value;
foo.push(id.toString());
}
if(foo.join("") != bla.join("")){
alert("Du elendiger Betrüger! Fang von vorne an, aber dieses mal ohne zu bescheissen!");
history.back();
}
}
else{
alert("Problem bei der Server Kommunikation: "+xmlHttp.statusText);
}
}
}
createXMLHttpRequestObject();
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function array_values(){
var values = [];
var sichtbar = array_bilden();
for(var i = 0; i < sichtbar.length; i++) {
var res = document.getElementById(sichtbar[i]).value;
values.push(res.toString());
}
return values;
}
function code(values){
var code = [];
for(var i = 0; i < 3;i++){
var number = Math.floor(Math.random() * values.length);
code.push(values[number].toString());
values.splice(number,1);
}
return code;
}
function swap(targetID) {
if(aktiv==1){
getStart();
var values = array_values();
var klick = document.getElementById(targetID).value;
if(codes[number-1] == klick){
setcounter()
process();
var anzahl = document.getElementById("anzahl").value;
var max_anzahl = document.getElementById("max_anzahl").value;
obj = document.getElementById(targetID);
obj.style.display = "none";
number++;
}
if(number == 4){
var values = array_values();
codes = code(values);
document.getElementById("foo").value = codes;
number = 1;
}
}
}
function array_bilden(){
var sichtbar = [];
var max_anzahl = document.getElementById("max_anzahl").value;
var strDisplay;
for (var i = 0; i< max_anzahl; i++){
// Falls der Brower die Methode "getComputetStyle" kennt (W3C-DOM)
if(window.getComputedStyle){
strDisplay = window.getComputedStyle(document.getElementById(i), "").getPropertyValue("display");
// Falls der Browser die Methode "currentStyle" kennt (neuere IEs)
}else if(document.getElementById(i).currentStyle){
strDisplay = document.getElementById(i).currentStyle.display;
}
if(strDisplay != "none") {
sichtbar.push(i.toString());
}
}
return sichtbar;
}
function setcounter(){
var anzahl = document.getElementById("anzahl").value;
anzahl = anzahl -1;
document.getElementById("anzahl").value = anzahl;
if(anzahl=== 0){
aktiv = 0;
}
}
function finish(){
aktiv = 0;
var time = document.getElementById("Zeit").value;
var lvl = document.getElementById("level").value;
document.getElementById("done_time").value = time;
document.getElementById("done_level").value = lvl;
document.getElementById("finish_form").submit();
} setStart();
var javascript_countdown = function () {
var time_left = 10; //number of seconds for countdown
var keep_counting = 1;
function countdown() {
document.getElementById("start").style.display ="none";
if(time_left < 2) {
keep_counting = 0;
}
time_left = time_left - 1;
}
function add_leading_zero( n ) {
if(n.toString().length < 2) {
return "0" + n;
} else {
return n;
}
}
function format_output() {
var hours, minutes, seconds;
seconds = time_left % 60;
minutes = Math.floor(time_left / 60) % 60;
hours = Math.floor(time_left / 3600);
return seconds;
}
function format_output2() {
var hours, minutes, seconds;
seconds = VergangeneZeit % 60;
minutes = Math.floor(VergangeneZeit / 60) % 60;
hours = Math.floor(VergangeneZeit / 3600);
return seconds;
}
function show_time_left() {
document.getElementById("javascript_countdown_time").innerHTML = format_output();//time_left;
}
function no_time_left() {
document.getElementById("javascript_countdown_time").style.display = "none";
document.getElementById("lvlanzeige").style.display = "none";
document.getElementById("start").style.display = "none";
aktiv = 1;
if(aktiv == 1){
Jetzt = new Date();
Start = Jetzt.getTime();
setStart();
if(number == 0){
var values = array_values();
codes = code(values);
document.getElementById("foo").value = codes;
number++;
}
window.setTimeout("ZeitAnzeigen()",1);
}
}
return {
count: function () {
countdown();
show_time_left();
},
timer: function () {
javascript_countdown.count();
if(keep_counting) {
setTimeout("javascript_countdown.timer();", 1000);
} else {
no_time_left();
}
},
init: function (n) {
time_left = n;
javascript_countdown.timer();
}
};
}();
function ZeitBerechnen()
{
var Jetzt2 = new Date();
return((Jetzt2.getTime() - Start)/1000);
}
function ZeitTausendstel()
{
var Jetzt3 = new Date();
return((Jetzt3.getTime() - Start)/10);
}
function ZeitAnzeigen()
{
var absSekunden = Math.round(ZeitBerechnen());
var tauSekunden = Math.round(ZeitTausendstel());
var relSekunden = absSekunden % 60;
var reltauSekunden = tauSekunden % 60;
var absMinuten = Math.round((absSekunden-30)/60);
var anzSekunden ="" + ((relSekunden > 9) ? relSekunden : "0" + relSekunden);
var anzMinuten ="" + ((absMinuten > 9) ? absMinuten : "0" + absMinuten);
document.getElementById("Zeit").value = anzMinuten + ":" + anzSekunden + ":" + reltauSekunden;
window.setTimeout("ZeitAnzeigen()",10);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T19:38:12.797",
"Id": "28768",
"Score": "0",
"body": "[JSLint](http://www.jslint.com/) is a good starting point for JavaScript. It will flag up quite a few issues. In particular, it's complaining about references before definitions; and about the use of `==`."
}
] |
[
{
"body": "<ul>\n<li>Don't mix German and English code. I'd highly suggest you to use only English in your code (and I'm German myself).</li>\n<li>Don't mix different variable naming styles and only use variable names starting with a capital letter for constructor function which must be used with the <code>new</code> prefix. A good practice is to adopt the convention of the language you use, in case of JS it would be camelCase. This is a good starter for JS code convention: <a href=\"http://javascript.crockford.com/code.html\">http://javascript.crockford.com/code.html</a></li>\n<li>When creating the XHR object prefer <code>XMLHttpRequest</code> and only fallback to <code>ActiveXObject</code> if the native one is not defined. The latter is only necessary in IE6.</li>\n<li><a href=\"http://jsbeautifier.org/\"><strong>Indent your code properly</strong></a></li>\n<li>Get rid of the duplicate code in <code>setStart</code> and <code>getStart</code>. Write a single function that sends your AJAX request.</li>\n<li><strong>Never</strong> pass a string to <code>setInterval()</code> or <code>setTimeout()</code>. Doing so is as bad as using <code>eval()</code> and it results in unreadable and possibly insecure code as soon as you use variables since you need to insert them into the string instead of passing the actual variable. The proper solution is <code>setInterval(function() { /* your code *) }, msecs);</code>. The same applies to <code>setTimeout()</code>. If you just want to call a single function without any arguments, you can also pass the function name directly: <code>setInterval(someFunction, msecs);</code> (note that there are <strong>no</strong> <code>()</code> behind the function name)</li>\n<li>Consider using a DOM abstraction library. jQuery is nice and common but there are also more lightweight alternatives (not that I'd prefer these). It will save you a lot time and is likely to make your code much nicer.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T12:23:19.043",
"Id": "18041",
"ParentId": "18037",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T11:02:28.013",
"Id": "18037",
"Score": "3",
"Tags": [
"javascript",
"optimization",
"beginner",
"security",
"ajax"
],
"Title": "Efficient (Virtual) Home Security"
}
|
18037
|
<p>I posted the following code <a href="https://codereview.stackexchange.com/questions/17992/request-for-help-to-tidy-up-code-involving-arrays-and-for-statements">on here a few days ago</a>:</p>
<pre><code>public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random();
int[] arrayOfGenerator = new int[100];
int[] countOfArray = new int[10];
int count;
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
{
count = numberGenerator.nextInt(10);
countOfArray[count]++;
arrayOfGenerator[countOfGenerator] = count + 1;
}
int countOfNumbersOnLine = 0;
for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
{
if (countOfNumbersOnLine == 10)
{
System.out.println("");
countOfNumbersOnLine = 0;
countOfOutput--;
}
else
{
if (arrayOfGenerator[countOfOutput] == 10)
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
else
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
}
}
System.out.println("");
System.out.println("");
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
System.out.println("The number " + (countOfNumbers + 1)
+ " occurs " + countOfArray[countOfNumbers] + " times.");
System.out.println("");
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
if (countOfNumbers != 9)
System.out.print((countOfNumbers + 1) + " ");
else
System.out.print((countOfNumbers + 1) + " ");
for (int a = 0; a < countOfArray[countOfNumbers]; a++)
{
System.out.print("*");
}
System.out.println("");
}
System.out.println("");
int max = 0;
int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] > max)
{
max = countOfArray[counter];
test = counter + 1;
}
}
System.out.println("The number that appears the most is " + test);
}
}
</code></pre>
<p>I posted it for help on how to tidy it up - the suggestion I got was to add methods to break the code down into more manageable, testable sections.
However, despite spending the best part of two days trying, I can't get my head around how to do this. Everytime I try, I either generate compile-time or run-time errors.</p>
<p>Would anyone mind showing me even one or two of the methods I could use, so I can work from that?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T13:39:20.537",
"Id": "28744",
"Score": "0",
"body": "Maybe try to do it in very small steps? And make sure that each step doesn't break anything. [The other question](http://codereview.stackexchange.com/questions/17992/request-for-help-to-tidy-up-code-involving-arrays-and-for-statements) may give inspiration to the next helper in line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:40:59.483",
"Id": "28752",
"Score": "0",
"body": "@froderik: I posted a solution I came up with using methods. I am sure it's still inefficient, but it'll do for now! Thanks for your help on both this thread and the previous one."
}
] |
[
{
"body": "<p>After stressing about it for about two hours, I got the methods sorted, so I'll answer my own question. Please note - I'm just a beginner and I'm sure there are plenty of things that could be done even more efficiently!</p>\n\n<pre><code>import java.util.Random;\n// Imports Java random number generator.\n\npublic class Practical4_Assessed_with_Methods \n{\nstatic int[] randomNumbers = new int[100];\nstatic int[] countNumbers = new int[10];\n// Two arrays declared, one to hold 100 elements, the other 10.\n\npublic static void main(String[] args) \n{\n programExplanation();\n generateNumbers(randomNumbers, countNumbers);\n printNumbers(randomNumbers);\n generateNumberOfOccurences(countNumbers);\n generateAsteriskPattern(countNumbers);\n findMaxValues(countNumbers);\n // Code is broken down into five method calls (to make each section more manageable and testable).\n}\n\nstatic void programExplanation()\n{\n System.out.println(\"This program will generate 100 random integers between 1 and 10. \" +\n \"It will then output them in rows of 10.\");\n System.out.println(\"Following this, it will output how often each integer occured in \" +\n \"the array.\");\n System.out.println(\"It will also output this information in a horizontal bar chart of \" +\n \"asterisks.\");\n System.out.println(\"Finally, it will output which number, or numbers appeared most often\");\n System.out.println(\"\");\n}\n\nstatic void generateNumbers(int[] arrayOfGenerator, int[] countArray)\n{\n Random numberGenerator = new Random ();\n for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++) // For loop continues 100 times.\n {\n int count = numberGenerator.nextInt(10);\n countArray[count]++;\n arrayOfGenerator[countOfGenerator] = count + 1;\n }\n /* A random number (from 0 and 9) is generated and stored in count.\n * Whatever number is generated, that element number of countArray is incremented by 1.\n * E.g. If random number generated = 4, fourth element of countArray (i.e. element 3) is increased by 1.\n * The element of arrayOfGenerator (determined by the loop) is given the value of count + 1.\n * This is because the numberGenerator creates integers from 0 and 9 - we want from 1 and 10.\n\n * This coding is beneficial as both arrays are filled at the same time, which saves processing time.\n */\n}\n\nstatic void printNumbers(int[] arrayOfGenerator)\n{\n int countOfNumbersOnLine = 0;\n for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)\n {\n if (countOfNumbersOnLine % 10 == 0)\n System.out.println(\"\");\n // Takes a new line when 10 integers have been printed on a line.\n\n if (arrayOfGenerator[countOfOutput] == 10)\n {\n System.out.print(arrayOfGenerator[countOfOutput] + \" \");\n countOfNumbersOnLine++;\n }\n else\n {\n System.out.print(arrayOfGenerator[countOfOutput] + \" \");\n countOfNumbersOnLine++;\n }\n\n }\n /* Used to calculate the amount of integers on a line and the spacing between them.\n * If the arrayOfGenerator is 10, it takes two spaces, else it takes 3 spaces (to ensure proper spacing).\n * This is needed because the numeral 10 has two characters, as opposed to 1-9.\n */\n\n System.out.println(\"\");\n System.out.println(\"\");\n}\n\nstatic void generateNumberOfOccurences(int[] countOfArray)\n{\n for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)\n System.out.println(\"The number \" + (countOfNumbers + 1) + \" occurs \" + countOfArray[countOfNumbers] + \" times.\");\n System.out.println(\"\");\n /* For loop continues for entire length of countOfArray (i.e. 10 times)\n * Prints out how often each random number occured.\n */\n}\n\nstatic void generateAsteriskPattern(int[] countOfArray)\n{\n for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)\n {\n if (countOfNumbers != 9)\n System.out.print((countOfNumbers + 1) + \" \");\n else\n System.out.print((countOfNumbers + 1) + \" \");\n\n for (int asteriskCount = 0; asteriskCount < countOfArray[countOfNumbers]; asteriskCount++)\n System.out.print(\"*\");\n System.out.println(\"\");\n }\n System.out.println(\"\");\n /* For loop continues for entire length of countOfArray (i.e. 10 times)\n * First if/else statement determines how many spaces are taken after numeral and before asterisks.\n * This is used to ensure all asterisks are vertically aligned when output.\n * Second for statement runs on each element of countOfArray, outputting asterisks for as long as array lasts. \n * For example, if element 0 has the value 3, 3 asterisks are output. \n */\n}\n\nstatic void findMaxValues(int[] countOfArray)\n{\n int max = 0;\n for (int counter = 0; counter < countOfArray.length; counter++)\n {\n if (countOfArray[counter] > max)\n {\n max = countOfArray[counter];\n }\n }\n\n System.out.print(\"Number(s) that appears the most:\");\n /* For loop continues for entire length of countOfArray (i.e. 10 times) and compares each value to max.\n * If value compared is larger than the max value, it becomes new max value.\n * By the end of this loop, largest value in the array is stored in max. \n */\n\n for(int checkValue = 0; checkValue < countOfArray.length; checkValue++)\n if(countOfArray[checkValue] == max)\n System.out.print(\" \" + (checkValue + 1));\n System.out.print(\".\");\n /* For loop continues for entire length of countOfArray (i.e. 10 times)\n * If value of element scanned is equal to the value in max, it is output. \n */\n}\n}\n</code></pre>\n\n<p>Andrew</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:49:27.563",
"Id": "28753",
"Score": "0",
"body": "way to go. much easier to understand now!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T21:41:41.197",
"Id": "48673",
"Score": "1",
"body": "comment before the code not after, it is easier to read and understand. Overall very good improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T11:38:49.320",
"Id": "76900",
"Score": "0",
"body": "@niks: Given your language, you'll likely be banned from here too. On the site I posted under your answer advice on how to improve your future posts. I suggest you clean up your language and follow it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:39:59.297",
"Id": "18050",
"ParentId": "18038",
"Score": "4"
}
},
{
"body": "<p>(I am not yet allowed to make a comment, this post refers to the authors answer)</p>\n\n<p>Be careful with code comments. I do not like the \"comment as much as possible\" way, this way has some serious flaws.</p>\n\n<p>In your example, you should not add trivial comments. You do not have to write <code>For loop continues for entire length of countOfArray</code>, because this is clear from the loop body. Or <code>// Imports Java random number generator.</code>. This is clearly stated in the code before.<br>\nI would advise to put the comments above the corresponding lines of code.</p>\n\n<p>You should only add comments, if non trivial things are happening. Even more, a huge amount of comments is a sign that this part of code should perhaps be changed to make it more clear.</p>\n\n<p>If you want to test your methods (as stated in one comment), you should not do a print to sys.out inside it. It is very hard to test this things (You have to redirect sys.out or catch it somewhere else). But well, one can discuss if this is necessary in this small exercise.</p>\n\n<p>For <code>generateNumberOfOccurences</code> and <code>generateAsteriskPattern</code> I would use <code>print</code> instead of <code>generate</code> as for <code>printNumbers</code>, because this describes what is happening inside.</p>\n\n<p>Perhaps you want to think about making it more flexible. You should prefer a <code>List</code> instead of an <code>Array</code>. You could use <code>StringBuilder</code> instead of String concatenation with the <code>+</code>. You could use a <code>Map</code> to calculate the occurrences.</p>\n\n<p>If you are interested, I have appended a fast typed down implementation (this means, it does not check for all possible problems or caveats). You can scroll around and get some ideas how to handle some things. But be aware, that not everything is necessarily the best way. It mostly reflects my own experience.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Random;\n\npublic class test {\n public static void main(final String[] args) {\n final int amountOfNumbers = 100;\n final int randomStart = 1;\n final int randomEndInclusive = 10;\n final List<Integer> randomNumbers = getRandomNumbers(amountOfNumbers, randomStart, randomEndInclusive);\n\n final int columnsPerLine = 10;\n System.out.println(getTableAsString(randomNumbers, columnsPerLine));\n\n final Map<Integer, Integer> mapNumberToOccurence = getOccurenceMap(randomNumbers);\n\n System.out.println(getOccurenceAsString(mapNumberToOccurence));\n\n final String chartIndicator = \"*\";\n System.out.println(getOccurenceChartAsString(mapNumberToOccurence, chartIndicator));\n\n System.out.println(getHighestAppearanceAsString(mapNumberToOccurence));\n }\n\n private static List<Integer> getRandomNumbers(final int amountOfNumbers, final int randomStart, final int randomEndInclusive) {\n final List<Integer> result = new ArrayList<>();\n final Random random = new Random();\n final int randomEndExclusive = randomEndInclusive + 1 - randomStart;\n for (int i = 0; i < amountOfNumbers; i++)\n result.add(randomStart + random.nextInt(randomEndExclusive));\n return result;\n }\n\n private static String getTableAsString(final List<Integer> randomNumbers, final int columnsPerLine) {\n int counter = 0;\n int maxNumber = Integer.MIN_VALUE;\n for (final Integer randomNumbersItem : randomNumbers)\n maxNumber = Math.max(maxNumber, randomNumbersItem);\n final int maxWidth = String.valueOf(maxNumber).length();\n final String format = \" %\" + maxWidth + \"d\";\n final StringBuilder stringBuilder = new StringBuilder();\n for (final Integer randomNumbersItem : randomNumbers) {\n ++counter;\n stringBuilder.append(String.format(format, randomNumbersItem)).append(\" \");\n if (counter >= columnsPerLine) {\n stringBuilder.append(System.lineSeparator());\n counter = 0;\n }\n }\n return stringBuilder.toString();\n }\n\n private static Map<Integer, Integer> getOccurenceMap(final List<Integer> randomNumbers) {\n final Map<Integer, Integer> mapNumberToOccurence = new HashMap<>();\n for (final Integer randomNumbersItem : randomNumbers) {\n Integer occurence = mapNumberToOccurence.get(randomNumbersItem);\n if (occurence == null) occurence = 0;\n mapNumberToOccurence.put(randomNumbersItem, occurence + 1);\n }\n return mapNumberToOccurence;\n }\n\n private static String getOccurenceAsString(final Map<Integer, Integer> mapNumberToOccurence) {\n final List<Integer> allNumbers = new ArrayList<>(mapNumberToOccurence.keySet());\n Collections.sort(allNumbers);\n final StringBuilder stringBuilder = new StringBuilder();\n for (final Integer allNumbersItem : allNumbers)\n stringBuilder.append(\"The number \").append(allNumbersItem).append(\" occurs \").append(mapNumberToOccurence.get(allNumbersItem)).append(\" times.\")\n .append(System.lineSeparator());\n return stringBuilder.toString();\n }\n\n private static String getOccurenceChartAsString(final Map<Integer, Integer> mapNumberToOccurence, final String chartIndicator) {\n final List<Integer> allNumbers = new ArrayList<>(mapNumberToOccurence.keySet());\n Collections.sort(allNumbers);\n final int maxWidth = String.valueOf(allNumbers.get(allNumbers.size() - 1)).length();\n final String format = \" %\" + maxWidth + \"d\";\n final StringBuilder stringBuilder = new StringBuilder();\n for (final Integer allNumbersItem : allNumbers) {\n stringBuilder.append(String.format(format, allNumbersItem)).append(\": \");\n final int occurence = mapNumberToOccurence.get(allNumbersItem);\n for (int i = 0; i < occurence; i++)\n stringBuilder.append(chartIndicator);\n stringBuilder.append(System.lineSeparator());\n }\n return stringBuilder.toString();\n }\n\n private static String getHighestAppearanceAsString(final Map<Integer, Integer> mapNumberToOccurence) {\n int counter = 0;\n final String separator = \", \";\n final int highestAppearance = getHighestAppearance(mapNumberToOccurence);\n final StringBuilder stringBuilderNumbers = new StringBuilder();\n for (final Entry<Integer, Integer> mapNumberToOccurenceEntrySetItem : mapNumberToOccurence.entrySet()) {\n if (mapNumberToOccurenceEntrySetItem.getValue() == highestAppearance) {\n ++counter;\n stringBuilderNumbers.append(mapNumberToOccurenceEntrySetItem.getKey()).append(separator);\n }\n }\n\n if (counter == 0) return \"\";\n if (counter > 0) // we have results, remove the last separator\n stringBuilderNumbers.setLength(stringBuilderNumbers.length() - separator.length());\n final StringBuilder result = new StringBuilder(\"Number\");\n if (counter > 1) // we have more than 1 result, make it plural\n result.append(\"s\");\n result.append(\" that appear\");\n if (counter == 1) // we have 1 result, append the third person singular s\n result.append(\"s\");\n result.append(\" the most: \").append(stringBuilderNumbers).append(\".\");\n\n return result.toString();\n }\n\n private static int getHighestAppearance(final Map<Integer, Integer> mapNumberToOccurence) {\n int highestAppearance = Integer.MIN_VALUE;\n for (final Integer mapNumberToOccurenceValuesItem : mapNumberToOccurence.values())\n highestAppearance = Math.max(highestAppearance, mapNumberToOccurenceValuesItem);\n return highestAppearance;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T18:58:34.033",
"Id": "28822",
"Score": "0",
"body": "+1. In [my answer](http://codereview.stackexchange.com/questions/17992/request-for-help-to-tidy-up-code-involving-arrays-and-for-statements/18051#18051) to the [original question](http://codereview.stackexchange.com/q/17992/9390), I also suggested using a `Map`. I'd appreciate some feedback on that answer, actually, as it took a significant amount of time to write down."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:45:53.913",
"Id": "28830",
"Score": "0",
"body": "Unfortunately, I have not enough reputation here to make comments anywhere but my own answers :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T16:24:13.367",
"Id": "28997",
"Score": "0",
"body": "@codesparkle: Just letting you know that Uni work has gotten a bit hectic lately, and that's why I haven't responded to all your help. We've a uni project due on Wed, two practicals on Mon and two tests on Tues - I will get back to you though with how I've gotten on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T16:25:04.583",
"Id": "28998",
"Score": "0",
"body": "@tb-: Just letting you know my lecturer told me about the commenting and I've whacked it way down. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:16:47.760",
"Id": "29005",
"Score": "0",
"body": "@andrew no worries."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T18:46:49.007",
"Id": "18091",
"ParentId": "18038",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18050",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T11:04:17.490",
"Id": "18038",
"Score": "1",
"Tags": [
"java",
"array",
"classes"
],
"Title": "Request for help to tidy up code involving arrays and loops"
}
|
18038
|
<p>explain:</p>
<p><strong>from start day till now I've got 7.7 mb size, how long it will be to make it 10 gb size</strong></p>
<pre><code>open System
let dd = (DateTime.Now - DateTime.Parse("12/09/2012")).Days
let oneday = 7.7 / Convert.ToDouble(dd)
let in10gb = Convert.ToInt32( Math.Round (10.0 * 1024.0 / oneday) )
let years = Convert.ToInt32( Math.Round (float in10gb / 365.0) )
let mutable months = Convert.ToInt32( Math.Round (float (in10gb - years * 365) / 30.0) )
let days =
let d = in10gb - years * 365 - months * 30
if d > 0 then d else month = month - 1; (30 - d)
printf "%d years %d months %d days" years months days
Console.ReadKey() |> ignore
</code></pre>
<p>Also <code>/ 30.0</code> for months is dirty hack here... I'm not sure how to avoid it in easy way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:53:51.830",
"Id": "28754",
"Score": "0",
"body": "Be careful with things like `DateTime.Parse(\"12/09/2012\")`. They can give different results on different computes, due to culture settings."
}
] |
[
{
"body": "<p>I would propose an alternative method of calculating your time, using seconds and DateTimes:</p>\n\n<pre><code>open System\n\nlet startDate = DateTime.Parse (\"2012-09-12\")\nlet now = DateTime.Now;\nlet currentRuntime = (now - startDate).TotalSeconds\nlet timePerGig = currentRuntime / 7.7;\nlet tenDate = startDate + TimeSpan.FromSeconds (10.0 * timePerGig);\n</code></pre>\n\n<p>With that done, you can do whatever you like to represent the final date relative to the current date.</p>\n\n<p>An overly simplistic example is as follows:</p>\n\n<pre><code>printf \"%d years %d months %d days\" (finalDate.Year - now.Year) (finalDate.Month - now.Month) (finalDate.Day - now.Day)\n</code></pre>\n\n<p>Of course, you would have to account for roll-over for days and months in any final piece of code, but it illustrates how you could pull the date parts back out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T18:08:38.250",
"Id": "18055",
"ParentId": "18040",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18055",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T11:47:18.870",
"Id": "18040",
"Score": "1",
"Tags": [
"f#"
],
"Title": "TimeSpan don't support years so how do I deal with it? Is there could be smarter solution?"
}
|
18040
|
<pre><code>public bool CheckPlace(string State, string City)
{
TestDataContext data = new TestDataContext();
bool IsKochi = new bool();
if (!string.IsNullOrEmpty(State) && !string.IsNullOrEmpty(City))
{
var Place = (from a in data.Places where a.State == State || a.City == City select a.Place).ToList();
if (Place != null)
{
foreach (var placeName in Place)
{
if (placeName.ToString().ToLower() == "kochi")
{
IsKochi = true;
break;
}
else
{
IsKochi = false;
}
}
}
}
return IsKochi;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T22:51:37.157",
"Id": "28784",
"Score": "1",
"body": "`new bool()` is a very weird way to write `false`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-04T23:33:38.980",
"Id": "181559",
"Score": "1",
"body": "The title of your post should be the function/purpose of your code."
}
] |
[
{
"body": "<pre><code>public bool CheckPlace(string State, string City)\n{\n if (string.IsNullOrEmpty(State) || string.IsNullOrEmpty(City))\n {\n return false;\n }\n\n using (var data = new TestDataContext())\n {\n var ret = data.Places.Where(a => (a.State == State || a.City == City)).Select(a => a.Place).ToList().Any(x => x.ToString().ToLower() == \"kochi\");\n\n return ret;\n }\n}\n</code></pre>\n\n<p>If the Place have a string property what can be use at the \"is kochi\" check then use that in the Any() and leave out the .ToList().</p>\n\n<p>Instantiating the TestDataContext() in this method is bad (can not test the method) please inject it as method or class constructor parameter (you can inject a lambda for instantiating it also).</p>\n\n<p>(Syntax errors maybe exists in my code [powered by Notepad].)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T16:19:14.577",
"Id": "28763",
"Score": "0",
"body": "I like the short-circuiting in your first if statement. Concise and liable to save a lot of cycles depending on how complex the TestDataContext is."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:01:19.917",
"Id": "18047",
"ParentId": "18044",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p>Make <code>data</code> a parameter. This allows you to test the method without relying on a specific <code>Context</code> instance. You can wrap another method that passes in the default <code>Context</code>, but this way you are not tied to the specific implementation.</p></li>\n<li><p>Create a method that does the query on the data. This way you can have a simple method call that clear states what it is doing, instead of forcing someone to interpret the code. It also makes a long line of code shorter because it is on it's own and not in nested in an if block.</p></li>\n<li><p><code>bool</code> defaults to false. You don't have to keep setting <code>IsKochi</code> to false every time you don't find a match.</p></li>\n<li><p>The convention is that names of method variables are in lowerCamelCase, not UpperCamelCase.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T15:12:10.127",
"Id": "28757",
"Score": "1",
"body": "Just an FYI...This is called `camelCase` (first character lower case). This is called `PascalCase` (first character upper case)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:02:06.460",
"Id": "18048",
"ParentId": "18044",
"Score": "0"
}
},
{
"body": "<p>First of all, coding standards generally suggest that all local variables, including parameters, be camelCase. </p>\n\n<p>Here is a suggestion...</p>\n\n<pre><code>public bool CheckPlace(string state, string city)\n{\n TestDataContext data = new TestDataContext();\n bool isKochi = false;\n if (!string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(city))\n {\n isKochi = data.Places.Any(a => (a.State == state || a.City == city) && a.Place.ToLower() == \"kochi\");\n }\n\n return isKochi;\n}\n</code></pre>\n\n<p><code>.Any</code> returns true if there are any values in the collection based on the filter condition passed into the <code>.Any</code> clause</p>\n\n<p>Second,\nWhat is the type of <code>Place</code>. Is it a distinct list that can be turned into an enum? That could make it so you are not checking for a specific string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T14:06:58.823",
"Id": "18049",
"ParentId": "18044",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T13:23:42.703",
"Id": "18044",
"Score": "1",
"Tags": [
"c#",
"asp.net",
"linq"
],
"Title": "Can someone improve this code?"
}
|
18044
|
<p>The basic idea here is that I want to measure the number of seconds between two python datetime objects. However, I only want to count hours between 8:00 and 17:00, as well as skipping weekends (saturday and sunday). This works, but I wondered if anyone had clever ideas to make it cleaner.</p>
<pre><code>START_HOUR = 8
STOP_HOUR = 17
KEEP = (STOP_HOUR - START_HOUR)/24.0
def seconds_between(a, b):
weekend_seconds = 0
current = a
while current < b:
current += timedelta(days = 1)
if current.weekday() in (5,6):
weekend_seconds += 24*60*60*KEEP
a_stop_hour = datetime(a.year, a.month, a.day, STOP_HOUR)
seconds = max(0, (a_stop_hour - a).total_seconds())
b_stop_hour = datetime(b.year, b.month, b.day, STOP_HOUR)
if b_stop_hour > b:
b_stop_hour = datetime(b.year, b.month, b.day-1, STOP_HOUR)
seconds += (b - b_stop_hour).total_seconds()
return (b_stop_hour - a_stop_hour).total_seconds() * KEEP + seconds - weekend_seconds
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T01:04:19.407",
"Id": "461344",
"Score": "0",
"body": "What about other holidays? It sounds as if by excluding weekends you mean to exclude all free days. Note that in Arabic countries, Friday is not a work day, but sunday is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T01:38:14.433",
"Id": "461346",
"Score": "0",
"body": "@RolandIllig, good points, although my use case from 7 years ago wouldn't have been concerned about other possible holidays."
}
] |
[
{
"body": "<p>I think the initial calculation between the two dates looks cleaner using a generator expression + sum. The posterior correction is easier to understand if you do the intersection of hours by thinking in seconds of the day</p>\n\n<pre><code>from datetime import datetime\nfrom datetime import timedelta\n\nSTART_HOUR = 8 * 60 * 60\nSTOP_HOUR = 17 * 60 * 60\nKEEP = STOP_HOUR - START_HOUR\n\ndef seconds_between(a, b):\n days = (a + timedelta(x + 1) for x in xrange((b - a).days))\n total = sum(KEEP for day in days if day.weekday() < 5)\n\n aseconds = (a - a.replace(hour=0, minute=0, second=0)).seconds\n bseconds = (b - b.replace(hour=0, minute=0, second=0)).seconds\n\n if aseconds > START_HOUR:\n total -= min(KEEP, aseconds - START_HOUR)\n\n if bseconds < STOP_HOUR:\n total -= min(KEEP, STOP_HOUR - bseconds)\n\n return total\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T22:53:51.810",
"Id": "18899",
"ParentId": "18053",
"Score": "8"
}
},
{
"body": "<h3>1. Issues</h3>\n\n<p>Your code fails in the following corner cases:</p>\n\n<ol>\n<li><p><code>a</code> and <code>b</code> on the same day, for example:</p>\n\n<pre><code>>>> a = datetime(2012, 11, 22, 8)\n>>> a.weekday()\n3 # Thursday\n>>> seconds_between(a, a + timedelta(seconds = 100))\n54100.0 # Expected 100\n</code></pre></li>\n<li><p><code>a</code> or <code>b</code> at the weekend, for example:</p>\n\n<pre><code>>>> a = datetime(2012, 11, 17, 8)\n>>> a.weekday()\n5 # Saturday\n>>> seconds_between(a, a + timedelta(seconds = 100))\n21700.0 # Expected 0\n</code></pre></li>\n<li><p><code>a</code> after <code>STOP_HOUR</code> or <code>b</code> before <code>START_HOUR</code>, for example:</p>\n\n<pre><code>>>> a = datetime(2012, 11, 19, 23)\n>>> a.weekday()\n0 # Monday\n>>> seconds_between(a, a + timedelta(hours = 2))\n28800.0 # Expected 0\n</code></pre></li>\n</ol>\n\n<p>Also, you count the weekdays by looping over all the days between the start and end of the interval. That means that the computation time is proportional to the size of the interval:</p>\n\n<pre><code>>>> from timeit import timeit\n>>> a = datetime(1, 1, 1)\n>>> timeit(lambda:seconds_between(a, a + timedelta(days=999999)), number=1)\n1.7254137992858887\n</code></pre>\n\n<p>For comparison, in this extreme case the revised code below is about 100,000 times faster:</p>\n\n<pre><code>>>> timeit(lambda:office_time_between(a, a + timedelta(days=999999)), number=100000)\n1.6366889476776123\n</code></pre>\n\n<p>The break even point is about 4 days:</p>\n\n<pre><code>>>> timeit(lambda:seconds_between(a, a + timedelta(days=4)), number=100000)\n1.5806620121002197\n>>> timeit(lambda:office_time_between(a, a + timedelta(days=4)), number=100000)\n1.5950188636779785\n</code></pre>\n\n<h3>2. Improvements</h3>\n\n<p><a href=\"https://codereview.stackexchange.com/a/18899/11728\">barracel's answer</a> has two very good ideas, which I adopted:</p>\n\n<ol>\n<li><p>compute the sum in seconds rather than days;</p></li>\n<li><p>add up whole days and subtract part days if necessary.</p></li>\n</ol>\n\n<p>and I made the following additional improvements:</p>\n\n<ol>\n<li><p>handle corner cases correctly;</p></li>\n<li><p>run in constant time regardless of how far apart <code>a</code> and <code>b</code> are;</p></li>\n<li><p>compute the sum as a <code>timedelta</code> object rather than an integer;</p></li>\n<li><p>move common code out into functions for clarity;</p></li>\n<li><p>docstrings!</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<pre><code>from datetime import datetime, timedelta\n\ndef clamp(t, start, end):\n \"Return `t` clamped to the range [`start`, `end`].\"\n return max(start, min(end, t))\n\ndef day_part(t):\n \"Return timedelta between midnight and `t`.\"\n return t - t.replace(hour = 0, minute = 0, second = 0)\n\ndef office_time_between(a, b, start = timedelta(hours = 8),\n stop = timedelta(hours = 17)):\n \"\"\"\n Return the total office time between `a` and `b` as a timedelta\n object. Office time consists of weekdays from `start` to `stop`\n (default: 08:00 to 17:00).\n \"\"\"\n zero = timedelta(0)\n assert(zero <= start <= stop <= timedelta(1))\n office_day = stop - start\n days = (b - a).days + 1\n weeks = days // 7\n extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5\n weekdays = weeks * 5 + extra\n total = office_day * weekdays\n if a.weekday() < 5:\n total -= clamp(day_part(a) - start, zero, office_day)\n if b.weekday() < 5:\n total -= clamp(stop - day_part(b), zero, office_day)\n return total\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-16T06:22:34.960",
"Id": "298867",
"Score": "3",
"body": "This code is broken for a couple of cases, for instance if you give it a Monday and Friday in the same week it gives a negative timedelta. The issue is with the calculation of extra but I don't have a solution yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T00:52:42.630",
"Id": "461365",
"Score": "0",
"body": "@radman's comment on the error of Gareth Rees' is caused by 'extra' value.\nwhen the first day starts on Monday and ends on Friday or Saturday, this issue happens so need to adjust accordingly. so change `extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5` to `if a.weekday()==0 and (b.weekday()==4 or b.weekday()==5): extra = 5 else: extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T13:53:05.113",
"Id": "18912",
"ParentId": "18053",
"Score": "15"
}
},
{
"body": "<p>The code below is a bit of a hybrid between the two approaches mentioned. I think it should work for all scenarios. No work done outside working hours is counted.</p>\n\n<pre><code>from datetime import datetime\nfrom datetime import timedelta\n\ndef adjust_hour_delta(t, start, stop):\n\n start_hour = start.seconds//3600\n end_hour = stop.seconds//3600\n zero = timedelta(0)\n\n if t - t.replace(hour = start_hour, minute = 0, second = 0) < zero:\n t = t.replace(hour = start_hour, minute = 0, second = 0)\n elif t - t.replace(hour = end_hour, minute = 0, second = 0) > zero:\n t = t.replace(hour = end_hour, minute = 0, second = 0)\n # Now get the delta\n delta = timedelta(hours=t.hour, minutes=t.minute, seconds = t.second)\n\n return delta \n\ndef full_in_between_working_days(a, b):\n working = 0\n b = b - timedelta(days=1)\n while b.date() > a.date():\n if b.weekday() < 5:\n working += 1\n b = b - timedelta(days=1)\n return working\n\ndef office_time_between(a, b, start = timedelta(hours = 8),\n stop = timedelta(hours = 17)):\n \"\"\"\n Return the total office time between `a` and `b` as a timedelta\n object. Office time consists of weekdays from `start` to `stop`\n (default: 08:00 to 17:00).\n \"\"\"\n zero = timedelta(0)\n assert(zero <= start <= stop <= timedelta(1))\n office_day = stop - start\n working_days = full_in_between_working_days(a, b)\n\n total = office_day * working_days\n # Calculate the time adusted deltas for the the start and end days\n a_delta = adjust_hour_delta(a, start, stop)\n b_delta = adjust_hour_delta(b, start, stop)\n\n\n if a.date() == b.date():\n # If this was a weekend, ignore\n if a.weekday() < 5:\n total = total + b_delta - a_delta\n else:\n # We now consider if the start day was a weekend\n if a.weekday() > 4:\n a_worked = zero\n else:\n a_worked = stop - a_delta\n # And if the end day was a weekend\n if b.weekday() > 4:\n b_worked = zero\n else:\n b_worked = b_delta - start\n total = total + a_worked + b_worked\n\n return total\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-06T18:52:58.090",
"Id": "361239",
"Score": "0",
"body": "Testing this for these two dates, I get 1 working day when it should be 4: `2018-02-26 18:07:17` and\n`2018-03-04 14:41:04`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T08:10:32.243",
"Id": "461363",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-03T18:40:15.220",
"Id": "179542",
"ParentId": "18053",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18912",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T15:43:41.037",
"Id": "18053",
"Score": "22",
"Tags": [
"python",
"datetime"
],
"Title": "Seconds between datestimes excluding weekends and evenings"
}
|
18053
|
<p><a href="http://code.google.com/p/guava-libraries/" rel="nofollow">Guava</a> has a <a href="http://code.google.com/p/guava-libraries/issues/detail?id=872" rel="nofollow">feature request</a> which is asking to provide the ability to forget memoized value on a given supplier.</p>
<p>On top on that I needed another functionality where if during the calculation of expensive value another thread would invalidate the data, the memoisation should retry (guava <code>LoadableCache</code> doesn't provide this feature: invalidation during calculation is ignored).</p>
<p>I couldn't wait for this feature so I wrote this myself. First, an interface for forgettable supplier:</p>
<pre><code>public interface ForgettableSupplier<T> extends Supplier<T> {
public void forget();
}
</code></pre>
<p>Then, a base class, mostly taken from <a href="http://weblogs.java.net/blog/mason/archive/2006/09/rechecking_doub.html" rel="nofollow">here</a>:</p>
<pre><code>public abstract class DoubleCheck<T> extends ReentrantReadWriteLock {
protected abstract T create();
protected abstract T retrieve();
protected abstract boolean invalid(T value);
public T get() {
try {
readLock().lock();
T value = retrieve();
while (invalid(value)) { // this spins until no more invalidations are made
readLock().unlock();
writeLock().lock();
value = retrieve();
try {
if (invalid(value)) {
value = create();
}
} finally {
readLock().lock();
writeLock().unlock();
}
}
return value;
} finally {
readLock().unlock();
}
}
}
</code></pre>
<p>And finally, the static utility that combines everything together:</p>
<pre><code>public class Suppliers {
private Suppliers() {
}
public static <T> ForgettableSupplier<T> memoize(Supplier<T> delegate) {
return new ForgettableMemoizingSupplier<>(delegate);
}
private static final class ForgettableMemoizingSupplier<T> implements ForgettableSupplier<T> {
private final Supplier<T> delegate;
private volatile T t;
private final AtomicBoolean needsToBeForgotten = new AtomicBoolean(false);
private final DoubleCheck<T> doubleCheck = new DoubleCheck<T>() {
@Override
protected T create() {
needsToBeForgotten.set(false);
return ForgettableMemoizingSupplier.this.t = delegate.get();
}
@Override
protected T retrieve() {
return ForgettableMemoizingSupplier.this.t;
}
@Override
protected boolean invalid(final T t) {
return (ForgettableMemoizingSupplier.this.t == null) || needsToBeForgotten.get();
}
};
private ForgettableMemoizingSupplier(final Supplier<T> delegate) {
this.delegate = delegate;
}
@Override
public void forget() {
needsToBeForgotten.set(true);
}
@Override
public T get() {
return doubleCheck.get();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Class names should be nouns</a>. I'd rename <code>DoubleCheck</code> to <code>DoubleCheckedResource</code> or something similar.</p></li>\n<li><p><code>ForgettableMemoizingSupplier</code> should not allow <code>null</code> suppliers. You should check that and throw a <code>NullPointerException</code>.</p></li>\n<li><p>The name of the <code>invalid</code> method in the <code>DoubleCheck</code> class is ambiguous. Does it invalidate something or does it check that something is valid or not? It seems that the latter is true, so I'd call this <code>isInvalid</code> (or <code>isValid</code> to eliminate the negation).</p></li>\n<li><p>The <code>T t</code> field could be in the <code>DoubleCheck</code> anonymous subclass because this is the only class which uses it.</p></li>\n<li><p>Is <code>DoubleCheck</code> a <code>ReentrantReadWriteLock</code>? Currently it is. I think your clients should not be able to call <code>getOwner()</code>, <code>writeLock()</code> or <code>isFair()</code> on a <code>DoubleCheck</code> instance. I'd use composition instead of inheritance here:</p>\n\n<pre><code>public abstract class DoubleCheck<T> {\n\n private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();\n\n private final ReadLock readLock = lock.readLock();\n\n private final WriteLock writeLock = lock.writeLock();\n\n ...\n\n}\n</code></pre>\n\n<p>Check <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em>.</p></li>\n<li><p>The <code>get</code> method with the <code>lock()</code> call in the <code>finally</code> block smells a little bit. Are you sure that the object will always be in a consistent state? What happens when <code>retrieve()</code>, <code>create()</code> or <code>invalid()</code> throws an exception? Will all locks be released properly? </p>\n\n<p>If I'm right the following is the same but use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html\">usual <code>lock(); try { use() } finally { unlock(); }</code> construction</a>:</p>\n\n<pre><code>public T get() {\n readLock.lock();\n try {\n final T value = retrieve();\n if (!isInvalid(value)) {\n return value;\n }\n } finally {\n readLock.unlock();\n }\n\n writeLock.lock();\n try {\n T value = retrieve();\n while (isInvalid(value)) { // this spins until no more invalidations\n // are made\n value = retrieve();\n if (isInvalid(value)) {\n value = create();\n }\n }\n return value;\n } finally {\n writeLock.unlock();\n }\n}\n</code></pre>\n\n<p>(Please note that in the original code between the <code>readLock.unlock()</code> and <code>writeLock.lock()</code> calls another threads could get the read lock, therefore more than one thread could acquire the write lock at the same time.)</p></li>\n<li><p>If you can ignore the <code>forget</code> calls which are parallel with <code>get</code> calls it could be more simple:</p>\n\n<pre><code>public T get() {\n readLock.lock();\n try {\n final T value = retrieve();\n if (!isInvalid(value)) {\n return value;\n }\n } finally {\n readLock.unlock();\n }\n\n writeLock.lock();\n try {\n T value = retrieve();\n if (!isInvalid(value)) {\n return value;\n }\n return create();\n } finally {\n writeLock.unlock();\n }\n}\n</code></pre>\n\n<p>(Here <code>if (isValid(value))</code> would be more natural than the current <code>if (!isInvalid(value) ...</code>.)</p></li>\n<li><p>I'd consider using an <code>AtomicReference</code> and a simple <code>ReentrantLock</code> too:</p>\n\n<pre><code>public final class ForgettableMemoizingSupplier<T> \n implements ForgettableSupplier<T> {\n\n private final Supplier<T> delegate;\n\n private final AtomicReference<T> resourceRef = new AtomicReference<T>(); \n\n private final ReentrantLock lock = new ReentrantLock();\n\n public ForgettableMemoizingSupplier(final Supplier<T> delegate) {\n this.delegate = checkNotNull(delegate, \"delegate cannot be null\");\n }\n\n @Override\n public void forget() {\n resourceRef.set(null);\n }\n\n @Override\n public T get() {\n final T resource = resourceRef.get();\n if (resource != null) {\n return resource;\n }\n return getAndSetResource();\n }\n\n private T getAndSetResource() {\n lock.lock();\n try {\n final T resource = resourceRef.get();\n if (resource != null) {\n return resource;\n }\n final T newResource = delegate.get();\n resourceRef.set(newResource);\n return newResource;\n } finally {\n lock.unlock();\n }\n }\n}\n</code></pre>\n\n<p>(Untested code.)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T15:13:46.147",
"Id": "29101",
"Score": "0",
"body": "Thanks for your comments. I mostly agree with 1-5 (and have actually done most of these myself independently) but 7-8 are irrelevant because I *need* readers to block until there are no more `forget()` calls and `create()`ing is finished (see the second chapter of my post). Regarding 6 - if I understand correctly, this will make it so two `create()` calls can be running at the same time, right? This might or might not be desirable, I need to think more about this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T13:38:33.977",
"Id": "18211",
"ParentId": "18056",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T18:29:01.940",
"Id": "18056",
"Score": "7",
"Tags": [
"java",
"multithreading",
"cache",
"guava",
"memoization"
],
"Title": "Ability to forget the memoized supplier value"
}
|
18056
|
<p>When I look at this style of code I feel like there has to be a better way to write this:</p>
<pre><code><div id="by_cx">
<!-- free text input for name -->
<label>Name:<input type="text" id="cxByNameInput" name="cxByNameInput"/></label>
<!-- cx state drop down -->
<label for="cxState">State:</label>
<select id="cxState">
<option></option>
<?$states = getStates();
while($state = $states->fetch_assoc())
{?>
<option value="<?=$state['st']?>"><?=$state['state']?></option>
<?}?>
</select>
<!-- cx status drop down -->
<label for="cxStatus">Status</label>
<select id="cxStatus">
<option></option>
<?$statusList = getCxStatusList();
while($status = $statusList->fetch_assoc())
{?>
<option value="<?=$status['cxType']?>"><?=$status['cxTypeDescription']?></option>
<?}?>
</select>
</div>
</code></pre>
<p>I'd like to mention that keeping eclipses HTML code coloring would be a huge bonus...</p>
|
[] |
[
{
"body": "<h2>Code separation</h2>\n\n<p>What you have there is everything mixed together - just by moving the php logic to the top of the file, makes it easier to read. With some minor reformatting it becomes easier to read/maintain:</p>\n\n<pre><code><?php\n$states = getStates();\n$statusList = getCxStatusList();\n?> \n<div id=\"by_cx\">\n <!-- free text input for name -->\n <label>Name:<input type=\"text\" id=\"cxByNameInput\" name=\"cxByNameInput\"/></label>\n <!-- cx state drop down -->\n <label for=\"cxState\">State:</label>\n <select id=\"cxState\">\n <option></option>\n <?php while($state = $states->fetch_assoc()): ?>\n <option value=\"<?= $state['st'] ?>\"><?= $state['state'] ?></option>\n <?php endwhile; ?>\n </select>\n <!-- cx status drop down -->\n <label for=\"cxStatus\">Status</label>\n <select id=\"cxStatus\">\n <option></option>\n <?php while($status = $statusList->fetch_assoc()): ?>\n <option value=\"<?= $status['cxType'] ?>\"><?= $status['cxTypeDescription'] ?></option>\n <?php endwhile; ?>\n </select>\n</div>\n</code></pre>\n\n<h3>Format for readability</h3>\n\n<p>If you're jumping in and out of php - having lines like this: <code>{?></code> make things hard to read, especially if there is some nesting in the code. Whether you choose to use curly braces or the alternate (colon) syntax is up to you, but in html code using a style which aides readability (putting the curly brace/colon on the same line as the statement it relates to) helps.</p>\n\n<h3>No PHP Short tags</h3>\n\n<p>Shorttags are often considered a bad practice, and as such should be avoided unless the code is your own, and you control where it's going to be used. Note that you can use <code><?=</code> with PHP 5.4 irrespective of the shorttags setting.</p>\n\n<h3>Consistent whitespace</h3>\n\n<p>The following:</p>\n\n<pre><code><? foo(); ?>\n</code></pre>\n\n<p>Is easier to read than</p>\n\n<pre><code><?foo();?>\n</code></pre>\n\n<p>Especially where it appears inline somewhere - use whitespace for readability.</p>\n\n<h3>Sprintf</h3>\n\n<p>If you find that your code gets to be like this:</p>\n\n<pre><code><foo x=\"<?= $x ?>\" y=\"<?= $y ?>\" z=\"<?= $z ?>\"> ...\n</code></pre>\n\n<p>Then it's probably easier to read and maintain using:</p>\n\n<pre><code><?php echo sprintf('<foo x=\"%s\" y=\"%s\" z=\"%s\">...', $x, $y, $z); ?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T20:38:19.580",
"Id": "28776",
"Score": "0",
"body": "Interesting, so it would seem that other than the code separation you mentioned, there isn't much to improve on being that a lot of the other issues are just personal preference things ie. readablity. I had wondered if the while loop should actually be removed from inside the `<select>` tag but it would seem not. Thank you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T21:15:34.460",
"Id": "28778",
"Score": "2",
"body": "I wouldn't say that ;). There are changes outside the scope of your question as posed. View-like code should be as dumb as possible - the while loops should really be a foreach iterating over an array (allows for caching and or testing without the use of a db), \"complex\" html should be rendered with a helper function. These are two examples from the code in the question - look at any framework for something to compare to."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T20:12:36.357",
"Id": "18060",
"ParentId": "18058",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T19:52:14.833",
"Id": "18058",
"Score": "2",
"Tags": [
"php",
"html"
],
"Title": "Better way to incorporate HTML and PHP"
}
|
18058
|
<pre><code>public static class ThreadStatic<T> where T : new()
{
[ThreadStatic]
private static T instance;
public static T Instance
{
get { return instance ?? (instance = new T()); }
}
}
</code></pre>
<p>Used like this:</p>
<pre><code>var probability = ThreadStatic<Random>.Instance.NextDouble();
</code></pre>
<ol>
<li>Can this be broken? (Like, am I missing a <code>volatile</code> somewhere?)</li>
<li>Is there an existing pattern for this? Is there a better way to do this?</li>
<li>What would be an elegant way to allow for constructor parameters to be specified?</li>
<li>Would this be better suited to an IOC container?</li>
</ol>
|
[] |
[
{
"body": "<ol>\n<li><p>I'm not sure to be honest, the contained resource would be specific per thread and created upon first read so volatile may be unnecessary as I believe that's for multiple threads reading and writing to the same field.</p></li>\n<li><p>It looks like you are trying to make a singleton version of the <a href=\"http://msdn.microsoft.com/en-us/library/dd642243.aspx\" rel=\"nofollow\">ThreadLocal</a> class, unless you have a good reason I would suggest that you just use that instead.</p></li>\n<li><p>The ThreadLocal class allows for a factory method (as a <code>Func<T></code>) to be supplied to create a more complex object.</p></li>\n<li><p>It depends on the type of resource you want to use in this manner, if it is a service or resource then yes an IOC may be a better option as most containers allow an instance per thread. However if you just need per thread storage of a field, then <code>ThreadLocal</code> is a better option. It also allows the resource to be properly disposed if required too.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T00:04:41.657",
"Id": "28786",
"Score": "0",
"body": "I was not aware of the `ThreadLocal<T>` class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T06:50:55.540",
"Id": "28796",
"Score": "0",
"body": "@JohnGietzen given the size of the .net framework these days I'm not surprised! It wasn't introduced until .NET 4 either so it's relatively new too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T21:04:24.507",
"Id": "18061",
"ParentId": "18059",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T20:05:17.390",
"Id": "18059",
"Score": "5",
"Tags": [
"c#",
"thread-safety"
],
"Title": "Is this a thread safe way to control access to a reusable resource? Is there a better way?"
}
|
18059
|
<p>So I created this custom application and ported it into a few websites. It uses the Twitch API and pulls in active streams and the viewer count. The problem I run into is when the list gets so big it seems to become too much to do though ajax. I think this because sometimes it will show a stream online when it has been offline for awhile. I'm looking to improve it so open to suggestions. I'll leave a link at the bottom to an simple active page I have set up.</p>
<p>This is the AJAX / JS to handle my channel info and set them up into the page. I store some flash parameters in here because I didn't find it possible to change flash vars via JS so I just reset it every time. When there's no active channels it falls back on showing youtube videos.</p>
<pre><code>var channel = new Array();
var stats = new Array();
var title = new Array();
var viewers = new Array();
var called = true;
var active = false;
var query = window.location.search.split( '?' );
var current; // For viewers update
var ran;
var youtube = '<iframe width="560" height="315" frameborder="0" allowfullscreen></iframe>';
var tubes = ["zn7-fVtT16k", "7rE0-ek6MZA", "zj2Zf9tlg2Y", "mhTd4_Ids80", "AeNYDwbm9qw", "mgVwv0ZuPhM",
"l3w2MTXBebg", "WA4tLCGcTG4", "TAaE7sJahiw", "xBzoBgfm55w", "AFA-rOls8YA", "YHRxv-40WMU",
"ZIMoQHpvFQQ", "7ZsKqbt3gQ0", "1_hKLfTKU5Y", "UcTLJ692F70", "CeLrlmV9A-s", "FArZxLj6DLk",
"gAYL5H46QnQ", "NisCkxU544c", "BBcYG_J3O2Q"];
function getList(){
var i=0;
$.getJSON(
"streams.php",
function(data)
{
var first;
while(data.streams[i]){
channel[i] = data.streams[i];
stats[i] = data.status[i];
title[i] = data.title[i];
viewers[i] = data.viewers[i];
i++;
}
var online = $.inArray('online', stats);
if(online != -1){
first = online;
current = online;
online = true;
}
if(query[1] != null && called)
specific();
else if(online && called)
build(first);
else if(called)
randomTube();
addList();
updateViewers();
}
);
}
getList();
function build(a){
var data = 'http://www.twitch.tv/widgets/live_embed_player.swf?channel='; // Object Data
var src = 'hostname=www.twitch.tv&auto_play=true&start_volume=25&channel='; // Flashvars Param
data += channel[a];
src += channel[a];
var changeVars = '<param name="flashvars" value="hostname=www.twitch.tv&auto_play=true&start_volume=25&channel='+src+'"/>';
var params = '<param name="allowFullScreen" value="true" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowNetworking" value="all" />' +
'<param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" />' +
changeVars;
$("#twitchTV").html(params);
$("#twitchTV").attr("data", data);
if(stats[a] == 'online')
$('#streamTitle').html("Streamer: " + title[a] + " - <span id=\"viewers\">" + viewers[a] + "</span> Viewers");
else
$('#streamTitle').text("Streamer: " + title[a] + " - Offline");
current = a;
called = false;
}
function addList(){
var i = 0;
var content = '';
while(channel[i]){
if(stats[i] == 'online'){
content += '<li class="item"><div class="online"></div><a style="color:green" href="javascript: void(0)"'+
' title="'+title[i]+' Stream : '+viewers[i]+' Viewers" onClick="changeStream($(this).text())">'+title[i]+'</a></li>';
}
i++;
}
i=0;
while(channel[i]){
if(stats[i] == 'offline'){
content += '<li class="item"><div class="offline"></div><a class="keyWord" href="javascript: void(0)"'+
' title="'+title[i]+' Stream" onClick="changeStream($(this).text())">'+title[i]+'</a></li>';
}
i++;
}
$('#list ul').html(content);
}
function updateViewers(){
$('#viewers').text(viewers[current]);
}
function changeChat(){
var chatSrc = $('#chatFrame').attr('src');
var chat = chatSrc.split('channel=');
$('#chatFrame').attr('src', chat[0]+'channel='+channel[current]);
$('#mainChat').removeClass('activeChat');
$('#streamChat').addClass('activeChat');
}
function changeStream(find){
var found = $.inArray(find, title);
if(found != -1){
build(found);
current = found;
}
if($('#streamChat').hasClass('activeChat'))
changeChat();
}
function randomTube(){
$('#player').html(youtube);
$('#player iframe').attr("src", "http://www.youtube.com/embed/"+ tubes[Math.floor(Math.random()*tubes.length)]);
$('#streamTitle').html('<a href="javascript: void(0)" title="Random Video" onClick="randomTube()" class="rano">Random Video</a>');
called = false;
}
function specific(){
var found = $.inArray(query[1], channel);
if(found != -1){
build(found);
current = found;
called = false;
}
}
setInterval(getList, 1000); // Update the streams list every second
</code></pre>
<p>The PHP file reads from a file which contains the channel name and channel Nick Name (which is how we want to show it in the webpage) and then I loop through to check and see which ones are active:</p>
<pre><code><?php
$streamer = array();
$status = array();
$title = array();
$viewers = array();
$i = 0;
$handle = file("streamers.txt", FILE_IGNORE_NEW_LINES);
foreach($handle as $chan){
$temp = explode("-t-", $chan); // Seperate Streamer from Title
$streamer[$i] = $temp[0]; // Streamer is on left of -t-
$title[$i] = $temp[1]; // Title is on the right of -t-
$i++;
}
$i = 0;
foreach($streamer as $index) // Loop through and see what streams are online
{
$json_file = @file_get_contents("http://api.justin.tv/api/stream/list.json?channel={$index}", 0, null, null);
$json_array = json_decode($json_file, true);
if ($json_array[0]['name'] == "live_user_{$index}")
{
$status[$i] = "online";
$viewers[$i] = $json_array[0]['channel_count'];
}
else
{
$status[$i] = "offline";
$viewers[$i] = 0;
}
$i++;
}
// Combine the 3 needed arrays to send through JSON
$data['streams'] = $streamer;
$data['status'] = $status;
$data['title'] = $title;
$data['viewers'] = $viewers;
echo json_encode($data);
</code></pre>
<p>I run into a bottle neck once I have so many channels to check. The only solution I can see if to do check half then check another half, but I'm not sure. Here's some links to an active example. The <a href="http://www.webdevstl.com/misc/stream/" rel="nofollow">Index Page</a>, The <a href="http://www.webdevstl.com/misc/stream/dynamic.js" rel="nofollow">JS Page</a> and The what <a href="http://www.webdevstl.com/misc/stream/streams.php" rel="nofollow">PHP Returns</a>. Let me know if you have any questions!</p>
|
[] |
[
{
"body": "<p>Updating the list through ajax every second takes a lot of resources, both client and server side. If you insist on doing the update so often I recommend you take a look at, comet or websockets. Read <a href=\"https://stackoverflow.com/questions/19995/is-there-some-way-to-push-data-from-web-server-to-browser\">Is there some way to PUSH data from web server to browser?</a>.</p>\n\n<p>Also witch part of your applications seems to be the bottleneck? Is it the PHP script that is lagging behind or is it the AJAX side of the app that is not working as you would like?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T08:06:17.667",
"Id": "29086",
"Score": "0",
"body": "That's what I was talking about is the resources it takes to update the list. I looked into web sockets but I tried to play around with it and maybe I don't understand how it works but I need to loop through a list to update it instead of just leaving open a port. It has to go through many links and many 'channels'. Comet Might be the answer but I need to look into it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T08:45:56.600",
"Id": "29087",
"Score": "1",
"body": "Am I understanding you correctly that it's the ajax page that is using to much resources? If so I'm not supprised since pulling the server every second takes a lot of processing power."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T19:08:00.163",
"Id": "29120",
"Score": "0",
"body": "Yeah. When it's updating the list of active channels (via JS that it pulls from the ajax data) that's when I run into problems so it's safe to assume my ajax requests are fairly heavy. What sucks though is I would love to check out Web Sockets and dealing with Persistent Connections but apparently my provider doesn't allow it. So while it may be a valid assumption that Web Sockets would improve my application I have no way of testing :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T21:33:33.583",
"Id": "29125",
"Score": "0",
"body": "Do you need to pull the server every second? Try pulling every minute or so instead. I doubt it's mission critical if you update the channel list less often."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T02:05:12.013",
"Id": "29133",
"Score": "0",
"body": "It probably doesn't need to pull the list every second but once a channel is active it needs to pull that channel (where web sockets would come in handy) to update the number of viewers viewing the active stream every second. Though even pulling the list every minute I imagine would still be fairly resource intensive. I'll run it through and see what happens though, again maybe splitting up the active channel into its own ajax call to get just viewers might be a good idea."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T07:44:37.410",
"Id": "18237",
"ParentId": "18066",
"Score": "2"
}
},
{
"body": "<p>Have you attempted to isolate the different functions? i.e. test the ajax against local data (just copy an output from the php page and hit that) instead of a php page that rebuilds the list every time? If you are still getting slow down issues than you know it is the javascript that is slow. If not you can be pretty sure that it is the querying of the api that is slow.</p>\n\n<p>My guess is that your biggest bottleneck is this line (I have nothing to back this up, just a guess):</p>\n\n<p><code>@file_get_contents(\"http://api.justin.tv/api/stream/list.json?channel={$index}\", 0, null, null);</code></p>\n\n<p>According to the docs the data in the list function is cached for 60 seconds. So no reason to poll more often than that. <a href=\"http://apiwiki.justin.tv/mediawiki/index.php/Stream/list\" rel=\"nofollow\">http://apiwiki.justin.tv/mediawiki/index.php/Stream/list</a>. Polling more often is just wasting resources.</p>\n\n<p>As an aside, as a general rule you should try to limit your use of global variables. Not sure if this would affect any of the performance problems so I won't go into specifics on that unless asked.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-07T02:26:43.720",
"Id": "29160",
"Score": "0",
"body": "Global Javascript Variables or Global PHP Variables? And good call on the cache - I didn't realize that. I don't really see why that PHP line would cause a major issue since it is just getting the data. Probably lowing the call on the ajax request to 60s would help it out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-07T02:39:47.127",
"Id": "29161",
"Score": "0",
"body": "As a general rule you should avoid to use the suppress operator (@) to suppress errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-07T02:57:27.413",
"Id": "29162",
"Score": "0",
"body": "I was referring to the javascript as I am more familiar with javascript and am not completely familiar with PHP conventions. If you are calling an API once per stream to get the info you are wiring up all the http calls for every stream. As a single call not a big deal but can get heavy with multiple calls. These are just guesses though, which I is why I recommended removing this and trying to load data with the js only. Isolate the parts to determine which is slowing you down. Otherwise you will only be guessing at what to fix."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T19:44:30.757",
"Id": "18289",
"ParentId": "18066",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18289",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-29T23:58:43.507",
"Id": "18066",
"Score": "2",
"Tags": [
"javascript",
"php",
"jquery",
"ajax",
"api"
],
"Title": "Custom Streaming Application - Twitch"
}
|
18066
|
<p>As part of an assignment in Cryptography I've been asked to write code that involves calculating modular exponentiation. The BigInteger modPow is not allowed in this case, we have to implement it ourselves. </p>
<p>I have the assignment working, but I think my modular exponentiation function is not the greatest in terms of run time. It's based on the right-to-left binary method.
Here is it : </p>
<p>The algorithm calculates (a^b) mod c.</p>
<pre><code>private static BigInteger modulo(BigInteger a, BigInteger b, BigInteger c) {
BigInteger x = BigInteger.ONE;
final BigInteger TWO = new BigInteger("2", 16);
while(b.compareTo(BigInteger.ZERO) > 0) {
BigInteger compareVal = b.mod(TWO);
if(compareVal.compareTo(BigInteger.ONE) ==0) {
x = (x.multiply(a)).mod(c);
}
a = (a.multiply(a)).mod(c);
b = b.divide(TWO);
}
return x.mod(c);
}
</code></pre>
<p>However, that solution uses 2 comparisons, 2 multiplications and a division within the loop. Can anyone point me in the direction of something more efficient? I'm not looking for a specific answer here, maybe just some ideas. Googling modular exponentation doesn't yield much that's useful in this case, and when I time this algorithm it's performance is very poor. </p>
<p>Any direction or feedback would be hugely appreciated. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T04:46:46.800",
"Id": "28793",
"Score": "0",
"body": "Your loop is going to run (b / 2) times. That is what is slowing you down."
}
] |
[
{
"body": "<p>Just a quick note, not an optimization idea:</p>\n\n<pre><code>if(compareVal.compareTo(BigInteger.ONE) ==0) { ... }\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>if (compareVal.equals(BigInteger.ONE)) { ... }\n</code></pre>\n\n<p>which is a little bit easier to read. Furthermore, if you switch the objects it will be null-safe:</p>\n\n<pre><code>if (BigInteger.ONE.equals(compareVal)) { ... }\n</code></pre>\n\n<p>It does not throw <code>NullPointerException</code> when <code>compareVal</code> is <code>null</code>. (This is true for <code>compareTo</code> too, for example: <code>BigInteger.ZERO.compareTo(b)</code>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T22:05:05.720",
"Id": "28884",
"Score": "0",
"body": "While what you say about your version not throwing an NPE is true, I feel this is a minor worry at best - namely, you'd have to get a null return out of `b.mod(TWO)`, which is _probably_ impossible; I'd rate the possibility of either of those two operands being null (especially `b`, which is an entry parameter) rather higher."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T06:25:50.870",
"Id": "18070",
"ParentId": "18067",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>However, that solution uses 2 comparisons, 2 multiplications and a division within the loop.</p>\n</blockquote>\n\n<p>You are doing 3 mod, they are not free, too (mod creates new internal copies and does a divide).</p>\n\n<hr>\n\n<pre><code>final BigInteger TWO = new BigInteger(\"2\", 16);\n</code></pre>\n\n<p>I do not understand, why you parse 2 to basis 16? It does not change the result, but i suggest to use:</p>\n\n<pre><code>final BigInteger TWO = new BigInteger(\"2\");\n</code></pre>\n\n<hr>\n\n<p>I assume here:</p>\n\n<pre><code>BigInteger compareVal = b.mod(TWO);\n if(compareVal.compareTo(BigInteger.ONE) ==0) { \n</code></pre>\n\n<p>You want to check for oddnes. You can to this in constant time if you look at the last bit:</p>\n\n<pre><code>if (b.testBit(0)) // then it is odd\n</code></pre>\n\n<p>And you can get rid of this <code>TWO</code> </p>\n\n<hr>\n\n<p>Instead of dividing by 2</p>\n\n<pre><code>b = b.divide(TWO);\n</code></pre>\n\n<p>You can shift:</p>\n\n<pre><code>b = b.shiftRight(1);\n</code></pre>\n\n<p>This has a better implementation.</p>\n\n<hr>\n\n<p>The last mod for the return:</p>\n\n<pre><code>return x.mod(c);\n</code></pre>\n\n<p>is not needed:</p>\n\n<pre><code>return x;\n</code></pre>\n\n<hr>\n\n<p>and after all, you can choose better names and you could end up with:</p>\n\n<pre><code>private static BigInteger fastModPow(BigInteger base, BigInteger exponent, final BigInteger modulo) {\n // plan: exploit the binary representation of the exponent, see for example http://en.wikipedia.org/w/index.php?title=Modular_exponentiation&oldid=517653653#Right-to-left_binary_method\n BigInteger result = BigInteger.ONE;\n while (exponent.compareTo(BigInteger.ZERO) > 0) {\n if (exponent.testBit(0)) // then exponent is odd\n result = (result.multiply(base)).mod(modulo);\n exponent = exponent.shiftRight(1);\n base = (base.multiply(base)).mod(modulo);\n }\n return result.mod(modulo);\n}\n</code></pre>\n\n<p>Small and meaningless test with base and exponent length of 50.000:<br>\nold: around 20s<br>\nnew: around 1s<br>\n(Java: couple of ms)</p>\n\n<p>If you want further optimization, you have to choose better algorithms. One little trick could be to look into the <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/math/BigInteger.java#BigInteger.modPow%28java.math.BigInteger,java.math.BigInteger%29\">Java source code</a>. If you are not allowed to use the Java method, noone forbids you to use the code inside?</p>\n\n<p>(One last hint: If you do some non trivial algorithms, add a comment about it)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T11:15:14.343",
"Id": "28865",
"Score": "0",
"body": "Thanks for that, test bit and shift were functions I hadn't even considered, great answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:32:46.660",
"Id": "18093",
"ParentId": "18067",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18093",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T00:42:20.830",
"Id": "18067",
"Score": "2",
"Tags": [
"java",
"optimization",
"cryptography"
],
"Title": "Modular exponentiation optimisation in Java"
}
|
18067
|
<p>How can I design this class and its implementation so that it looks like it was developed by a seasoned senior level PHP developer that follows all of the best practices? I'm trying to design this class so that it can be reused in other applications. I also have some other questions that are located inside of the code.</p>
<p>Please overlook commenting on the following 2 things:</p>
<ul>
<li>Docblock commenting </li>
<li>Unit testing</li>
</ul>
<h2><code>Login</code> Class</h2>
<pre><code><?php
class Login
{
private $username;
private $password;
//PDO mysql connection object
private $pdo;
/**
* Question 1.
* Is this the correct way to use an error object? I am passing it in to
* the constructor for DI (Dependency Injection) just like the $pdo
* object? I will have multiple classes that need error management.
*
* Question 2.
* Would each class that uses the error object need to have a method
* called getErrors() as shown below and should I implement an interface
* called 'errors' that has a getErrors() method or should I use an abstract
* class that implements it once so all classes can use it?
*/
private $error;
public function __construct(PDO $pdo, Error $error, $loginCredentials)
{
/**
* Throw exception if missing Login Credentials
*/
if (!isset($loginCredentials['username']) || !isset($loginCredentials['password'])) {
throw new InvalidArgumentException(
"Login credentials must be passed into the ". __CLASS__ . " class in the form of an
associative array with the keys 'username' and 'password'."
);
}
$this->pdo = $pdo;
$this->error = $error;
$this->username = $loginCredentials['username'];
$this->password = $loginCredentials['password'];
}
public function authenticate()
{
/**
* Question 3.
* In each class that uses a PDO connection object,
* is it proper to do all these database interaction details
* in each method that requires database interaction?
*/
$query = "SELECT * FROM admin WHERE user = :user AND password = :pass";
//Prepare statement
$stmt = $this->pdo->prepare($query);
//Set fetch mode
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//Set params to bind
$params = array(
':user'=>$this->username,
':pass'=>sha1($this->password)
);
$stmt->execute($params);
//If the user is found, log them in.
if ($stmt->rowCount()) {
$this->loginUser();
return true;
} else {
/**
* Is this the best way to set errors?
*/
$this->error->set('Invalid Username and or Password combination');
}
}
/**
* Question 4.
* Is this the proper way to display errors back to the user?
* Once a use submits the login form, the client code calls
* authenticate(). If it returns false, it runs this method.
*/
public function getErrors() {
return $this->error->getErrors();
}
private function loginUser()
{
$_SESSION['loggedIn'] = 1;
$this->isLoggedIn = true;
}
}
</code></pre>
<h2><code>Error</code> Class</h2>
<pre><code>class Error
{
private $errors = array();
public function set($msg)
{
$this->errors[] = $msg;
}
public function getErrors()
{
return $this->format();
}
private function format()
{
if (count($this->errors) > 0) {
$errors = '';
foreach ($this->errors as $error) {
$errors .= '<p>'.$error.'</p>';
}
return $errors;
}
return false;
}
}
</code></pre>
<h2>Implementation</h2>
<pre><code>if (isset($_POST['submit'])) {
/**
* Question 5.
* Looking at the below code, is there a better way so that I can comply
* with the DRY (Don't Repeat Yourself) principle in order to not repeat
* the try{} catch() {} block very time I pass a $pdo object into a class?
*
* Is the proper way accomplished by first creating a new class i.e. PDOConfig
* that extends PDO, and inside the constructor put the try catch block?
*
* If so, is it always better to pass the details into PDOConfig like this:
* $Login = new Login(new PDOConfig(DB_DSN, DB_USER, DB_PASS), new Error(), $_POST)
* or is it better to hard code the constants into the PDOConfig
* class's constructor, and then call it like this:
* $Login = new Login(new PDOConfig(), new Error(), $_POST)
*/
try{
$pdo = new PDO(DB_DSN, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "There was an error connecting: " . $e-getMessage();
}
$Login = new Login($pdo, new Error(), $_POST);
if ($Login->authenticate()) {
header("Location: index.php");
exit();
} else {
echo $Login->getErrors();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T13:43:18.190",
"Id": "29146",
"Score": "0",
"body": "Why is everyone doing the password check using SQL instead of PHP? SQL will use a collation when comparing strings that is not always predictable (CI, AI). PHP will compare the strings in a safer way. Just fetch the user by username and check fields (lockout, password, expiry) using PHP."
}
] |
[
{
"body": "<h1>Red flag</h1>\n<pre><code> $query = "SELECT * FROM admin WHERE user = :user AND password = :pass";\n</code></pre>\n<p>Ok, so you've heard that you should hash passwords before storing them, because it turns out that <code>pass</code> is a SHA hash. But you don't seem to have heard of salt. The password database is going to be wide open to a rainbow table attack.</p>\n<p>I would recommend that you use a framework which has a good password storage mechanism (if there is one). If not, read the <strong><a href=\"https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet\" rel=\"nofollow noreferrer\">OWASP Password Storage Cheat Sheet</a></strong> very carefully before you rewrite this code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T14:58:12.047",
"Id": "28873",
"Score": "0",
"body": "Using a salt is of course something to change, but I feel this answer is misleading. It doesn't mention you'd need another exploit to gain access to the db, to make use of that weakness. I.e. unless someone gains access to the db, it changes nothing in terms of the security of the application. [crypt](http://es.php.net/manual/en/function.crypt.php) with blowfish, is a better recommendation than a salted sha1. It's also a single relatively trivial (in terms of effort at least) point, there are other fish to fry. -1 for tone \"you don't seem to have heard of salt\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T18:07:19.717",
"Id": "28879",
"Score": "0",
"body": "@AD7six, it's certainly not trivial, in terms of effort or in any other terms. Doing anything security-related correctly is very hard: that's why I recommend using a framework which does it well over implementing it yourself. Various high-profile leaks of password databases over the past year should be sufficient demonstration of the value of storing them properly. Not sure what problem you have with the tone. Too friendly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T18:23:48.180",
"Id": "28880",
"Score": "0",
"body": "Users don't post their code to be ridiculed for what they don't know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T20:14:39.103",
"Id": "28881",
"Score": "0",
"body": "@AD7six, ridiculed, no, of course not, but I don't intend or see any ridicule. People do post their code to be *told* what they don't know: that's the point of code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T13:29:48.133",
"Id": "28910",
"Score": "0",
"body": "I've noticed that is the tough thing with \"text\". To one person a word or phrase might sound like a bad tone, and to the person writing the word or phrase, they do not intend for it to happen. But it's ok you guys, thanks for both wanting to help :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T13:31:06.620",
"Id": "28911",
"Score": "0",
"body": "Although all answers are great, they still don't answer the question about how a senior developer would design this same class. All password hashing aside! It's great to know about password hashing, but that isn't what I am after with this."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T13:30:50.243",
"Id": "18115",
"ParentId": "18068",
"Score": "4"
}
},
{
"body": "<pre><code><?php\n\nclass Login {\n\n private $pdo;\n private $hasher;\n\n public function __construct(PDO $pdo, IHasher $hasher) {\n $this->pdo = $pdo;\n $this->hasher = $hasher;\n }\n\n public function Authenticate($userName, $password) {\n $query = \"SELECT * FROM admin WHERE user = :user\";\n\n $stmt = $this->pdo->prepare($query);\n\n $stmt->setFetchMode(PDO::FETCH_ASSOC);\n\n $params = array(\n ':user'=>$this->username\n );\n\n $stmt->execute($params);\n\n if ($stmt->rowCount() == 1) {\n // ... get user row or object say:\n\n $user = new User(); //or something else\n\n if ($this->hasher->Compare($password, $user->Password)) { \n //check other stuff, disabled user, locked etc.\n\n /* a PHP session has been already started but we start a new with different session id see session handling on php.net */\n $session = Session::Start($user);\n\n return $session;\n }\n }\n\n throw new \\Exception('Invalid Username and or Password combination');\n }\n}\n</code></pre>\n\n<h2>Error class</h2>\n\n<p>If something goes wrong simply throw an exception and handle it. No need for some custom magic error handling stuff.</p>\n\n<h2>PDO usage</h2>\n\n<p>Yes you can use PDO like this but if i were you i would create a wrapper for it to minimalize code duplicates and provide more readability. I recommend you to fatch objects from database rows not associative arrays becouse it is a bad habbit in the PHP community (arrays are for storing data which are same types).</p>\n\n<h2>Hashing</h2>\n\n<p>First see @Peter Taylor's comment. In my example i'm injecting an IHasher implementation through the constructor but this is not the best i think. You should have some membership provider stuff and that can have a configurable hashing method what can be used at authentication/user registration and password changing scenarios.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T13:36:15.013",
"Id": "28912",
"Score": "0",
"body": "Hi Peter, thank you for posting. The reason I want to use an error class, is because I want to manage all errors in all my classes the same way. I'm trying to get practice using other objects inside objects. As far as the PDO usage, could you provide an example of that wrapper? I agree with fetching objects instead of assoc arrays, I overlooked that. Thank you! As far as hashing, I will look into the salt. I've heard of it, just have never used it yet. Thxs!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T14:27:47.667",
"Id": "28916",
"Score": "0",
"body": "See Database class here: http://stackoverflow.com/questions/13100427/static-method-calling-result-of-mysql-query/13100788#13100788\nThis is a very basic class, the next could be a new Exucute and Query method, for example: public function Query($queryString, array $params) { /* ... */ } here you can not use names parameters int the query instead those you have to use question marks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T22:57:48.260",
"Id": "28937",
"Score": "0",
"body": "Hey Peter, I took a look! Thanks!! I have come to the conclusion that in order for me to learn the right way to program, I need to find an open source application that is VERY SMALL, probably less than 20 classes. But large enough to see how it is developed and how the individual classes interact. Do you happen to know of such a project? I only want to study the absolute best principles. I absolutely hate to ask, but do you think you could write the entire Login class the way that you would write it and post it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T23:00:22.440",
"Id": "28938",
"Score": "0",
"body": "That way I can learn from it. Most likely it will be the accepted answer because it will be most beneficial to many people who are trying to learn proper class design. The sad thing is that when people post questions on here, they truely are looking to learn ALOT, but sometimes answers get posted that just teach a little. Like for instance, the post that has the highest score. It simply talks about adding a SALT instead of a sha1 hash. Ok that's great, but it doesn't teach any true class design. You see what I mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T23:02:28.180",
"Id": "28939",
"Score": "0",
"body": "When I say \"the exact way you would do it\" I am referring to the \"wrapper\" and the whole nine yards. A true class design for all to feast off of who really want to learn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T02:52:13.270",
"Id": "28941",
"Score": "0",
"body": "Neither of these are unique to your answer, but: Throwing an exception is not the correct course of action for a failed authentication. An exception implies that something particularly out of the ordinary happened. A failed authentication is just as expected as a successful authentication (depending on perspective). Also, authentication and identity persistence should not be tied together. What if the consumer of this class wanted to check a username/password combination *without* then logging in as that user? That's two separate concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T07:52:44.380",
"Id": "28943",
"Score": "0",
"body": "@darga33 to write a complete solution is difficult becouse it requires a huge infrastructure: how do you process the request, how can you inject configurations etc. The solution will contain a lot classes: Membership (this can be full static depending on your solution), MembershipUser, IMembershipProvider interface for real backends (SQL, XML, memory), IPasswordService for the providers to do the hashing, some kind of session handling stuff with authentication and session validation. The best thing to do is try put these things together (without any implementation just skeletons) and ask."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T04:12:14.100",
"Id": "29027",
"Score": "0",
"body": "Yeah Peter, I know what you mean. It can be very very complex. I'm not actually looking for a complex complete solution. I'm looking for a barebones solution but that utilizes some kind of error handling technique that allows for errors to be displayed back to the user. It's something that I think I'm going to have to spend some time on to wrap my mind around. Thanks so much for all the help! It was much appreciated! Everyones answers were great!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T14:11:41.117",
"Id": "18116",
"ParentId": "18068",
"Score": "1"
}
},
{
"body": "<p>I would not recommend returning user messages from the Login class, but instead to return a 'status' which can be converted to a message. This will provide better maintainability and extensibility. There are a couple of options for doing this. First I'll start by demonstrating a problem with the approach of using an Error object when it comes time to differentiate between different failure scenarios:</p>\n\n<pre><code>$Login = new Login($pdo, new Error(), $_POST);\nif ($Login->authenticate()) {\n header(\"Location: index.php\");\n exit();\n} else {\n // Do something additional based on the failure\n foreach ($Login->getErrors() as $error) {\n if ($error === 'Invalid username or password') {\n // Do something special for invalid credentials\n }\n }\n}\n</code></pre>\n\n<p>A better approach to handle this case is to throw an exception when authentication fails:</p>\n\n<pre><code>class Login {\n public function authenticate(...) {\n // ...\n if ($stmt->rowCount()) {\n $this->loginUser();\n return true;\n } else {\n throw new Exception('Invalid username or password');\n }\n }\n}\n</code></pre>\n\n<p>Lets evaluate this from the point of view of code that uses the Login class (consumer code).</p>\n\n<pre><code>try {\n $login = new Login(/*...*/);\n $login->authenticate(/*...*/);\n\n // ... Do whatever needs to happen on successful login\n} catch (Exception $e) {\n\n // Here is where we run into problems with this approach because we\n // don't know for sure why this exception occurred, it could very well\n // be a PDOException\n if ($e->getMessage() === 'Invalid username or password') {\n // ...\n } else {\n // ... Handle other types of exceptions\n }\n}\n</code></pre>\n\n<p>This is very fragile and difficult to maintain because every time the message is updated this code needs to be updated as well. You could use a constant for the message, but this still involves a complicated catch clause to determine the nature of the exception and doesn't allow for parameterized messages. This can be improved by a subclass of exception specifically for login related errors:</p>\n\n<pre><code>class LoginException extends Exception {}\n\nclass Login {\n public function authenticate(...) {\n // ...\n if ($stmt->rowCount()) {\n $this->loginUser();\n return true;\n } else {\n throw new LoginException('Invalid username or password');\n }\n }\n}\n</code></pre>\n\n<p>Now the updated consumer code:</p>\n\n<pre><code>try {\n // ... same as above\n} catch (LoginException $e) {\n echo $e->getMessage();\n} /* Other types of exceptions will bubble or can be caught here if it is possible to handle them */\n</code></pre>\n\n<p>This is perfectly fine for a single type of error, but lets suppose the login class is expanded to protect against brute force attacks by locking accounts after a certain number of failed attempts. The authenticate method would now look something like this:</p>\n\n<pre><code>class Login {\n public function authenticate(...) {\n // ...\n $acctInfo = $stmt->fetch();\n if ($acctInfo !== null) {\n if ($acctInfo['locked']) {\n throw new LoginException('Account is locked, you must contact an administrator before you can login');\n }\n $this->loginUser();\n return true;\n } else {\n throw new LoginException('Invalid username or password');\n }\n }\n}\n</code></pre>\n\n<p>Now the consumer code:</p>\n\n<pre><code>try {\n // ...\n} catch (LoginException $e) {\n if ($e->getMessage() === 'Invalid username or password') {\n // ...\n } else if ($e->getMessage() === 'Account is locked, you must contact an administrator before you can login') {\n // ... Do something different\n }\n}\n</code></pre>\n\n<p>This has the same problem as the first example. Again this can be simplified by using constants to hold the error messages but the same issues apply. Another solution would be to create an exception subclass for each type of error resulting in the following consumer code:</p>\n\n<pre><code>try {\n // ...\n} catch (InvalidUsernameOrPasswordLoginException $e) {\n // Common exception handling setup...\n\n // Differentiated exception handling for invalid credentials...\n\n // Common exception handling output...\n\n} catch (AccountLockedLoginException $e) {\n // Common exception handling setup...\n\n // Differentiated exception handling for locked account...\n\n // Common exception handling output...\n}\n</code></pre>\n\n<p>Now we're getting somewhere, there is no reliance on the actual message to distinguish between failure types. However, this style of multiple catch statements can make it difficult to eliminate duplication. Lets take a step back and instead of introducing multiple types of exception for login failure use an error code to distinguish failure types:</p>\n\n<pre><code>class LoginException extends Exception {\n const INVALID_USERNAME_OR_PASSWORD = 'login.failure.invalidUsernameOrPassword';\n const ACCOUNT_LOCKED = 'login.failure.accountLocked';\n\n public function __construct($code) {\n parent::__construct('Authentication failed', $code);\n }\n}\n\nclass Login {\n public function authenticate(...) {\n // ...\n $acctInfo = $stmt->fetch();\n if ($acctInfo !== null) {\n if ($acctInfo['locked']) {\n throw new LoginException(LoginException::ACCOUNT_LOCKED);\n }\n $this->loginUser();\n return true;\n } else {\n throw new LoginException(LoginException::INVALID_USERNAME_OR_PASSWORD);\n }\n }\n}\n</code></pre>\n\n<p>Now the consumer code will be similar to the code we had before but is relying instead on codes to distinguish between failure types.</p>\n\n<pre><code>try {\n // ...\n} catch (LoginException $e) {\n\n // Do common exception handling setup here...\n\n switch ($e->getCode()) {\n case LoginException::INVALID_USERNAME_OR_PASSWORD:\n // Differentiated exception handling for invalid credentials\n break;\n\n case LoginException::ACCOUNT_LOCKED:\n // Differentiated exception handling for a locked account\n break;\n }\n\n // Do common exception handling output here...\n}\n</code></pre>\n\n<p>This is preferable to relying on messages which are prone to change or may not even be the same for each execution. Consider trying to determine the type of failure for the the following message: <code>\"Invalid password or unrecognized user: $username\"</code>.</p>\n\n<p>Not getting into details, using codes has additional benefits over generating messages in internal classes when your application is localized or when support is added for additional clients.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T20:15:30.393",
"Id": "28933",
"Score": "0",
"body": "Hey pgraham, Thanks for the advice but I'm not sure what you mean when you say this \"messages should only be generated at the boundary of your application, immediately before you pass it to the client. Before this the failure should simply be represented as an object encapsulating a status which is not tied to any particular message:\" Keep in mind, I am VERY VERY new to programming, and OOP. My first and only language is PHP. I'm trying to learn as fast as I can, but in order to really understand and learn, I need to see simple complete examples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T20:37:36.813",
"Id": "28934",
"Score": "0",
"body": "If you look at the Implementation section of the code, the status code is only transformed into an actual message (by L10N) immediately before being echoed. By \"boundary\" I mean the point where data is passed to user. In the case of PHP this is usually done with `echo`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T22:18:42.397",
"Id": "28936",
"Score": "0",
"body": "Oh yeah I saw L10N, I just don't know what L10N is. I have a tremendous amount to learn in order to understand these concepts clearly. I just thought that it would be a good idea to try to find a project that was developed in PHP using the SOLID acronym princples and all of the best practices. Something that is small, and has around 15 classes. Do you happen to know of such a program?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T13:55:05.557",
"Id": "28959",
"Score": "0",
"body": "L10N stands for localization (first letter L, last letter N with 10 letters in between). In my code sample it is a theoretical class that takes a code and uses that to generate a localized message. I don't know of any such program off the top of my head but you could start by looking at http://symfony.com/. It's not small but you could probably look at one of its components in isolation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T21:52:54.803",
"Id": "28976",
"Score": "0",
"body": "I think talking about localization is just distracting - most code doesn't need it. A method to set the texts used in the class however, would be appropriate. Pointing at symfony for someone \"VERY VERY new to programming, and OOP\" is not a good idea. Symfony's source code is confusing for experienced developers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T04:19:01.117",
"Id": "29028",
"Score": "0",
"body": "Hey pgraham! I think I am starting to understand what you are talking about with localization. This technique seems really useful! I want to learn it! **So when you say:** \"Before this, the failure should simply be represented as an object encapsulating a status which is not tied to any particular message.\", are you referring to -- when you wrote, for instance this: $statusCode = 'authentication.failure.invalidUsernameOrPassword'; \n\n**If so**, one thing I'm not understanding: your returning a new AuthenticationStatus object that is passed a $statusCode, which seems to be a string?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T04:26:44.843",
"Id": "29029",
"Score": "0",
"body": "but the AuthenticateStatus constructor takes 2 params: $success and $code. What are the $success and $code params supposed to be? And then in the implementation, when you do: L10N::get($authStatus->getCode()), what does the class definition of the L10N class look like? Do I have a different one for each class that has errors? Or is this approach only used for Login classes? I really do want to learn this, it's just complicated to wrap my head around! I kind of have to see the whole picture in order to understand it! Boy I can't wait to get passed this part of my learning curve!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T17:20:43.933",
"Id": "29109",
"Score": "0",
"body": "@AD7six Yes I agree the conversation has veered a bit. My original intention was to use localization as an example of why the Login class shouldn't be generating it's own error messages but simply error statuses. I'll have to take your word about Symfony as I am mostly unfamiliar with the internals but was under the impression that it is composed of many smaller projects, one of which might be useful as an example for a beginner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T17:44:20.960",
"Id": "29112",
"Score": "0",
"body": "@AD7six \"...talking about localization is just distracting - most code doesn't need it.\" I wholehearted disagree, every single project I've worked on professionally has required some level of localization.\n\n\"A method to set the texts used in the class however, would be appropriate.\" Again, I disagree. This would create a maintenance problem whenever a new class of error is added requiring updates to every single consumer."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T18:33:41.470",
"Id": "18140",
"ParentId": "18068",
"Score": "3"
}
},
{
"body": "<h2>The numbered questions</h2>\n\n<h3>1 Correct usage of an Error object?</h3>\n\n<p>Probably not. Using DI is fine, creating an object to inject into the construtor where it's not fundamentally required is not.</p>\n\n<p>The use of the term \"an Error object\" implies it's a common/global concept - I'm not familiar with this. Javascript has error objects for example, PHP has exceptions. In both cases though, they are classes that are created to represent one error and to be thrown and not something that's passed around and especially not something that's eagerly created incase an error condition occurs.</p>\n\n<h3>2 all classes need getErrors?</h3>\n\n<p>The Error object is not something I feel should exist.</p>\n\n<p>Ignoring that though, from what you've said in the question, the Error object is supposed to be used with various, possibly quite different classes. Since (I assume) the same instance of the error object is passed around there is no need for the getErrors method at all - just get a reference to the singleton Error instance, and query it directly.</p>\n\n<h3>3 PDO usage?</h3>\n\n<p>You're better off using some abstraction, doctrine is a reasonable choice if you aren't using anything at all right now.</p>\n\n<h3>4 Proper way to display errors?</h3>\n\n<p>Probably not. This class isn't presentational, it should be returning only data.</p>\n\n<h3>5 DRY try/catch?</h3>\n\n<p>Only catch exceptions that you know how to handle. in the example code a PDOException is caught, no corrective action is taken which simply means that a fatal error will be thrown on this line:</p>\n\n<pre><code>if ($Login->authenticate()) {\n</code></pre>\n\n<p>since it tries to talk to the database, which isn't connected. You can use <a href=\"http://php.net/manual/en/function.set-exception-handler.php\" rel=\"nofollow\">set_exception_handler</a> so that you don't need to scatter try catch blocks around your code where the intended result is to do nothing except logging and show the user (or developer) a 500 error message.</p>\n\n<p>With that said, some more detail in the order points are encountered reading the code:</p>\n\n<h2>Don't mix presentation logic into classes</h2>\n\n<p>Unless the class is dedicated to presentation logic - don't put presentation logic in it. This simply means don't return or assume html, instead just return appropriate data (booleans, arrays - as appropriate). The function <code>Error::format</code> is an example whereby it would be better to just return the array stack and let something else loop over it and dump to html,json, the log etc.</p>\n\n<h2>Don't create needless classes</h2>\n\n<p>The error class doesn't seem to offer any benefits.</p>\n\n<p>I.e. this:</p>\n\n<pre><code>$foo = new Login($pdo, new Error(), array(..));\n$return = $foo->authenticate();\n...\n$errors = $foo->getErrors();\n</code></pre>\n\n<p>Could be used almost identically if the error object didn't exist:</p>\n\n<pre><code>/**\n * Is this the best way to set errors?\n */\n$this->errors['user'] = 'User not found'; // as appropriate\n$this->errors['password'] = 'Invalid Password combination'; // or this error\n</code></pre>\n\n<p>If there's a class tracking all errors (why, what's the use/benefit) - it should either be asking individual instances what errors they contain, or some intermediary logic should be doing that. If the error class just contains an array of strings, there's no context to know why of where an error came from. Using DI is fine, but not having a needless dependency is better.</p>\n\n<p>As a related point the function <code>authenticate</code> only returns true or null. It would be preferable to always return something:</p>\n\n<pre><code>function authenticate() {\n if () {\n ...\n return true;\n }\n return false; // default deny\n}\n</code></pre>\n\n<h2>Write reusable/configurable classes</h2>\n\n<p>Instead of this:</p>\n\n<pre><code>$foo = new Login($pdo, ...);\n...\n$bar = new Login($pdo, ...); // oops, need to try and login again with different props\n</code></pre>\n\n<p>Make it easy to (re)configure an existing instance:</p>\n\n<pre><code>$foo = new Login($pdo);\nif ($foo->authenticate($_POST)) {\n ...\n}\n...\n$foo->reset();\n$foo->checkOldPasswordTable(); // old passwords were stored with a different hash function\nif ($foo->authenticate($_POST)) {\n ...\n}\n</code></pre>\n\n<h2>Write testable code</h2>\n\n<p>The above point is a pseudo-contrived example, unit tests are possibly a better example of when you'd want to not keep creating new objects.</p>\n\n<p>the login credentials are not something that are required at the time the Login class is created:</p>\n\n<pre><code>$foo = new Login($pdo);\n\n$result = $foo->authenticate(array('user' => 'testuser1', 'password' => 'correct password'));\n$this->assertTrue($result, \"User was not authenticated but expected to be so\");\n\n$result = $foo->authenticate(array('user' => 'testuser1', 'password' => 'wrong password'));\n$this->assertFalse($result, \"User was authenticated with a wrong password\");\n</code></pre>\n\n<p>When the time comes to write unit tests, the code shouldn't need to be modified. Changes to make code testable are usually trivial - and just mean planning ahead and having appropriate methods to set and get data.</p>\n\n<h2>Be secure</h2>\n\n<p>As indicated by other answers an unsalted sha1 password is weak. Passwords should be stored such that even if someone gets access to the database, they can't determine the original password.</p>\n\n<p>It's <em>not</em> hard to store passwords securely, here's some pseudo code:</p>\n\n<pre><code>function register($username, $password) {\n $salt = '$2a$10$' . substr(md5(time()), 0, 22);\n $storeThis = crypt($password, $salt);\n\n return $this->save(array(\n 'username' => $username,\n 'password' => $storeThis\n ));\n}\n\nfunction login($username, $password) {\n $dbUser = $this->findByUsername($username);\n\n if (!$dbUser) {\n return false;\n }\n if (crypt($password, $dbUser->password) === $dbUser->password) {\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>By using <a href=\"http://php.net/manual/en/function.crypt.php\" rel=\"nofollow\">crypt</a> and blowfish (the string '$2a$' indicates to use blowfish encryption) passwords are stored securely such that password leaks such as the recent linkedin incident become a none issue.</p>\n\n<h2>Be configurable</h2>\n\n<p>In the above code example, blowfish and a cost parameter of 10 is used. Instead it would be better to make the hash algorighm used configurable:</p>\n\n<pre><code>protected $_algorighm = 'blowfish';\n\nprotected $_cost = 10;\n\npublic function setAlgorithm($algo, $cost = null) {\n // verify algo is a possibility and the cost is appropriate\n ...\n $this->_algorithm = $algo;\n $this->_cost = $cost;\n}\n\nfunction register($username, $password) {\n $salt = $this->_getSalt();\n $storeThis = crypt($password, $salt);\n\n return $this->save(array(\n 'username' => $username,\n 'password' => $storeThis\n ));\n}\n\nprotected function _getSalt($salt = '') {\n $length = 0;\n\n switch ($this->_algorithm) {\n case 'des':\n $template = '%s';\n $length = 2;\n break;\n case 'md5':\n $template = '$1$%s';\n $length = 12;\n break;\n case 'blowfish':\n $template = '$2a$%d$%s';\n break;\n case 'sha256':\n $template = '$5$rounds=%d';\n break;\n case 'sha512':\n $template = '$6$rounds=%d';\n break;\n default:\n $template = '';\n }\n\n return sprintf($template, $this->_cost, $this>_getRandomString($length));\n}\n\nprotected function _getRandomString($length = 0) {\n return substr(md5(time()), 0, $length);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T04:04:06.727",
"Id": "29024",
"Score": "0",
"body": "Hey AD7six! I don't know where to start, your answer was quite descriptive. It is much appreciated. Your answer is definitely going to help a lot of people! Everyone's answer was great but this one goes above and beyond! Thanks for that. In response to what you wrote about the handling errors part. The current project I am working on (like you assumed) has multiple classes. If there is an error when a user logs in, or there is an error when a user submits one of the other many forms, I need some way to display the list of errors to the user."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T04:06:30.780",
"Id": "29025",
"Score": "0",
"body": "I'm very confused on what to do? I also want to learn the best way for much more complex projects than the current one I am working on. I want to learn the best way for complex projects. How would you handle errors? With an array or with an error class? You mention both ways. If I use an error class as a singleton, then I can call the getErrors() method of it. And pass the Error object into each of the classes that use it. But you also mention not using the singleton, and instead using a simple errors array. I'm confused as far as that goes. So I'm kind of just as stuck on the \"errors\" portion"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T04:07:01.123",
"Id": "29026",
"Score": "0",
"body": "as I was when I first made the post. Although I learned a TREMENDOUS amount from everything else you wrote and I really appreciate those teachings!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T11:21:35.680",
"Id": "29039",
"Score": "0",
"body": "I [edited the answer](http://codereview.stackexchange.com/posts/18163/revisions) to clarify that the error object is not something I recommend. if you want to put all errors in a single place you can do so e.g. like this `$_SESSION['errors'][] = \"a new error occurred\";` and loop on `$_SESSION['errors']` somewhere in your presentational code to advise the user (and delete from the session on display). That would be by querying objects for error or *in addition* to logging errors to an internal class property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T16:31:17.123",
"Id": "29057",
"Score": "0",
"body": "Thanks!!! So are you suggesting that the best way to capture errors is.. inside of each class that captures errors, whenever an error occurs like \"invalid user\", \"required field missing\", etc, would be to do $_SESSION['errors']['Name To Display To Screen']= \"description of message to display to user\". ? But if I do this, my classes will be sprinkled with $_SESSION['errors'][] = \"\". Is that still following with best practices? I'm a tough cookie, I know. I just want to do it the best way! :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T21:39:12.673",
"Id": "18163",
"ParentId": "18068",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18163",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T02:39:13.757",
"Id": "18068",
"Score": "14",
"Tags": [
"php",
"php5"
],
"Title": "How would a senior PHP developer design this Login class?"
}
|
18068
|
<p>This function was hard to write as a Clojure newbie, and I don't like the result.
Can you help me find a better (more readable) way to do it?</p>
<pre><code>(defn split-seq
"Splits a seq into blocks defined by start-fn and stop-fn.
Returns a lazy seq of seqs"
[start-fn stop-fn lines]
(let [step (fn [c state]
(when-let [s (seq c)]
(if (stop-fn (first s))
(cons state (split-seq start-fn stop-fn (rest s) ))
(recur (rest s)
(if (start-fn (first s))
'()
(cons (first s) state))))))]
(lazy-seq (step lines '()))))
(defn post-start? [l] (.startsWith l "#ENTRY_START"))
(defn post-end? [l] (.startsWith l "#ENTRY_END"))
(defn split-lines
"Split a line-seq into entries based on #ENTRY_START and #ENTRY_END."
[data]
(split-seq post-start? post-end? data))
;
; Test
;
(def test-data [
"Header line"
"#ENTRY_START"
"entry line 1 "
"entry line 2"
"#ENTRY_END"
"This line should be filtered out"
"#ENTRY_START Having data here shouldn't make a difference."
"entry line 1 "
"entry line 2"
"#ENTRY_END"
"This should be gone too"])
(split-lines test-data)
; yields (("entry line 2" "entry line 1 ") ("entry line 2" "entry line 1 "))
; The order of elements doesn't matter in my case because I'm making a map with this data
</code></pre>
<p>With Arthurs help, the final code looks like this: </p>
<pre><code>(defn entry-seq [data]
(let [[f r] (split-with #(not (post-end? %))
(rest (drop-while #(not (post-start? %)) data)))]
(when (not-empty f) (lazy-seq (cons f (entry-seq2 r))))))
</code></pre>
<p>Still lazy and a lot more readable!</p>
|
[] |
[
{
"body": "<p>So the idea in this new approach is to write two expressions:</p>\n\n<ul>\n<li>one that extracts the next expresstion:<br>\n<code>(take-while #(not= \"#ENTRY_END\" %) \n (rest (drop-while #(not= \"#ENTRY_START\" %) data)))</code></li>\n<li>one that extracts everything after the next expression<br>\n<code>(rest (drop-while #(not= \"#ENTRY_END\" %) \n (rest (drop-while #(not= \"#ENTRY_START\" %) data))))</code></li>\n</ul>\n\n<p>and then wrap them up into a lazy sequence:</p>\n\n<p>first lets expand the test data to include some additional edge cases:</p>\n\n<pre><code>user> (def test-data [\n \"Header line\"\n \"#ENTRY_START\"\n \"entry line 1 \"\n \"entry line 2\"\n \"#ENTRY_END\"\n \"not part of an entry\"\n \"also not part of an entry\"\n \"#ENTRY_START\"\n \"entry line 1 \"\n \"entry line 2\"\n \"#ENTRY_END\"\n \"footer1\"\n \"footer2\"])\n</code></pre>\n\n<p>then wrap our two expressions into a function:</p>\n\n<pre><code>user> (defn entry-seq [data] \n (let [f (take-while #(not= \"#ENTRY_END\" %) \n (rest (drop-while #(not= \"#ENTRY_START\" %) data))) \n r (rest (drop-while #(not= \"#ENTRY_END\" %) \n (rest (drop-while #(not= \"#ENTRY_START\" %) data))))] \n (when (not-empty f) (lazy-seq (cons f (entry-seq r))))))\n#'user/entry-seq\n</code></pre>\n\n<p>and we test it:</p>\n\n<pre><code>user> (take 4 (entry-seq test-data))\n((\"entry line 1 \" \"entry line 2\") (\"entry line 1 \" \"entry line 2\"))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T07:44:53.483",
"Id": "28798",
"Score": "0",
"body": "Thanks. I started out that way, but to filter out anything between or outside delimiters, I have to know too much about the contents. All this function should know about is start-fn and end-fn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T07:46:23.467",
"Id": "28799",
"Score": "0",
"body": "There can be lines before, after or in-between. I want to get rid of those without knowing what they are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T08:01:24.790",
"Id": "28802",
"Score": "0",
"body": "I'll fix this answer then ... please stand by!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T08:05:42.593",
"Id": "28803",
"Score": "0",
"body": "I updated the test data to show more what I had in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T08:58:15.407",
"Id": "28805",
"Score": "0",
"body": "if they weren't already broken into a sequence of string then this would just be one call to `re-seq`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T09:35:32.443",
"Id": "28807",
"Score": "0",
"body": "Thanks again! I put my start/stop functions back in and it works with my test data. I didn't like the repetition for f and r so I changed it to split-with. See my updated answer. Short and readable."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T07:41:57.880",
"Id": "18072",
"ParentId": "18071",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T07:15:58.680",
"Id": "18071",
"Score": "5",
"Tags": [
"clojure"
],
"Title": "String-splitting function"
}
|
18071
|
<p>So my app needed a cookie store that persists over the app closing, device reboot etc. I decided to use the sharedPreferences for this. The class works pretty well, in both my tests and on the device. However there are couple of things I think can be improved. First is error handling. The problem is I cannot throw the errors further up in the app as the cookiestore interface doesn't not allow it. Secondly I have made a persistantcookie so I have a concrete class to serialise. I then convert that to the cookie interface. It seems an ugly way to do it. So any pointers would be very much appreciated.</p>
<pre><code>public class BetterPersistantCookieStore implements CookieStore {
private static final String TAG = BetterPersistantCookieStore.class.getSimpleName();
private SharedPreferences sharedPreferences;
private ObjectMapper objectMapper = new ObjectMapper();//TODO pass serializer and deserialiser into constructor
private static final String COOKIES_KEY = "cookiesKey";
@Inject
public BetterPersistantCookieStore(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
@Override
public void addCookie(Cookie cookie) {
List<PersistantCookie> cookieList = getPersistantCookies();
int len = cookieList.size();
for (int i = 0; i < len; ++i) {
Cookie tempCookie = cookieList.get(i);
if (cookie.getName().equals(tempCookie.getName())) {
cookieList.remove(i);
}
}
cookieList.add(new PersistantCookie(cookie));
sharedPreferences.edit().putString(COOKIES_KEY, listToString(cookieList)).commit();
}
@Override
public List<Cookie> getCookies() {
return convertPersistantCookiesToCookies(getPersistantCookies());
}
@Override
public boolean clearExpired(Date date) {
List<PersistantCookie> cookieList = getPersistantCookies();
int len = cookieList.size();
boolean returnValue = false;
for (int i = 0; i < len; ++i) {
Cookie cookie = cookieList.get(i);
if (cookie.isExpired(date)) {
cookieList.remove(i);
returnValue = true;
}
}
sharedPreferences.edit().putString(COOKIES_KEY, listToString(cookieList)).commit();
return returnValue;
}
@Override
public void clear() {
sharedPreferences.edit().remove(COOKIES_KEY).commit();
}
private List<PersistantCookie> getPersistantCookies() {
return stringToList(sharedPreferences.getString(COOKIES_KEY, ""));
}
private List<PersistantCookie> stringToList(String value) {
try {
return objectMapper.readValue(value, TypeFactory.collectionType(ArrayList.class, PersistantCookie.class));
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<PersistantCookie>(0);
}
}
private String listToString(List<PersistantCookie> cookies) {
try {
return objectMapper.writeValueAsString(cookies);
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
private List<Cookie> convertPersistantCookiesToCookies(List<PersistantCookie> persistantCookies) {
List<Cookie> cookies = new ArrayList<Cookie>();
for (Cookie cookie : persistantCookies) {
cookies.add(cookie);
}
return cookies;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T12:41:19.187",
"Id": "28811",
"Score": "0",
"body": "It is persistent ... not persistant."
}
] |
[
{
"body": "<blockquote>\n <p>First is error handling. The problem is I cannot throw the errors further up in the app as the cookiestore interface doesn't not allow it. </p>\n</blockquote>\n\n<p>You can define a custom <strong>unchecked</strong> exception and throw that. (Or throw an existing unchecked exception if you can find one that is suitable.)</p>\n\n<blockquote>\n <p>Secondly I have made a persistantcookie so I have a concrete class to serialise. I then convert that to the cookie interface. It seems an ugly way to do it.</p>\n</blockquote>\n\n<p>I don't think you have any sensible alternatives. (And besides, I disagree that it is \"ugly\".)</p>\n\n<hr>\n\n<p>And please correct the spelling of (at least) the public class and method names. It is like chalk screeching on a blackboard ...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T12:49:14.303",
"Id": "18078",
"ParentId": "18073",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18078",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T10:36:42.423",
"Id": "18073",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "Persistent Cookie Store"
}
|
18073
|
<p>I am fresh at OOP and I am curious if the code below is object oriented and can be improved:</p>
<pre><code>class cTitleBreadcrumb {
public function __construct($sAction, $sItem){
$this->sAction = $sAction;
$this->sItem = $sItem;
}
public function displayAction(){
if($this->checkUrlAction($this->sAction) === true){
return $this->sAction;
}
}
public function displayItem(){
if($this->checkUrlItem($this->sItem) === true){
return $this->sItem;
}
}
private function checkUrlAction($sAction){
if($sAction == 'insert' || $sAction == 'view' || $sAction == 'update' || $sAction == 'delete'){
return true;
}
}
private function checkUrlItem($sItem){
if($sItem == 'imagelist' || $sItem == 'mkdir' || $sItem == 'rdir'){
return true;
}
else{
$objShowPDO = new mShowPDO();
$result = $objShowPDO->allTables();
while($array = $result->fetch()){
if($array[0] == $this->sItem){
return true;
}
}
}
}
$objTitleBreadcrumb = new cTitleBreadcrumb($sAction,$sItem);
echo ucfirst($objTitleBreadcrumb->displayAction());
echo ucfirst($objTitleBreadcrumb->displayItem());
</code></pre>
|
[] |
[
{
"body": "<h2>You are not always returning anything</h2>\n\n<pre><code>private function checkUrlAction($sAction) {\n if(true){ \n return true;\n }\n\n //but else?\n}\n</code></pre>\n\n<h2>Dependency injection</h2>\n\n<p>$objShowPDO = new mShowPDO(); is bad a mShowPDO instance should by injected via method or constructor argument see dependency injection topics</p>\n\n<pre><code>private function checkUrlItem(mShowPDO $objShowPDO, $sItem){\n if($sItem == 'imagelist' || $sItem == 'mkdir' || $sItem == 'rdir'){\n return true;\n }\n\n //redundand else removed\n\n $result = $objShowPDO->allTables(); //maybe you can inject only the result\n while($array = $result->fetch()){\n if($array[0] == $this->sItem){\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n\n<h2>Hard coding</h2>\n\n<p>The checklists are really hard coded (long if with OR relations), try use some container for them (an array and use in_array() for example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T16:03:52.080",
"Id": "28812",
"Score": "0",
"body": "Hi Peter, thanks for your reply. What do you mean by You are not always returning anything and whats the solution for this dependency injection?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T16:56:24.200",
"Id": "28813",
"Score": "0",
"body": "He means that for the display functions you should always return something. If the sAction doesn't pass your check you don't return anything from `displayAction()` (and same for displayItem)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T18:49:06.853",
"Id": "28818",
"Score": "0",
"body": "@Peter, do you mean like mysql_real_escape_string for mysql_*?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:03:42.533",
"Id": "28825",
"Score": "0",
"body": "Sorry, but i don't understand how the mysql_ stuff comes here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T04:13:25.060",
"Id": "28846",
"Score": "0",
"body": "ahh ok i understand thanks. But i dont understand the PDO Dependency injection, can you explain it, whats exactly the problem and how can code it correctly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T07:09:14.087",
"Id": "28854",
"Score": "0",
"body": "See this for example: http://stackoverflow.com/questions/130794/what-is-dependency-injection"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T14:31:41.110",
"Id": "18081",
"ParentId": "18077",
"Score": "1"
}
},
{
"body": "<p>Just little improvement to write this method shorter</p>\n\n<pre><code>private function checkUrlAction($sAction)\n{\n return in_array($sAction , array('insert','view','update''delete'));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T18:47:37.193",
"Id": "28817",
"Score": "0",
"body": "A recommend to put the array in a class field."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T18:52:44.530",
"Id": "28820",
"Score": "0",
"body": "@Peter put an array in a class field, what do you mean by that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:00:46.800",
"Id": "28824",
"Score": "0",
"body": "class cTitleBreadcrumb { private $_actions = array(...) } and then in the return statement: return in_array($sAction, $this->_actions));"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:17:41.983",
"Id": "28828",
"Score": "0",
"body": "ahh ok i understand thanks. \nBut i dont understand the PDO Dependency injection, can you explain it, whats exactly the problem and how can code it correctly?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T17:47:52.220",
"Id": "18089",
"ParentId": "18077",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T12:45:03.887",
"Id": "18077",
"Score": "3",
"Tags": [
"beginner",
"php",
"object-oriented"
],
"Title": "PHP breadcrumb class"
}
|
18077
|
<p>I want to make sure <code>find_value_from_key()</code> is safe and efficient. My constraints are language C++, use of standard library ok, but cannot use Boost or any new C++11 features.</p>
<p>Can anyone offer any comments/criticisms/feedback on my implementation of the function here? Any flaws in my test cases would also be interesting to hear.</p>
<pre><code>#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
bool find_value_from_key(const string& source, const string& key, string& value, const string& EndOfValueMarker) {
bool ret = false;
size_t pos_start = source.find(key);
if(pos_start != string::npos) {
size_t pos_end = source.find_first_of(EndOfValueMarker, pos_start+key.length());
if(pos_end == string::npos && source.length() > pos_start+key.length())
pos_end = source.length();
if(pos_end != string::npos) {
value = source.substr(pos_start+key.length(), pos_end-pos_start-key.length());
ret = true;
}
}
return ret;
}
int main(int argc, char* argv[])
{
//test strings to exercise find_value_from_key function
const char* test_strings[] = {
"key1 = value1",
" key1 = value1 ",
"key1 = value1,key2 = value2 ,key3 = value3",
"_key1 = value1 ,key2 = value2 ,Gkey3 = value3,",
"key1 = value1,key2 = value2 ,key3 = value3 x",
"key1 = value1,key2 = value2key3 = value3\n",
"key1 = value1_,key2 = value2 ,key3 = value3 ",
"key1 = value1$,key2 = value2 ,key3 = value3",
"key1 = value1\t,key2 = value2 ,key3 = value3\t" };
const char* keys[] = {"key1 = ", "key2 = ", "key3 = "};
int elements = sizeof(test_strings) / sizeof(test_strings[0]);
for(int i = 0; i < elements; ++i) {
cout << "processing: " << test_strings[i] << endl;
string value;
if(find_value_from_key(test_strings[0], keys[0], value, ", \t\n"))
cout << value << endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T19:24:41.173",
"Id": "28932",
"Score": "1",
"body": "What is the ultimate goal with this code. Are you being provided with comma separated key value pairs? Are you going to be doing repeated searches of this string of data? Will your keys always be unique in the string you are given? This implementation is case sensitive, do you need to worry about case insensitive key lookup?"
}
] |
[
{
"body": "<h2>find_value_from_key</h2>\n<p>The core method <code>find_value_from_key</code> looks functional for the limited specification you have given. I am not a great fan of the specification though, I think the function should try to be a bit smarter about identifying values in the input strings. The two items I find most concerning are:</p>\n<ul>\n<li>It will successfully find <code>key1 = </code> and <code>value1</code> in <code>"ThisIsSubkey1 = value1"</code></li>\n<li>it does not successfully find <code>value1</code> in <code>"key1 = value1"</code> (note two spaces after <code>=</code>)</li>\n</ul>\n<p>These are both items related to the context-naive usage of the <code>find(...)</code> method.</p>\n<p>Still, as far as the specification goes, your code looks like it does the job.</p>\n<p>There is one improvement that can/should be done to make it more readable. You reuse the value <code>pos_start+key.length()</code> four times. Performance-wise this may be sorted out by a compiler, but it does not help the readability at all...</p>\n<p>I would prefer the function written as:</p>\n<pre><code>bool find_value_from_key(const string& source, const string& key, string& value, const string& endmarkers) {\n bool ret = false;\n size_t key_start = source.find(key);\n size_t val_start = key_start + key.length();\n if(key_start != string::npos) {\n size_t val_end = source.find_first_of(endmarkers, val_start);\n if(val_end == string::npos && source.length() > val_start)\n val_end = source.length();\n\n if(val_end != string::npos) {\n value = source.substr(val_start, val_end - val_start);\n ret = true;\n }\n }\n return ret;\n}\n</code></pre>\n<p>Note how there is no <code>pos_start</code> variable... it was being reused for different purposes in different places. It was confusing. Renaming the variables to self-document makes the code easier to understand. The compiler will sort out any optimizations in the same ways as before.</p>\n<p>There is one additional item in that method... why the CamelCase parameter <code>EndOfValueMarker</code>? I have renamed it <code>endmarkers</code>.</p>\n<h2>main</h2>\n<p>The main method has a couple of issues I think must just be an artifact from testing.</p>\n<p>You set up the loop to check each input string, but, you do not use <code>i</code> (the loop variable) as an index to the actual data you check... you have the code:</p>\n<blockquote>\n<pre><code> for(int i = 0; i < elements; ++i) {\n cout << "processing: " << test_strings[i] << endl;\n string value;\n if(find_value_from_key(test_strings[0], keys[0], value, ", \\t\\n"))\n cout << value << endl;\n }\n</code></pre>\n</blockquote>\n<p>This code prints each <code>test_strings[i]</code> just fine, but the input to the function is always index <code>0</code>... so you only actually test the first input.</p>\n<p>The second item is that you only test for key1. The other keys are not tested.</p>\n<p>The loop code should look like:</p>\n<pre><code>for(int i = 0; i < elements; ++i) {\n cout << "processing: " << test_strings[i] << endl;\n string value;\n for (int k = 0; k < 3; k++) {\n if(find_value_from_key(test_strings[i], keys[k], value, ", \\t\\n"))\n cout << keys[k] << " -> " << value << endl;\n }\n}\n</code></pre>\n<p>I know, it has the magic number <code>3</code> for the k loop, but at least it checks each key....</p>\n<h2>Ideone</h2>\n<p>I have put my recommendations in to <a href=\"http://ideone.com/mvsW8X\" rel=\"noreferrer\">this ideone... take it for a spin</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T03:49:24.480",
"Id": "42570",
"ParentId": "18079",
"Score": "5"
}
},
{
"body": "<p>@rolfl has mentioned some great points, so I won't repeat those. I'll address some C++-specific things I've found, keeping in mind that Boost and C++11 shouldn't be mentioned.</p>\n\n<ul>\n<li><p>These <code>using</code> statements:</p>\n\n<pre><code>using std::cout;\nusing std::endl;\nusing std::string;\n</code></pre>\n\n<p>are okay to use, but I'd still use <code>std::</code> where needed, especially if this list ends up getting longer. But this is still better than having <code>using namespace std</code>.</p></li>\n<li><p>Regarding the use of <code>char* []</code>:</p>\n\n<p>For this:</p>\n\n<pre><code>int elements = sizeof(test_strings) / sizeof(test_strings[0]);\n</code></pre>\n\n<p><code>elements</code> should be of type <code>std::size_t</code>, which is the return type of the <code>sizeof</code> operator. You should also give it a more accurate name, such as <code>numberOfElements</code>.</p>\n\n<p>Moreover, you shouldn't be needing to do this in C++ when you have access to the standard library. You can instead have an <code>std::vector</code> of <code>std::string</code>s instead of <code>char* []</code>.</p>\n\n<p>For instance, this is what <code>test_strings</code> would look like:</p>\n\n<pre><code>std::vector<std::string> test_strings = { /* string 1 */, /* string n */ };\n</code></pre>\n\n<p>To get the size, just use <code>size()</code>:</p>\n\n<pre><code>std::vector<std::string>::size_type elements = test_strings.size();\n</code></pre>\n\n<p>This type should also be used when incrementing through the number of <code>element</code>s.</p>\n\n<p>Instead of using <code>test_strings[0]</code> to access the first element, you can use <code>front()</code>:</p>\n\n<pre><code>test_strings.front();\n</code></pre>\n\n<p>I've also done a quick example test of all this <a href=\"http://ideone.com/zYwDM9\" rel=\"nofollow\">here</a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T05:33:41.560",
"Id": "42576",
"ParentId": "18079",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T12:52:19.357",
"Id": "18079",
"Score": "7",
"Tags": [
"c++",
"parsing"
],
"Title": "Token-finding function"
}
|
18079
|
<p>I'm learning Go at this moment and it is my first program in Go, so I will be thankfull for any suggestion, remarks and observations.</p>
<pre><code>package main
import (
"fmt"
)
const ascii = "abcdefghijklmnopqrstuvwxyz"
var goodness_values = []float32 { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 }
func zip(s1 string, s2 string) map[string]string {
result := make(map[string] string)
for i, v := range s1 {
result[string(v)] = string(s2[i])
}
return result
}
func crypt(s string, table map[string]string) string {
result := ""
for _, v := range s {
result += table[string(v)]
}
return result
}
func encode(message string, key int) string {
shifted_ascii := ascii[key:] + ascii[:key]
trans_table := zip(ascii, shifted_ascii)
return crypt(message, trans_table)
}
func decode(secret string, key int) string {
shifted_ascii := ascii[key:] + ascii[:key]
trans_table := zip(shifted_ascii, ascii)
return crypt(secret, trans_table)
}
func goodness(version string, letter_goodness map[string] float32) float32 {
var result float32 = 0.0
for _, v := range version {
result += letter_goodness[string(v)]
}
return result
}
func crack(secret string) string {
var best_score float32 = 0.0
result := ""
letter_goodness := make(map[string] float32)
for i, v := range ascii {
letter_goodness[string(v)] = goodness_values[i]
}
for i := 0; i <= 26; i++ {
version := decode(secret, i);
score := goodness(version, letter_goodness);
if(score > best_score) {
best_score = score
result = version
}
}
return result
}
func main() {
fmt.Printf("%s\n", encode("hello", 10))
fmt.Printf("%s\n", decode("rovvy", 10))
fmt.Printf("%s\n", crack("pybrscpexnkwoxdkvmyxdbsledsyxcdydronopsxsdsyxkxnnocsqxypzbyqbkwwsxqvkxqekqoc"))
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-06T21:37:21.280",
"Id": "377471",
"Score": "0",
"body": "This question is on-topic, it is \" [concrete code from a project, with sufficient context](https://codereview.meta.stackexchange.com/a/3652) for reviewers to understand how that code is used\" . This is not Pseudocode, stub code, hypothetical code or obfuscated code."
}
] |
[
{
"body": "<p>It looks like it was written in another language and then translated to Go. It looks complicated. Go is designed to be efficient. Maps are not as efficient as slices and arrays for simple indexing. <code>decode(secret, i)</code> executes 26 times instead of once. Etc.</p>\n\n<p>Here's an alternate version,</p>\n\n<pre><code>package main\n\nimport \"fmt\"\n\nconst alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\nfunc rotate(s string, rot int) string {\n rot %= 26\n b := []byte(s)\n for i, c := range b {\n c |= 0x20\n if 'a' <= c && c <= 'z' {\n b[i] = alphabet[(int(('z'-'a'+1)+(c-'a'))+rot)%26]\n }\n }\n return string(b)\n}\n\nfunc decode(cipher string, rot int) (text string) {\n return rotate(cipher, -rot)\n}\n\nfunc encode(text string, rot int) (cipher string) {\n return rotate(text, rot)\n}\n\nvar frequencies = []float32{\n .0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241,\n .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007,\n}\n\nfunc crack(cipher string) (text string) {\n var sums [26]float32\n for _, c := range cipher {\n c |= 0x20\n for j := range sums {\n if 'a' <= c && c <= 'z' {\n sums[j] += frequencies[(int(c)-int('a')+j)%26]\n }\n }\n }\n var maxi, maxsum = 0, float32(0)\n for i, sum := range sums {\n if sum > maxsum {\n maxsum = sum\n maxi = i\n }\n }\n return rotate(cipher, maxi)\n}\n\nfunc main() {\n fmt.Printf(\"%s\\n\", encode(\"hello\", 10))\n fmt.Printf(\"%s\\n\", decode(\"rovvy\", 10))\n fmt.Printf(\"%s\\n\", crack(\"pybrscpexnkwoxdkvmyxdbsledsyxcdydronopsxsdsyxkxnnocsqxypzbyqbkwwsxqvkxqekqoc\"))\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>rovvy\nhello\nforhisfundamentalcontributionstothedefinitionanddesignofprogramminglanguages\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T09:53:19.067",
"Id": "28855",
"Score": "0",
"body": "Thank you very much for your help. Expression '('z'-'a'+1)+' as I see can be removed from code ? Am I right ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T09:54:30.313",
"Id": "28856",
"Score": "0",
"body": "And another one question: what is 'c |= 0x20' ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-12T07:57:24.687",
"Id": "29472",
"Score": "2",
"body": "`|` is the bitwise-or operator, `|=` in turn ORs the lhs with the rhs and assigns it to the lhs. ORing an ASCII character with `0x20` has the effect of converting uppercase to lowercase (and leaving numbers and symbols untouched)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T03:18:00.487",
"Id": "18102",
"ParentId": "18080",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18102",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T12:57:38.877",
"Id": "18080",
"Score": "6",
"Tags": [
"beginner",
"go",
"caesar-cipher"
],
"Title": "My first Go program: Caesar Cipher"
}
|
18080
|
<p>I'm writing out two numbers separated with a dash. The first number is padded with leading zeros until 6 digits, the second number, 4.</p>
<pre><code>string taskNumber = order.ID.ToString("D6") + "-" + task.ID.ToString("D4");
</code></pre>
<p>If I was going to rewrite this using string.Format I would simply say:</p>
<pre><code>string taskNumber = string.Format("{0}-{1}", order.ID.ToString("D6"), task.ID.ToString("D4"));
</code></pre>
<p>Is there anything I can do with <code>string.Format</code>'s <code>{0}</code> and <code>{1}</code> to say that I want my numbers padded? Calling <code>ToString</code> is a bit verbose, IMO.</p>
|
[] |
[
{
"body": "<p>Sure. Simply include the padding specifier directly in the format string:</p>\n\n<pre><code>string taskNumber = string.Format(\"{0:D6}-{1:D4}\", order.ID, task.ID);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T16:57:30.873",
"Id": "18086",
"ParentId": "18084",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "18086",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T16:28:38.643",
"Id": "18084",
"Score": "8",
"Tags": [
"c#",
"strings",
"formatting"
],
"Title": "Formatting a number"
}
|
18084
|
<p>I currently use this code pattern fairly frequently</p>
<pre><code>if(array_key_exists('possible_key', $array)) {
$my_variable = $array['possible_key'];
} else {
$my_variable = 'my default value';
}
</code></pre>
<p>Is there a better way to be writing this?</p>
|
[] |
[
{
"body": "<p>One quick change you can do is making use of ternary operator instead of writing if else block.</p>\n\n<pre><code>$my_variable = array_key_exists('possible_key', $array) \n ? $array['possible_key'] \n : 'my default value';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T17:33:39.867",
"Id": "28815",
"Score": "2",
"body": "Never thought of using multiple lines with the ternary operator before, though I can see how this would be a very long line otherwise (and it does seem more readable like this). Is it considered a best practice to do this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T01:44:05.820",
"Id": "28836",
"Score": "0",
"body": "**Side note:** What's the difference between `array_key_exists('possible_key', $array)` and `isset($array['possible_key'])`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T03:01:26.080",
"Id": "28841",
"Score": "2",
"body": "@JosephSilber `$array['possible_key'] = null;` `isset($array['possible_key']); /* false */ array_key_exists('possible_key', $array); /* true */`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T17:14:53.433",
"Id": "18087",
"ParentId": "18085",
"Score": "6"
}
},
{
"body": "<p>I prefer to use use isset and make little refactor and wrap that code to function/method</p>\n\n<pre><code>function defaultize( $array_var ,$defaul_val ){\n if(isset($array_var)) {\n $ret = $array_var;\n } else {\n $ret = 'my default value';\n }\n return $ret;\n}\n</code></pre>\n\n<p>and then use in code</p>\n\n<pre><code>$my_variable = defaultize($array['possible_key'],'my default_value' );\n$my_variable2 = defaultize($array['possible_key2'],'my default_value2' );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T18:52:11.457",
"Id": "28819",
"Score": "1",
"body": "defaultize($array['possible_key'],'my default_value' ); <-- if 'possible_key' dows not exists the PHP will throw an E_NOTICE warning and your function body is messed up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T18:52:51.080",
"Id": "28821",
"Score": "0",
"body": "`$array` seem uninitialized inside the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:23:14.420",
"Id": "28829",
"Score": "0",
"body": "Ups, sorry just fixed that"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T17:41:05.357",
"Id": "18088",
"ParentId": "18085",
"Score": "-4"
}
},
{
"body": "<p>Untested code here as I don't have access to my dev machine, but taking Sky's ternary suggestion above and simplifying it (one empty() call is faster than an array_key_exists (see <a href=\"https://stackoverflow.com/questions/6884609/array-key-existskey-array-vs-emptyarraykey\">https://stackoverflow.com/questions/6884609/array-key-existskey-array-vs-emptyarraykey</a>)</p>\n\n<pre><code>$var = empty($array['possible_key']) ? 'default value' : $array['possible_key']; \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T01:45:27.427",
"Id": "28837",
"Score": "1",
"body": "If `$array['possible_key']` is set to `''` or `0`, this'll return `'default value'`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T03:05:17.390",
"Id": "28842",
"Score": "1",
"body": "\"one empty() call is faster than an array_key_exists\" Correct functionality is a lot more important than performance (in this context, though also usually in general). But yes, if he's willing to ignore values containing 0, empty, `'0'`, etc, this is shorter and a tiny bit faster. (`isset` would probably be a better fit here than `empty` by the way. `isset` has fewer false negatives in this context.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T03:49:48.910",
"Id": "28845",
"Score": "0",
"body": "Ah...true guys....woops"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T23:17:26.090",
"Id": "18098",
"ParentId": "18085",
"Score": "-2"
}
},
{
"body": "<p>I would prefer to keep it simple and not to use if else.\nJust assign it the default value, and change only when the condition meets.</p>\n\n<pre><code>$my_variable = 'my default value';\nif(array_key_exists('possible_key', $array)) $my_variable = $array['possible_key'];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T09:33:52.900",
"Id": "18109",
"ParentId": "18085",
"Score": "1"
}
},
{
"body": "<p>Is there an atomic way to check if the value exists by a key AND return the value, so there will be just one query to the array? I think that this was the original idea of the author of the question. In a very large array, all examples here have shown essentially too lookup: for example <code>array_key_exists('possible_key', $array) ? $array['possible_key']</code> etc...</p>\n<p>A better way would be a single operation with the array that would not give a PHP run time warning in the key does not exist.</p>\n<p>Unfortunately, PHP does not have an atomic check-and-lookup. So, the answer to the author's question is <strong>"NO, this is not possible in PHP to check and lookup in one operation".</strong></p>\n<p>However, on the question of "is there a better way to be writing this", the answer is "YES, you can <a href=\"https://rules.sonarsource.com/java/RSPEC-1192\" rel=\"nofollow noreferrer\">avoid repeating string literals</a> and <a href=\"https://larryullman.com/2008/10/29/using-the-ternary-operator-in-php\" rel=\"nofollow noreferrer\">use ternary operator</a>, but there still be two operations with the array". So here is an improved version of the author's code:</p>\n<pre><code>$my_key = 'possible_key'; $my_variable = (array_key_exists($my_key, $array)) ? $array[$my_key] : 'my default value';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-26T17:12:35.587",
"Id": "365493",
"Score": "0",
"body": "This re-statement of the question is what I was originally looking for, and what brought me here. It seems a single lookup isn't possible in PHP, but Hack has a built-in `idx()` with this behavior. https://docs.hhvm.com/hack/reference/function/HH.idx/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2017-04-18T01:06:18.750",
"Id": "161055",
"ParentId": "18085",
"Score": "0"
}
},
{
"body": "<p>A modern (PHP7+) solution in case you want a default value when <strong>either the element is not set or the value is null</strong>.</p>\n<pre><code>$my_variable = $array['possible_key'] ?? 'my default value';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T12:08:47.743",
"Id": "255934",
"ParentId": "18085",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18087",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T16:56:03.823",
"Id": "18085",
"Score": "5",
"Tags": [
"php"
],
"Title": "PHP checking for array key or using default value"
}
|
18085
|
<p>Users can define custom controls that are added to an entry form at run-time. The values of these controls are later stored in a MySQL database. Optionally, users can define 'recipes' to auto calculate some controls. </p>
<p>For an example, a user could enter Gross and Tare weight and use a FieldCalc for the Net Weight. In this case the ValueChanged event of both Gross and Tare will call FieldCalcValueChanged below. </p>
<p>Multiple recipes could be triggered by a change to a single field. There is no loop protection/detection.</p>
<p>CalcTotal does the work, processing each line of the recipe, then assigning the outputs. This could cascade other recipes.</p>
<p>In general, the above example is the normal case. In a few cases, there are 3-6 mileage fields, which total to a single field.</p>
<p>The code works great. But slowly. So much so, is some cases, that users choose to disable the FieldCalc recipes, and run a 10-key, which is not acceptable. </p>
<p>Any suggestions for speed or otherwise are appreciated.</p>
<p>configfieldcalc:</p>
<pre><code>id fieldcalcname code
---- --------------------------------------------- ----
2 NetWeight
6 MilesDifference
5 NetScale
7 MilesCalc
</code></pre>
<p>configfieldcalcstep:</p>
<pre><code>id configfieldcalcid step linetype output operator valuetype option notes
---- ----------------- ---- -------- --------------------------------------------- ------------------------ --------- --------------------------------------------- ---------------------------------------------
2 2 1 math weightnet math_assign metric weightgross
3 2 2 math weightnet math_subtract metric weighttare
7 5 1 if factor if_not_equal number 0
8 5 2 if weightnet if_not_equal number 0
9 5 3 math scalenet math_assign metric weightnet
10 5 4 math scalenet math_multiply number 1000.0000
11 5 5 math scalenet math_divide metric factor
12 5 6 round scalenet 0
13 5 7 endif
14 5 8 endif
19 6 1 if miles if_not_equal number 0
20 6 2 math milesdifference math_assign metric miles
21 6 3 math milesdifference math_subtract metric milesWaTotal
22 6 4 math milesdifference math_subtract metric milesWaOffroad
23 6 5 math milesdifference math_subtract metric milesOrLoaded
24 6 6 math milesdifference math_subtract metric milesOrEmpty
25 6 7 math milesdifference math_subtract metric milesOrRUAF
26 6 8 endif
15 7 1 if milesend if_not_equal number 0
16 7 2 math miles math_assign metric milesend
17 7 3 math miles math_subtract metric milesstart
18 7 4 endif
</code></pre>
<p>code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using LoggingControls;
using LoggingUtility;
namespace TicketEntry
{
public class FieldCalc
{
private static DataView _configFieldCalcStepView;
private readonly IEnumerable<ITicketRateMetric> _metricControls;
private readonly IEnumerable<Time> _timeControls;
static FieldCalc()
{
SetFieldCalcStepView();
}
static public void SetFieldCalcStepView()
{
_configFieldCalcStepView = new DataView
{
Table = LoggingUtility.Data.ConfigFieldCalcStep(),
Sort = "configfieldcalcid,step"
};
}
public FieldCalc(IEnumerable<ITicketRateMetric> metricControls, IEnumerable<Time> timeControls)
{
_metricControls = metricControls;
_timeControls = timeControls;
}
public void ClearEventHandlers()
{
Debug.WriteLine("<ClearEventHandlers>");
Debug.Indent();
foreach (ITicketRateMetric metric in _metricControls)
{
metric.ClearRateMetricValueChanged();
}
foreach (var time in _timeControls)
{
time.TextChanged -= FieldCalcValueChanged;
}
Debug.Unindent();
Debug.WriteLine("</ClearEventHandlers>");
}
public void SetEventHandlers()
{
Debug.WriteLine("<SetEventHandlers>");
Debug.Indent();
ClearEventHandlers();
var stepOptions = from DataRow basisstep in _configFieldCalcStepView.Table.Rows
where basisstep.Field<string>("valuetype") == "metric"
select new
{
configfieldcalcid = basisstep.Field<uint>("configfieldcalcid"),
option = basisstep.Field<string>("option")
};
foreach (var o in stepOptions)
{
try
{
var eo = o; //Must capture variable to avoid access to modified closure
var metric = (from control in _metricControls
where control.Name == eo.option
select control).First();
metric.RateMetricValueChanged += FieldCalcValueChanged;
}
catch (InvalidOperationException) { /* NOP */ }
}
stepOptions = from DataRow basisstep in _configFieldCalcStepView.Table.Rows
where basisstep.Field<string>("valuetype") == "time"
select new
{
configfieldcalcid = basisstep.Field<uint>("configfieldcalcid"),
option = basisstep.Field<string>("option")
};
foreach (var o in stepOptions)
{
try
{
var eo = o; //Must capture variable to avoid access to modified closure
var time = (from control in _timeControls
where control.Name == eo.option
select control).First();
time.TextChanged += FieldCalcValueChanged;
}
catch (InvalidOperationException) { /* NOP */ }
}
Debug.Unindent();
Debug.WriteLine("</SetEventHandlers>");
}
private void FieldCalcValueChanged(object sender, EventArgs e)
{
var s = sender as Control;
if (s != null)
{
CalcTotal(s.Parent.Name);
}
}
private void CalcTotal(string fieldTriggered)
{
var output = new Dictionary<string, decimal>();
var fieldCalcId = from DataRow basisstep in _configFieldCalcStepView.Table.Rows
where basisstep.Field<string>("option") == fieldTriggered
select basisstep.Field<uint>("configfieldcalcid");
foreach (var f in fieldCalcId)
{
_configFieldCalcStepView.RowFilter = string.Format("configfieldcalcid = '{0}'", f);
var skipIfCount = 0; //Track count of IF types, to find correct matching ENDIF, when there are nested IF types
foreach (DataRowView step in _configFieldCalcStepView)
{
Debug.WriteLine("LineType = " + step.Row.Field<string>("linetype"));
BasisUtility.BasisLineType b = BasisUtility.ParseBasisLineType(step.Row.Field<string>("linetype"));
var o = step.Row.Field<string>("output");
if (o != string.Empty && output.ContainsKey(o) == false && (b == BasisUtility.BasisLineType.MATH || b == BasisUtility.BasisLineType.ROUND))
{
output.Add(o, decimal.Zero);
}
switch (b)
{
default:
break;
case BasisUtility.BasisLineType.ENDIF:
skipIfCount--;
break;
case BasisUtility.BasisLineType.MATH:
if (skipIfCount == 0)
{
CalcLineTypeMath(step, output);
}
break;
case BasisUtility.BasisLineType.IF:
if (skipIfCount == 0)
{
var ifPassed = CalcLineTypeIf(step, output);
if (!ifPassed)
{
skipIfCount++;
}
}
else
{
skipIfCount++;
}
break;
case BasisUtility.BasisLineType.ROUND:
if (skipIfCount == 0)
{
CalcLineTypeRound(step, output);
}
break;
}
Debug.WriteLine("skipIfCount = " + skipIfCount);
}
foreach (var o in output)
{
var eo = o; //Must capture variable to avoid access to modified closure
var metric = (from control in _metricControls
where control.Name == eo.Key
select control).First();
metric.Value = o.Value;
}
_configFieldCalcStepView.RowFilter = string.Empty;
}
}
private void CalcLineTypeMath(DataRowView step, IDictionary<string, decimal> output)
{
Debug.WriteLine("<CalcLineTypeMath>");
Debug.Indent();
var outputVar = step.Row.Field<string>("output");
BasisUtility.BasisOperator op = BasisUtility.ParseBasisOperator(step.Row.Field<string>("operator"));
BasisUtility.BasisValueType valueType = BasisUtility.ParseBasisValueType(step.Row.Field<string>("valuetype"));
var option = step.Row.Field<string>("option");
Debug.WriteLine("outputVar = " + step.Row.Field<string>("output"));
Debug.WriteLine("op = " + step.Row.Field<string>("operator"));
Debug.WriteLine("valueType = " + step.Row.Field<string>("valuetype"));
Debug.WriteLine("option = " + step.Row.Field<string>("option"));
decimal input = CalcInput(output, valueType, outputVar, option);
switch (op)
{
case BasisUtility.BasisOperator.MATH_ASSIGN:
output[outputVar] = input;
break;
case BasisUtility.BasisOperator.MATH_ADD:
output[outputVar] += input;
break;
case BasisUtility.BasisOperator.MATH_SUBTRACT:
output[outputVar] -= input;
break;
case BasisUtility.BasisOperator.MATH_MULTIPLY:
output[outputVar] *= input;
break;
case BasisUtility.BasisOperator.MATH_DIVIDE:
try
{
output[outputVar] /= input;
}
catch (DivideByZeroException)
{
output[outputVar] = 1;
}
break;
case BasisUtility.BasisOperator.MATH_POWER_OF:
output[outputVar] = (decimal)Math.Pow((double)output[outputVar], (double)input);
break;
case BasisUtility.BasisOperator.MATH_MODULUS:
output[outputVar] %= input;
break;
default:
break;
}
Debug.WriteLine("output[outputVar] = " + output[outputVar]);
Debug.Unindent();
Debug.WriteLine("</CalcLineTypeMath>");
}
private decimal CalcInput(IDictionary<string, decimal> output, BasisUtility.BasisValueType valueType, string outputVar, string option)
{
Debug.WriteLine("<CalcInput>");
Debug.Indent();
var input = decimal.Zero;
decimal md;
Debug.WriteLine("valueType = " + valueType);
switch (valueType)
{
default:
break;
case BasisUtility.BasisValueType.ENTITY:
//TODO add lookup for ENTITY:
input = -2;
break;
case BasisUtility.BasisValueType.METRIC:
var o = (from m in _metricControls
where m.Name == option
select m.Value.ToString()).First();
decimal.TryParse(o, out md);
input = md;
break;
case BasisUtility.BasisValueType.TIME:
var t = (from m in _timeControls
where m.Name == option
select m.Value).First();
decimal.TryParse(t.TotalHours.ToString(), out md);
input = md;
break;
case BasisUtility.BasisValueType.INTERNAL:
input = (option.Equals("DEFAULT")) ? decimal.Zero : output[outputVar];
break;
case BasisUtility.BasisValueType.NUMBER:
decimal d;
decimal.TryParse(option, out d);
input = d;
break;
}
Debug.WriteLine("input = " + input);
Debug.Unindent();
Debug.WriteLine("</CalcInput>");
return input;
}
private bool CalcLineTypeIf(DataRowView step, IDictionary<string, decimal> output)
{
Debug.WriteLine("<CalcLineTypeIf>");
Debug.Indent();
var outputVar = step.Row.Field<string>("output");
BasisUtility.BasisOperator op = BasisUtility.ParseBasisOperator(step.Row.Field<string>("operator"));
BasisUtility.BasisValueType valueType = BasisUtility.ParseBasisValueType(step.Row.Field<string>("valuetype"));
var option = step.Row.Field<string>("option");
Debug.WriteLine("outputVar = " + step.Row.Field<string>("output"));
Debug.WriteLine("op = " + step.Row.Field<string>("operator"));
Debug.WriteLine("valueType = " + step.Row.Field<string>("valuetype"));
Debug.WriteLine("option = " + step.Row.Field<string>("option"));
var input = CalcInput(output, valueType, outputVar, option);
var outvalue = (output.Keys.Contains(outputVar)) ? output[outputVar] : CalcInput(output, BasisUtility.BasisValueType.METRIC, string.Empty, outputVar);
var result = false;
switch (op)
{
case BasisUtility.BasisOperator.IF_EQUAL:
result = (outvalue == input);
break;
case BasisUtility.BasisOperator.IF_NOT_EQUAL:
result = (outvalue != input);
break;
case BasisUtility.BasisOperator.IF_LESS_THAN:
result = (outvalue < input);
break;
case BasisUtility.BasisOperator.IF_LESS_THAN_OR_EQUAL:
result = (outvalue <= input);
break;
case BasisUtility.BasisOperator.IF_GREATER_THAN:
result = (outvalue > input);
break;
case BasisUtility.BasisOperator.IF_GREATER_THAN_OR_EQUAL:
result = (outvalue >= input);
break;
default:
break;
}
Debug.WriteLine("result = " + result);
Debug.Unindent();
Debug.WriteLine("</CalcLineTypeIf>");
return result;
}
private void CalcLineTypeRound(DataRowView step, IDictionary<string, decimal> output)
{
Debug.WriteLine("<CalcLineTypeRound>");
Debug.Indent();
var outputVar = step.Row.Field<string>("output");
int decimals;
int.TryParse(step.Row.Field<string>("option"), out decimals);
output[outputVar] = Math.Round(output[outputVar], decimals, MidpointRounding.AwayFromZero);
Debug.WriteLine("output[outputVar] = " + output[outputVar]);
Debug.Unindent();
Debug.WriteLine("</CalcLineTypeRound>");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:00:00.253",
"Id": "28823",
"Score": "0",
"body": "any idea where the bottleneck might be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:04:36.947",
"Id": "28827",
"Score": "0",
"body": "The foreach (DataRowView step in _configFieldCalcStepView) loop is called every time a digit is entered on the triggered control. So I guess the question is how I can improve the logic/speed of this section. I could move the event to validate? lostfocus? I'm not sure if that would be a better place. And truthfully, some users would not be happy with the 'delay' in updating the fields, see milesdifference in the above step list."
}
] |
[
{
"body": "<p>Hook up a profiler and measure what exactly is causing the slow down. Everything else is basically stabbing in the dark. That being said, there are a few things you could check:</p>\n\n<ol>\n<li><p>You have a few loops in there checking <code>_metricControls</code> and <code>_timeControls</code> frequently for one with a specific name. Store them in a dictionary keyed of the name rather than as the plain <code>IEnumerables</code>:</p>\n\n<pre><code>public FieldCalc(IEnumerable<ITicketRateMetric> metricControls, IEnumerable<Time> timeControls)\n{\n _metricControls = metricControls.ToDictionary(c => c.Name, c => c);\n _timeControls = timeControls.ToDictionary(c => c.Name, c => c);\n}\n</code></pre></li>\n<li>You do a fair amount of parsing so you could look at caching it. Caching can speed up things but comes with it's own draw backs so I'd be checking first if it's a problem or not.</li>\n</ol>\n\n<p>The first option is cheap and will reduce some of the code complexity (<code>_metricControls[op.Name]</code> as opposed to a multi-line LINQ statement) so I'd do it anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-16T00:43:45.733",
"Id": "32733",
"ParentId": "18090",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T17:57:20.597",
"Id": "18090",
"Score": "4",
"Tags": [
"c#"
],
"Title": "End User defined Controls and calculations on WinForm. Thoughts on speed?"
}
|
18090
|
<p>Please review this for concurrency correctness:</p>
<pre><code>#include <iostream>
#include <queue>
#include "boost\thread.hpp"
#include "boost\timer.hpp"
std::queue<int> itemQ;
boost::mutex m;
boost::condition_variable qFull, qEmpty;
const int max_size_q = 5;
void producer()
{
int i = 0;
while (1)
{
boost::this_thread::sleep(boost::posix_time::millisec(1000));
boost::mutex::scoped_lock lock(m);
if (itemQ.size() <= max_size_q)
{
itemQ.push(++i);
qEmpty.notify_one();
}
else
{
std::cout << "Q Full.notify_one Producer Waiting" << std::endl;
qFull.wait(lock);
std::cout << "Producer Notified to Continue" << std::endl;
}
}
}
void consumer()
{
while (1)
{
boost::this_thread::sleep(boost::posix_time::millisec(4000));
boost::mutex::scoped_lock lock(m);
if (itemQ.size() == 0)
{
std::cout << "Q Empty. Consumer " << boost::this_thread::get_id() <<" Waiting" << std::endl;
qEmpty.wait(lock);
std::cout << "Consumer Notified to Continue" << std::endl;
}
else
{
std::cout << itemQ.front() << std::endl;
itemQ.pop();
qFull.notify_one();
}
}
}
int main()
{
boost::thread producerthread(producer);
boost::thread consumerthread1(consumer);
boost::thread consumerthread2(consumer);
boost::thread consumerthread3(consumer);
boost::thread consumerthread4(consumer);
boost::thread consumerthread5(consumer);
consumerthread1.join();
consumerthread2.join();
consumerthread3.join();
consumerthread4.join();
consumerthread5.join();
}
</code></pre>
|
[] |
[
{
"body": "<p>Your usage of the condition variable will probably work but is a-typical.</p>\n\n<p>This is what you basically have:</p>\n\n<pre><code>while (1)\n{\n boost::mutex::scoped_lock lock(m); \n if (<Test OK>)\n {\n <Do Work>\n <Notify Consumer>\n } \n else \n {\n <Wait for consumer to signal conditional>\n }\n}\n</code></pre>\n\n<p>Notice that here you lock the mutex <code>m</code>. If the test is <strong>not</strong> OK then you wait for the consumer to signal the condition variable. This releases the lock on <code>m</code>. Once the condition variable is signaled then your thread must wait to re-aquire the lock to continue. Once it does it releases the lock and then re-starts the loop which immediately try to re-aquire the lock.</p>\n\n<p>A more typical pattern would be:</p>\n\n<pre><code>// pseudo code.\nstd::unique_ptr<WORK> getWork()\n{\n boost::mutex::scoped_lock lock(m); \n while(! <Test OK> )\n {\n <Wait for consumer to signal conditional>\n }\n return <getWorkObjectFromQueue>; \n}\n.....\nwhile(1)\n{\n work = getWork();\n\n <Do Work>\n <Notify Consumer>\n}\n</code></pre>\n\n<p>This way when you are waiting on the conditional variable and are signaled you do not have multiple attempts to re-acquire the lock before you do the work. As soon as you are signaled and have acquired the lock you can do a bit of work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T07:04:05.270",
"Id": "51125",
"Score": "0",
"body": "In your case the scopes make the two operations serial, which is often not desired. For example I might want to queue up 1000 work units."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T19:03:53.243",
"Id": "51185",
"Score": "0",
"body": "@Mikhail: You are correct. I was just trying to impart the pattern. But I have updated to make it more obvious."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T08:33:34.807",
"Id": "18107",
"ParentId": "18094",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:50:59.377",
"Id": "18094",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"boost",
"synchronization",
"producer-consumer"
],
"Title": "Boost Threads - Producer Consumer threads with synchronization"
}
|
18094
|
<p>Here is my problem. Do I need to give a new identifier to each delegate I write of the following delegate type? like so: or could i use one delegate that accounts for any Datatype I need to use so i don't have to keep repeating the code?</p>
<p>Something that may or may not be relevant: I'm calling these functions to prompt user's input for new fields to add for records in a database. So database field types are the data types I'm dealing with, but I'm using this approach for learning purposes to try and minimize redundancy.</p>
<pre><code>public static class stcHelper // helper class
{
public delegate T DelReturnType<T>();
static public DelReturnType<int> UserInt = () =>
{
Console.Write("Enter integer: ");
return int.Parse(Console.ReadLine());
};
static public DelReturnType<string> UserString = () =>
{
Console.Write("Enter string: ");
return Console.ReadLine();
};
static public DelReturnType<AnotherDataType> UserAnotherDataType = () =>
{
Console.Write("Enter AnotherDataType: ");
return SomeKindOfConversionFunction(Console.ReadLine());
};
// and so on for what could be 15 other data types ..
}
</code></pre>
<p>or is there a better way to reduce redundant code?</p>
<p>The code below is also part of the same class.</p>
<pre><code>public static class stcHelper
{
static public T InsistValidInput<T>(DelTypeReturn<T> MyInputAction)
{
bool bSuccess = true;
do
{
try
{
return MyInputAction();
}
catch (Exception ex)
{
Console.WriteLine("Invalid input!" + ex.ToString());
bSuccess = false;
}
} while (!bSuccess);
return default(T);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If done cleverly, you can get away with a single method to get the input of any type:</p>\n\n<pre><code>static T GetInput<T>(string message, Converter<string, T> transform)\n{\n Console.WriteLine(message);\n return transform(Console.ReadLine());\n}\n</code></pre>\n\n<p>All you need to do is pass in a transformation function (the <a href=\"http://msdn.microsoft.com/en-us/library/kt456a2y.aspx\" rel=\"noreferrer\"><code>Converter<TInput,TOutput></code></a> delegate is equivalent to <code>Func<T,TResult></code>):</p>\n\n<pre><code>int parsedInt = GetInput(\"Type in a number\", int.Parse);\nfloat parsedFloat = GetInput(\"Type in a float\", float.Parse);\n</code></pre>\n\n<p>And ta-da, you've got your input, parsed as the desired type.</p>\n\n<p>But as you also noted in the second half of your question, it's dangerous to assume that the input will always be valid. There's a universal version of your insist-on-valid-input function too. However, you should avoid using exceptions for normal control flow. Use the <code>xxx.TryParse</code> methods instead.</p>\n\n<p>First, define the following delegate that matches the <code>TryParse</code> method defined in all the primitive types:</p>\n\n<pre><code>delegate bool TryParse<T>(string input, out T output);\n</code></pre>\n\n<p>Then, you can implement the loop:</p>\n\n<pre><code>static T InsistOnValidInput<T>(string message, string errorMessage, TryParse<T> validator)\n{\n Console.WriteLine(message);\n T result;\n while (!validator(Console.ReadLine(), out result))\n {\n Console.WriteLine(errorMessage);\n }\n return result;\n}\n</code></pre>\n\n<p>And call it:</p>\n\n<pre><code>bool parsedBool = InsistOnValidInput<bool>(\"Type in a bool\", \"Try again\", bool.TryParse);\n</code></pre>\n\n<p>Unfortunately, C# doesn't infer the type parameter of the output argument, so you need to specify it manually (in this case, <code><bool></code>). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T01:29:21.423",
"Id": "28835",
"Score": "0",
"body": "I am reading your code, and wondering why you have 2 generics inside the 'Func<string, T>' ? Also, when you call the transform Func, you don't include <>, but include () with a parameter inside it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T01:51:06.743",
"Id": "28838",
"Score": "1",
"body": "`Func<string,T>` is a .NET delegate describing a method that takes a single argument of type `string` and returns a result of type `T`. `float.Parse` is such a method, so it can be used as a transform. It follows that we can call `transform` with the result of `Console.ReadLine` and it will return `T`. We don't need to explicitly specify type arguments when they can be *inferred* by the compiler. I strongly encourage you to step through the code in the debugger line for line - everything will make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T02:37:49.863",
"Id": "28839",
"Score": "0",
"body": "I see. by the way, in MSDN Library, it says `public delegate TResult Func<in T, out TResult>(T arg)`. Was your positioning of T for the second parameter `out TResult` instead of for the first parameter `in T` intentional? If yes, then does that mean that T is determined by the output of the given `Func<in T, out TResult>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T10:17:29.503",
"Id": "28857",
"Score": "0",
"body": "the use of `in` and `out` in this case is confusing, but it has nothing to do with input or output parameters; instead, it means that `T` is is *contravariant* (real argument can be *less derived*) and `TResult` is covariant (real argument can be *more derived*) as described [on msdn](http://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx). Be sure to take a look at the *delegates* section of the [covariance and contravariance guide](http://msdn.microsoft.com/en-us/library/dd799517.aspx#DelegateVariantTypeParameters) as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T10:19:47.180",
"Id": "28858",
"Score": "0",
"body": "I have to stress that **you need to run this code line-by-line** and examine the actual delegates being passed around. Visual Studio is an excellent tool for the job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T17:15:24.760",
"Id": "28875",
"Score": "2",
"body": "There is actually a more specific delegate for conversion, called [System.Converter<Tinput,Toutput>](http://msdn.microsoft.com/en-us/library/kt456a2y.aspx). It is ultimately just a Func<Tin,Tout>, but it is more specific to the task and can be re-used in several framework functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T17:16:24.567",
"Id": "28876",
"Score": "0",
"body": "@DanLyons wow, nice! I'll use that instead. There doesn't seem to be a more specific one to match `TryParse` though, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T17:22:22.510",
"Id": "28877",
"Score": "0",
"body": "Yeah, it's kinda nice to have. What's interesting is that there are several other delegates along a similar vein, like Predicate<T> which is Func<T,bool> and Comparison<T>, which is Func<T,T,int>, and EventHandler<T>, which is Action<T>."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T17:40:46.183",
"Id": "28878",
"Score": "0",
"body": "I'll run the code line by line for sure. But what should I pass for the conversion function when the expected result is to be a string?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T21:06:23.060",
"Id": "28883",
"Score": "0",
"body": "you can pass a Lambda expression such as `string result = GetInput(\"test\", i=>i.Trim());`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T00:35:06.087",
"Id": "28891",
"Score": "0",
"body": "Thanks. I want to ask about the other part of your answer, you said the following delegate that matches the TryParse defined in all primitives. Since you have defined it as `delegate bool TryParse<T>(string input, out T output);` I'm assuming that This TryParse method does not inherit or overload the TryParse method defined in primitives, because it's declared outside the scope of the primitive? And naming the delegate TryParse is just for convenient understanding of what it accomplishes in the definition?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T10:22:07.683",
"Id": "28899",
"Score": "0",
"body": "You can see a delegate as a reference to a method (a *method pointer*). The name doesn't matter; the signatures have to match."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T22:27:12.570",
"Id": "18097",
"ParentId": "18095",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": "18097",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T21:41:10.023",
"Id": "18095",
"Score": "10",
"Tags": [
"c#",
"generics",
"delegates"
],
"Title": "using <T> in generic delegates?"
}
|
18095
|
<p>I was looking for a C function that reads lines of arbitrary length from a file. I didn't find anything absolutely portable and safe from buffer overflows, so I tried writing my own.</p>
<ul>
<li>Does it look like I made any memory management mistakes?</li>
<li>Does it make sense to have this function return <code>NULL</code> everywhere that it does?</li>
<li>Have I made any other mistakes?</li>
</ul>
<p></p>
<pre><code>char *getaline (FILE *file)
{
size_t buffsize = 120; /* The minimum size for a line buffer */
size_t this_char = 0;
if (file == NULL) {
return NULL;
}
char *line = (char *) malloc(buffsize);
char **linebuff = &line;
if (*linebuff == NULL) {
return NULL;
}
char c = getc (file);
if (c == EOF) {
return NULL;
}
while (1) {
if (this_char + 1 >= buffsize) {
buffsize = 2 * buffsize;
char *next_linebuff;
next_linebuff = (char *) realloc (*linebuff, buffsize);
if (next_linebuff == NULL) {
return NULL;
}
*linebuff = next_linebuff;
}
(*linebuff)[this_char] = c;
this_char++;
if (c == '\n' || c == EOF) {
break;
}
c = getc (file);
}
(*linebuff)[this_char] = '\0';
line = *linebuff;
return line;
}
int main (int argc, const char *argv[]) {
FILE *file = fopen(argv[1], "r");
char *line = "";
while ((line = getaline(file)) != NULL) {
printf("%s", line);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T02:58:01.853",
"Id": "28840",
"Score": "1",
"body": "Might write a full response later if someone else hasn't already, but the first thing that jumps at me is that there are two possibilities for memory leaks in the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T04:50:59.543",
"Id": "28847",
"Score": "0",
"body": "Also, have you considered just using fgets? Even if you don't use it directly, your function could be built on it."
}
] |
[
{
"body": "<p>You definately have memory leaks.</p>\n\n<pre><code>==92867== Memcheck, a memory error detector\n==92867== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.\n==92867== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info\n==92867== Command: ./a.out test1\n==92867== \n--92867-- ./a.out:\n--92867-- dSYM directory is missing; consider using --dsymutil=yes\nabc\ndef\nghi\n==92867== \n==92867== HEAP SUMMARY:\n==92867== in use at exit: 10,815 bytes in 38 blocks\n==92867== total heap usage: 38 allocs, 0 frees, 10,815 bytes allocated\n==92867== \n==92867== LEAK SUMMARY:\n==92867== definitely lost: 480 bytes in 4 blocks\n==92867== indirectly lost: 0 bytes in 0 blocks\n==92867== possibly lost: 0 bytes in 0 blocks\n==92867== still reachable: 10,335 bytes in 34 blocks\n==92867== suppressed: 0 bytes in 0 blocks\n==92867== Rerun with --leak-check=full to see details of leaked memory\n==92867== \n==92867== For counts of detected and suppressed errors, rerun with: -v\n==92867== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)\n</code></pre>\n\n<p>Furthermore, It segfaults on me when I give it lines longer than 119 characters. (But this is probably system dependent).</p>\n\n<pre><code>$ ./a.out test3 ; cat test3\nabc\nthis is a test\nthis is a line with 40 characters in it\nthis is a line with 119 characters in it..............................................................................\nSegmentation fault: 11\nabc\nthis is a test\nthis is a line with 40 characters in it\nthis is a line with 119 characters in it..............................................................................\nthis is a line with 120 characters in it...............................................................................\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T03:12:45.783",
"Id": "18101",
"ParentId": "18100",
"Score": "1"
}
},
{
"body": "<p>As for existing solutions, check out <code>readline</code>. It's a pretty common library on *nix and even has <a href=\"http://gnuwin32.sourceforge.net/packages/readline.htm\" rel=\"nofollow\">a Windows port</a>.</p>\n\n<p>As for a critique of what you posted:</p>\n\n<pre><code>char *line = (char *) malloc(buffsize);\n</code></pre>\n\n<p>Don't bother casting a <code>void*</code> to another pointer type. This is a C++ thing. In C you don't have to do it, the conversion can be done implicitly.</p>\n\n<pre><code> char c = getc (file);\n</code></pre>\n\n<p>This is a common portability pitfall. A <code>char</code> cannot represent the full range of characters and also <code>EOF</code>. Depending on the environment you may not be able to distinguish between <code>EOF</code> and byte 255, or you may not be able to detect <code>EOF</code> at all. Store the result of <code>getc</code> in an <code>int</code>, because that's what it returns.</p>\n\n<pre><code>char *line = (char *) malloc(buffsize);\n\n// (snip)\n\nchar c = getc (file);\nif (c == EOF) {\n return NULL;\n}\n</code></pre>\n\n<p>If you hit that <code>return</code> you will leak the allocation of <code>line</code>.</p>\n\n<p>Now, you could introduce a <code>free</code> inside the <code>if</code> block... But many C programmers (myself included) prefer to avoid early <code>return</code> statements, because what happens is you end up with repetitive \"free all the buffers\" cleanup blocks. Instead of doing an early <code>return</code>, I like to let the scope own the allocation, meaning I insert the <code>free</code> whenever something like <code>line</code> goes out of scope, having the same cleanup block run in a success or failure case. (This sort of imitates C++'s RAII pattern, but with C and more manual.)</p>\n\n<pre><code> if (this_char + 1 >= buffsize) {\n buffsize = 2 * buffsize;\n</code></pre>\n\n<p>These integer operations can overflow. Maybe that's not a huge deal (I'll admit, I myself write a lot of code that doesn't handle overflow), but something to be aware of, should you be allocating sizes around the boundaries of the type of the size variables.</p>\n\n<pre><code> next_linebuff = (char *) realloc (*linebuff, buffsize);\n if (next_linebuff == NULL) {\n return NULL;\n }\n\n *linebuff = next_linebuff;\n</code></pre>\n\n<p><s>Looks like you've successfully avoided the \"leak on <code>realloc</code> failure\" issue that traps many newbies.</s> (<b>Update:</b> Sorry, must have suffered temporary blindness, you do leak here.) But I think this is too verbose. Why do you need to maintain <code>linebuff</code> as a double pointer? You already have <code>line</code>.</p>\n\n<pre><code>(*linebuff)[this_char] = '\\0';\nline = *linebuff;\n</code></pre>\n\n<p>Seems like you missed a potential <code>realloc</code> here. If the buffer is exactly full when you hit that line, you'll write past the allocation.</p>\n\n<pre><code>while ((line = getaline(file)) != NULL) {\n printf(\"%s\", line);\n}\n</code></pre>\n\n<p>You never call <code>free</code> on <code>line</code> here.</p>\n\n<hr>\n\n<p>My improved version follows, taking most of these suggestions. I've tried to keep your code mostly the same and follow the same style.</p>\n\n<pre><code>char *getaline (FILE *file)\n{\n size_t buffsize = 120; /* The minimum size for a line buffer */\n size_t this_char = 0;\n\n if (file == NULL) {\n return NULL;\n }\n\n char *line = malloc(buffsize);\n\n if (line == NULL) {\n return NULL;\n }\n\n int c;\n\n do {\n c = fgetc(file);\n\n if (this_char + 1 >= buffsize) {\n buffsize = 2 * buffsize;\n\n char *next_linebuff;\n next_linebuff = realloc (line, buffsize);\n if (next_linebuff == NULL) {\n free(line);\n line = NULL;\n break;\n }\n\n line = next_linebuff;\n }\n\n if (c == EOF || c == '\\n') {\n c = 0;\n }\n\n line[this_char++] = c;\n } while (c);\n\n return line;\n}\n\nint main()\n{\n char *p = NULL;\n while ((p = getaline(stdin)) && *p)\n {\n puts(p);\n free(p);\n }\n free(p);\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-17T16:48:30.167",
"Id": "401350",
"Score": "0",
"body": "Why set `line = NULL` if it's always set to `next_linebuf` before the next iteration? Is it just-in-case programming practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T22:37:26.277",
"Id": "403197",
"Score": "0",
"body": "@afuna There is no next iteration in the case you're describing. ```line = NULL``` appears after ```free``` and before ```break```, then gets returned to the caller. We can't return a stale pointer. In general though, I do like to null out pointers after a call to deallocate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T22:44:56.807",
"Id": "403198",
"Score": "0",
"body": "oops... I wasn't paying attention to the scope re. the `break`. my bad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T04:47:26.203",
"Id": "18103",
"ParentId": "18100",
"Score": "4"
}
},
{
"body": "<p>I see no need for the variable <code>linebuff</code>. In every location it is used you just de-reference it. Which makes it the same as <code>line</code> anyway. So wherever you use <code>*linebuff</code> just use <code>line</code> instead.</p>\n\n<pre><code> char **linebuff = &line;\n</code></pre>\n\n<p>Here you are potentially leaking <code>line</code>.<br>\nAt every return point you need to make sure you clean up any allocated memoty.</p>\n\n<pre><code> if (c == EOF) {\n return NULL;\n }\n</code></pre>\n\n<p>I think your loop is the wrong way around.<br>\nNormally when reading a line I would not add the new line character to the buffer (but that is a debatable point). Which you seem to be trying to do with the condition at the end. But if the first character is a new line then you add it to the buffer (because you don't test <code>c</code> that was read outside the loop.</p>\n\n<pre><code> while (1) {\n</code></pre>\n\n<p>You could simplify this by doing the read (and all the tests at the top).</p>\n\n<pre><code> int c; // note `c` should be an int.\n while((c = getc(file)) != EOF)\n {\n if (c == '\\n')\n { break;\n }\n\n // Now do all the work to add the character to the buffer.\n</code></pre>\n\n<p>Another potential leak.<br>\nIf realloc() fails then the original buffer is not affected. So you will need to release it if you return NULL.</p>\n\n<pre><code> char *next_linebuff;\n next_linebuff = (char *) realloc (*linebuff, buffsize);\n if (next_linebuff == NULL) {\n return NULL;\n }\n</code></pre>\n\n<p>Also I don't like the two line call to realloc(). I would declare and do the assignment in a single line:</p>\n\n<pre><code> char *next_linebuff = realloc (line, buffsize);\n</code></pre>\n\n<p>In main() you get a dynamically allocated string from a function. Documentation is scetchy but it looks like you should be taking ownership. Which means you are also responsable for clean up (ie freeing the string).</p>\n\n<pre><code>while ((line = getaline(file)) != NULL) {\n</code></pre>\n\n<p>Where each call to getaline() means the result of the last call is leaked.</p>\n\n<p>Your line doe not contain a new line.<br>\nSo when you print it, it may be a good idea to add the new line back</p>\n\n<pre><code> printf(\"%s\", line);\n</code></pre>\n\n<p>It should look like this:</p>\n\n<pre><code>char* line;\n\nwhile ((line = getaline(file)) != NULL)\n{\n printf(\"%s\\n\", line);\n free(line);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T08:16:27.220",
"Id": "18106",
"ParentId": "18100",
"Score": "2"
}
},
{
"body": "<p>Others have dissected your function thoroughly. In case you are interested, an alternative method of accessing a normal file (but not a socket, pipe, etc) is to use <code>mmap</code>. This maps the whole file into memory without the need to <code>malloc</code> anything. The allocation occurs in the background as you access the mapped file - which for a text file now looks just like a string.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/mman.h>\n#include <fcntl.h>\n\nstatic void fail(const char *msg)\n{\n perror(msg);\n exit(EXIT_FAILURE);\n}\n\nint main (int argc, const char *argv[])\n{\n (void) argc;\n int fd = open(argv[1], O_RDONLY);\n if (fd < 0) {\n fail(argv[1]);\n }\n struct stat st;\n\n if (fstat(fd, &st) < 0) { /* to get the file size */\n fail(argv[1]);\n }\n void *const map = mmap(0, st.st_size,\n PROT_READ|PROT_WRITE, \n MAP_FILE|MAP_PRIVATE, fd, 0);\n if (map == NULL) {\n fail(argv[1]);\n }\n char *term;\n char *s = map;\n\n while ((term = strchr(s, '\\n')) != NULL) {\n char ch = *term;\n *term ='\\0'; /* replace the '\\n' so we can print the line */\n printf(\"%s\\n\", s);\n *term = ch; \n s = term + 1;\n }\n if (*s) { /* if last line has no '\\n' */\n printf(\"%s\\n\", s);\n }\n munmap(map, st.st_size);\n return EXIT_SUCCESS;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T23:14:07.433",
"Id": "18124",
"ParentId": "18100",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18103",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T01:14:03.277",
"Id": "18100",
"Score": "5",
"Tags": [
"c",
"strings",
"reinventing-the-wheel",
"io"
],
"Title": "C getline function"
}
|
18100
|
<p>I've written a small routing system in PHP but I'm not sure if it's done the right way and what changes can they be done to the code and improvements.</p>
<pre><code><?php
namespace Twelve\Router;
use Twelve\Utils\Utils;
class Router
{
public
$routeMaps = [],
$controller;
private $_route = [];
public function add($name, $pattern, $controller, array $params = [])
{
if(!isset($this->routeMaps[$name]))
$this->routeMaps[$name] =
[
'pattern' => $pattern,
'controller' => $controller,
'params' => $params,
];
}
public function findMatch($url)
{
foreach($this->routeMaps as $routeMap)
{
$this->regex = $this->buildRegex($routeMap['pattern'], $routeMap['params']);
// Let's test the route.
if(preg_match($this->regex, $url))
{
return (array) $routeMap['controller'];
}
}
}
public function buildRegex($uri, array $params)
{
// FInd {params} in URI
if(preg_match_all('/\{(?:[^\}]+)\}/', $uri, $this->matches, PREG_SET_ORDER))
{
foreach($this->matches as $isMatch)
{
// Swap {param} with a placeholder
$this->uri = str_replace($isMatch, "%s", $uri);
}
// Build final Regex
$this->finalRegex = '/^' . preg_quote($this->uri, '/') . '$/';
$this->finalRegex = vsprintf($this->finalRegex, $params);
return $this->finalRegex;
}
}
public function dispatch(array $route = [], $url)
{
$this->setController($route['0']);
$this->setAction($this->getController());
$this->setParams(explode('/', $url));
$this->controller = $this->getController();
array_pop($this->controller);
$this->controller = implode('\\', $this->controller);
call_user_func_array([new $this->controller, $this->action], $this->params);
}
public function setController($controller)
{
$this->controller = explode(':', $controller);
}
public function getController()
{
return $this->controller;
}
public function setAction($action)
{
$this->action = end($action);
}
public function getAction()
{
return $this->action;
}
public function setParams($params)
{
$this->params = array_slice($params, 4);
}
public function getParams()
{
return $this->params;
}
public function run($uri, array $route = null)
{
$route = $this->findMatch($uri);
Utils::var_dump($route);
$this->dispatch($route, $uri);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T17:21:09.847",
"Id": "28926",
"Score": "0",
"body": "Am i right that you are mapping one route to one specific controller?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T13:54:02.750",
"Id": "28994",
"Score": "0",
"body": "yes i'm mapping one route to one specific controller"
}
] |
[
{
"body": "<p>Here are my observations</p>\n\n<p><strong>NOTE</strong> I did all this via stream-of-conscientiousness and I haven't tested any of these changes (or your original code) so take these as guidance and not exact changes :)</p>\n\n<p><strong>router.php</strong></p>\n\n<pre><code><?php\nclass Router\n{\n // TODO You need to use `private` a lot more for encapsulation\n private $routeMaps = [];\n\n // TODO This function needs to document the expected format of inputs\n // TODO is initial controller format supposed to be 'full:class:path:method' ?\n public function add($name, $pattern, $controller, array $params = [])\n {\n // TODO What if it is already set?\n if(!isset($this->routeMaps[$name]))\n {\n $this->routeMaps[$name] =\n [\n 'pattern' => $pattern,\n 'controller' => $controller,\n 'params' => $params,\n // Build the regex now so we ensure we only build it once\n 'regex' => $this->buildRegex($pattern, $params),\n ];\n }\n else\n {\n throw new Exception(\"Route '{$name}' already defined\");\n }\n }\n\n // TODO Document function\n\n# why the '$route = null'? It is not used\n#?? public function run($uri, array $route = null)\n public function run($uri)\n {\n $routeMap = $this->findMatch($uri);\n# Utils::var_dump($routeMap);\n // TODO check to see if we actually found a match\n if (null !== $routeMap)\n {\n // TODO we should probably parse the parms before calling dispatch\n $this->dispatch($routeMap, $uri);\n }\n // TODO probably want to notify user somehow\n else\n {\n ; // ??\n }\n }\n\n // TODO Why are you calling this parm $uri instead of $pattern?\n private function buildRegex($uri, array $params)\n {\n // FInd {params} in URI\n if(preg_match_all('/\\{(?:[^\\}]+)\\}/', $uri, $matches, PREG_SET_ORDER))\n {\n foreach($matches as $isMatch)\n {\n // Swap {param} with a placeholder\n# matching $uri and setting $this->uri means only the last match is saved\n# Is that what you want? If so, document it\n#?? $this->uri = str_replace($isMatch, \"%s\", $uri);\n $uri = str_replace($isMatch, \"%s\", $uri);\n }\n // Build final Regex\n $finalRegex = '/^' . preg_quote($this->uri, '/') . '$/';\n $finalRegex = vsprintf($finalRegex, $params);\n\n return $finalRegex;\n }\n // TODO Need to throw error if uri doesn't match\n else\n {\n throw new Exception(\"Invalid uri: '{$uri}'\");\n }\n\n }\n\n // TODO Why does (did) this return an array of one element, containing just the\n // controller?\n // TODO Shouldn't this return the routemap instead of just the controller?\n private function findMatch($url)\n {\n foreach($this->routeMaps as $routeMap)\n {\n // Let's test the route.\n if(preg_match($routeMap['regex'], $url))\n {\n return $routeMap;\n }\n }\n\n return null; // TODO We should return something if no match\n }\n\n // TODO This should take the already parsed $parms \n private function dispatch($routeMap, $url)\n {\n $parts = explode(':', $routeMap['controller']);\n $action = array_pop($parts);\n $clazz = implode('\\\\', $parts);\n $params = $this->parseParams($url);\n call_user_func_array([new $clazz, $action], $params);\n }\n\n // TODO This needs to be based on the pattern in the rout map\n // TODO Since it appears that the 'params' in the route map have to\n // match in order for the url to match, we should propably use\n // the length of those in our parsing here.\n // TODO Perhaps we could even use the regex to tell these values at\n // match time?\n private function parseParams($url)\n {\n return array_slice(explode('/', $url), 4);\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-13T03:02:27.790",
"Id": "19561",
"ParentId": "18110",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19561",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T09:46:15.023",
"Id": "18110",
"Score": "3",
"Tags": [
"php",
"php5",
"url-routing"
],
"Title": "Small routing system"
}
|
18110
|
<p>I have written the following script which simply:</p>
<ol>
<li>Loops through JavaScript files (either defined in a particular package, or separately with the libraries array)</li>
<li>Reads the files into the script and combines them into one string</li>
<li>Minifies the string and saves the contents to a cached file on the server and returns the contents.</li>
</ol>
<p>Some key features:</p>
<ol>
<li>The cached file is only updated when the script detects that one of the loaded JavaScript libraries has been modified</li>
<li>The script only gathers the files if a cached version does not exist</li>
</ol>
<p>I am sure most of us programmers will notice that the array of libraries could very easily be built dynamically by scanning the <code>_js/_source/</code> directory and therefore I would not have to add each library to the <code>$js_libraries</code> array individually. The reason I have not done this is simple, it is much slower when there are a lot of files and <strong>the absolute key of this script is speed!</strong></p>
<p>I simply want to know whether this could be written better and whether it has any areas I could improve on.</p>
<pre><code><?php
/**
* Sine Macula Package API
* The Sine Macula Package API loads and packs documents ready to
* be returned to the browser
* @name jsapi.php
* @author Ben Carey
* @version 1.0
* @date 24/10/2012
* @copyright (c) 2012 Sine Macula Limited (sinemaculammviii.com)
*/
// Retrieve the supplied variables
$package = $_REQUEST['package'] ? strtolower($_REQUEST['package']) : 'all';
$packageURL = $_REQUEST['packageURL'];
$libraries = strtolower($_REQUEST['libraries']);
// Define all the javascript libraries
$js_libraries = array(
'md5' => '/_js/_source/_md5/sinemacula.md5.js',
'cookies' => '/_js/_source/_cookies/sinemacula.cookies.js',
'preloading' => '/_js/_source/_preloading/sinemacula.preloading.js',
'browsers' => '/_js/_source/_browsers/sinemacula.browsers.js',
'overlay' => '/_js/_source/_overlay/sinemacula.overlay.js',
'forms' => '/_js/_source/_forms/sinemacula.forms.js',
'fancybox' => '/_js/_source/_fancybox/jQuery.lightbox-0.5.js',
'indexof' => '/_js/_source/_indexOf/init.indexOf.js'
// This array will be much larger
);
// Only define the javascript packages if the
// package is not coming from an external source
if($package){
// Define all the javascript packages
$js_packages = array(
'all' => array_keys($js_libraries)
// This array will be much larger
);
// Make sure the supplied package exists
if(array_key_exists($package,$js_packages)){
// Gather all the libraries for the particular package
$package = array_intersect_key($js_libraries,array_flip($js_packages[$package]));
}else{
$errors[] = 'The supplied package does not exist';
}
}elseif($packageURL){
// Attempt to retrieve the contents of the external package
$package = @file_get_contents($packageURL);
if($package){
// Decode the JSON object into an array
$package = json_decode($package,true);
}else{
$errors[] = 'Error retrieving package from remote source';
}
}
// Add the libraries to the package array
// if they have been supplied
if($libraries){
// Explode the libraries string into an array
$libraries = explode(',',$libraries);
// Gather the unrecognised libraries
$unrecognised_libraries = array_diff($libraries,array_keys($js_libraries));
// If there are unrecognised libraries then
// return relevant errors
if($unrecognised_libraries){
foreach($unrecognised_libraries as $value){
$errors[] = '\''.$value.'\' library does not exist';
}
}
// Insert all the sources for the library keys
$libraries = array_intersect_key($js_libraries,array_flip($libraries));
// Make sure package is an array
$package = is_array($package) ? $package : array();
// Merge the libraries with the package array
$package = array_merge($package,$libraries);
}
// Create a hash of the package
$package_hash = md5(implode('',array_keys($package)));
// Loop through the package and check their modified dates
$modified_timestamps = array_map(function($a){
// Get the modified time of each individual library
return filemtime(dirname(__FILE__).$a);
},$package);
// Hash the modified time, this will determine whether the,
// library has been updated
$modified_hash = md5(implode('',$modified_timestamps));
// Check to see if the package directory exists in the cache
if(@is_dir(dirname(__FILE__).'/_js/_cache/_' . $package_hash )){
// If the modified hash matches a file in the folder then it
// does not need updating
if(file_exists(dirname(__FILE__).'/_js/_cache/_'.$package_hash.'/'.$modified_hash.'.js')){
// Get the contents of the file
$packed_script = file_get_contents(dirname(__FILE__).'/_js/_cache/_'.$package_hash.'/'.$modified_hash.'.js');
}else{
// Set pack to true to ensure that the script
// is created
$pack = true;
}
}else{
// Create the directory for the package
@mkdir(dirname(__FILE__).'/_js/_cache/_'.$package_hash);
// Set pack to true to ensure that the script
// is created
$pack = true;
}
// If pack is set then gather all the files, combine
// into one and pack. This will create the file as
// well, and store it in the folder '_cache'
if($pack){
// Loop through the package and load all of the libraries
// into the script ready to be packed
foreach($package as $key => $value){
// Get the script
$current_script = @file_get_contents(dirname(__FILE__).$value);
// Return an error on fail to load
if($current_script){
$combined_script .= $current_script.";\n";
}else{
$errors[] = 'Failed to load \''.$key.'\' library';
}
}
// Include the javascript packer
require_once(dirname(__FILE__).'/_php/_classes/class.packer.php');
// Initiate the packer and pack the javascript
$js_packer = new JavaScriptPacker($combined_script);
$packed_script = $js_packer->pack();
// Retrieve the cached scripts (should only be one)
$cached_scripts = @glob(dirname(__FILE__).'/_js/_cache/_'.$package_hash.'/*.js');
// Delete all the files in the package directory
if(is_array($cached_scripts)){
array_map('unlink',$cached_scripts);
}
// Create the new javascript package file if there
// have been no errors
if(empty($errors)){
if(!@file_put_contents(dirname(__FILE__).'/_js/_cache/_'.$package_hash.'/'.$modified_hash.'.js',$packed_script)){
$errors[] = 'There was an error loading the javascript libraries';
}
}
}
// Set the content header to javascript
// and write the packed script or errors
header("Content-Type: text/javascript");
if(empty($errors)){
echo $packed_script;
}else{
// Loop through the errors and write them to the
// javascript console
foreach($errors as $value){
echo 'console.log("'.$value.'");';
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<h2>Don't point at php</h2>\n<p>This script looks like the intention is to point at a php file, that returns the compressed content. Assuming that's the case...</p>\n<p>PHP doesn't belong in-between a user and a static, public file. Webservers are much better for serving static content. Rather than pointing at a php script that processes the request, looks for and/or manipulates files and then serves it - take advantage of the webserver and point at the cache file directly - or where the cache file should be if it doesn't exist.</p>\n<p>I.e. change this logic:</p>\n<pre><code>user -> /someurl.php?args -> php -> build/find static file -> serve it\n</code></pre>\n<p>To the equivalent of:</p>\n<pre><code>user -> /js/packet/hash.js\n</code></pre>\n<p>Putting as little as possible in-between the user and the content they are requesting means better performance.</p>\n<h2>Handle requests for missing packets</h2>\n<p>If you want to automatically handle requests for missing packets, add a .htaccess file (or equivalent) like this to the css/js folder:</p>\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteRule ^(.*)$ handlemissingasset.php [L]\n</IfModule>\n</code></pre>\n<p>You'll have the possibility to handle requests for a packed js/css file on the first request where it's missing. Write to the equivalent path of the current url - and the webserver will take care of serving the file and sending appropriate headers.</p>\n<h2>Derive the url at run time, not the file's contents</h2>\n<p>Instead of using a url which contains, serialized in some form, the contents that are to be returned - just derive the url for the packet file. So e.g.:</p>\n<pre><code>function url($packets) {\n return md5(implode($packets) . APP_VERSION) . '.js';\n}\n\necho sprintf('<script src="%s"></script>', url(array('foo', 'bar')));\n</code></pre>\n<p>The less logic there is at runtime - the faster the code performs.</p>\n<h2>Use a build process</h2>\n<p>Rather than handle requests for missing packets, a process that builds them all, once, could be used.</p>\n<pre><code>$ . buildPackets.php\nScanning for packets\n... found ('foo', 'bar')\n... bumping APP_VERSION\n... writing js/packets/d41d8cd98f00b204e9800998ecf8427e.js\n</code></pre>\n<p>The benefit of working in this way is that the run-time logic is reduced to the bare minimum, there's no need at any point of a web request to check if files exist ect. This is also more or less a pre-requisite to be able to use a CDN.</p>\n<h2>Explicit is better than implicit</h2>\n<p>I'm not sure what the logic at the top of the code in the question is for, but (and this is from experience). if in a project there are requests for:</p>\n<pre><code>'foo', 'bar'\n'bar', 'foo'\n'foo', 'bar', 'other'\n'zum', 'bar', 'other'\n</code></pre>\n<p>It becomes difficult to automatically serve optimal packets.</p>\n<p>If each individual request results in 1 js file that is <em>sub</em> optimal, as the user receives one file per page, but the same content multiple times as they browser around the site.</p>\n<p>As such it's likely better to define all js packets in a config file and only refer to the packet names rather than permit dynamic usage.</p>\n<h2>Appropriate Headers</h2>\n<p>Whether you heed or ignore the above, this point is the biggest failing with the code as presented. There are 2 ways to handle headers for asset files (css, js images), the serverver and/or the php script needs to implement correct headers for optimal performance.</p>\n<h3>Validation requests</h3>\n<p>A short expiry is sent in the headers, the user sends a request and a successful response is either a 200 or a 304 - make sure to be sending 304s where appropriate.</p>\n<p>This means a user downloads the file once on the first request, and on each subsequent request for the same asset they receive an empty <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html\" rel=\"nofollow noreferrer\">304 not modified</a> response. Not sending the user back the same file saves bandwidth and increases speed.</p>\n<h3>Long expiry</h3>\n<p>If the url changes when an asset changes - there's no need for validation requests and you can send in the headers that the response is valid for - e.g. a year. This means a user downloads the file on the first request - and never requests it again. Validation requests are a great improvement over no/incorrect cache headers. Long expiry is another significant improvement.</p>\n<h3>Finally: Look for existing solutions</h3>\n<p>You may find repos like <a href=\"https://github.com/markstory/asset_compress\" rel=\"nofollow noreferrer\">this one</a> useful, either the code, the docs, the api or all of the above. Try to avoid the mistakes that many have already made before you :).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T13:38:12.317",
"Id": "28913",
"Score": "0",
"body": "Thank you very much for your answer and pointers! :-) I have a few questions about some of the things you have mentioned. Firstly, the `hash.js` file is not static as it is rebuilt whenever any of the files in that package have been modified, this is essential as if I make a change to any of the libraries, the changes must appear on the sites immediately. Therefore, I cannot see a way of doing this without pointing to a PHP file. This is also why I cannot derive the URL at runtime as the `hash` will be different if any of the libraries have been modified. *(continuing)*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T13:44:27.307",
"Id": "28914",
"Score": "0",
"body": "*(continued)* What do you mean about the `$js_libraries` array not being optimal? I can understand keeping the definition of this array in another file but don't understand what is wrong with it. As far as appropriate headers go, I only used what I found on the web, would you mind posting the correct headers to use for returning a javascript page? I agree about the cache, however, how will it know whether the cache file has been modified? Especially if it is not actually looking at it, it is looking at the PHP file instead? :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T14:47:47.833",
"Id": "28917",
"Score": "0",
"body": "you're still thinking that \"hash\" indicates only the packets of the file - just bump APP_VERSION (referring to the example code) whenever a file changes, and the url changes. The main problem with your approach and IMO the first thing to change - is that you're pointing at a php file. If you don't change that, this code will always be of limited use. Regarding headers - just use something like yslow, or google page speed and look at their references."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T14:55:06.267",
"Id": "28918",
"Score": "0",
"body": "I am modifying the files the whole time so bumping a constant is not a great method in this case. This will also mean that I will have to run a script each time I modify the files in order to minify them. Many applications point to PHP files to obtain javascript, I agree it is not a great method but sometimes it is necessary if the javascript you are loading is environment dependant. Do you not agree?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T16:17:16.917",
"Id": "28925",
"Score": "0",
"body": "no :). You're trying to optimize for development, instead of optimizing for production/the end user, it's the wrong focus. The use of a single constant was mostly for illustration - know that the cost of `file_exists`, `filemtime`, `md5_file` etc. are relatively significant, and to be avoided. There are lots of scripts out there that [run processes when files change](https://github.com/guard/guard) - in development just use the same kind of thing."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T20:44:21.490",
"Id": "18122",
"ParentId": "18117",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18122",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T15:21:38.877",
"Id": "18117",
"Score": "5",
"Tags": [
"javascript",
"php",
"api"
],
"Title": "Loading JavaScript libraries with PHP API"
}
|
18117
|
<p>I'm trying to develop a better function and curious what others would suggest I do to it so that its not so robust and still accomplish what I need.</p>
<p>A couple of things I need to account for is when I have a last 5 messages as well as getting just the regular number of messages.</p>
<pre><code>/**
* Gets all or last $x number of personal messages of the specified user
*
* @param integer $user_id User ID of the user specified
* @param integer $limit Limit of how many messages to retrieve
* @param integer $timezone The timezone offset of the user's geo location
* @param string $box Loading either the inbox or outbox of messages
* @param string $date_format The format for which the date needs to be ouputted
* @param array $display Tells what kind of messages to retrieve (important or specific datetime or datetime range)
* @return object/NULL
*/
public function get_personal_messages($user_id, $limit = NULL, $timezone, $box, $date_format, $display = NULL)
{
$this->db->select('personal_messages.message_id');
$this->db->select('personal_messages.subject');
$this->db->select('personal_messages.datetime_sent');
$this->db->select('personal_messages.attachments');
$this->db->select('personal_messages.priority');
$this->db->select('personal_messages.message_content');
if ($box == 'inbox')
{
$this->db->select('personal_messages.to_read AS message_read');
}
else
{
$this->db->select('personal_messages.from_read AS message_read');
}
if ($box == 'inbox')
{
$this->db->select('personal_messages.is_inbox_favorite AS is_favorite');
}
else
{
$this->db->select('personal_messages.is_outbox_favorite AS is_favorite');
}
$this->db->select('CONCAT(users.first_name, " ", users.last_name) AS sender_name', FALSE);
$this->db->select('users.email_address AS sender_email_address');
$this->db->select('user_profiles.user_avatar AS sender_avatar');
$this->db->from('personal_messages');
$this->db->join('users', 'users.user_id = personal_messages.from_user_id');
$this->db->join('user_profiles', 'users.user_id = user_profiles.user_id');
if ($display['type'] == 'today')
{
$this->db->where('datetime_sent >', $display['values']['start_time']);
$this->db->where('datetime_sent <', $display['values']['end_time']);
}
elseif ($display['type'] == 'this_week')
{
}
elseif ($display['type'] == 'last_week')
{
}
if ($box == 'inbox')
{
$this->db->where('personal_messages.to_user_id', $user_id);
}
else
{
$this->db->where('personal_messages.from_user_id', $user_id);
}
if ($limit != NULL)
{
if (is_numeric($limit))
{
$this->db->limit($limit);
}
}
$query = $this->db->get();
$personal_messages = array();
$personal_messages['messages'] = $query->result();
if (count($personal_messages['messages']) > 0)
{
for ($x = 0; $x < count($personal_messages['messages']); $x++)
{
$attachments = $personal_messages['messages'][$x]->attachments;
if ($this->functions_model->null_check($attachments) === FALSE)
{
$attachments = json_decode($attachments, TRUE);
for ($i = 0; $i < count($attachments); $i++)
{
$file_name = $attachments[$i];
$attachments[$i] = array();
$attachments[$i]['file_name'] = $file_name;
if ($this->functions_model->is_file('assets/downloads/'.$file_name, FALSE) === TRUE)
{
$attachments[$i]['is_file'] = TRUE;
$file_size = $this->functions_model->bytes_to_size(filesize('assets/downloads/'.$file_name));
$attachments[$i]['file_size'] = $file_size;
$attachments[$i]['file_location'] = 'assets/downloads/'.$file_name;
}
else
{
$attachments[$i]['is_file'] = FALSE;
}
}
$personal_messages['messages'][$x]->attachments = $attachments;
}
$personal_messages['messages'][$x]->datetime_sent = $this->functions_model->actual_time('Y-m-d g:i:s', $timezone, strtotime($personal_messages['messages'][$x]->datetime_sent));
$personal_messages['messages'][$x]->datetime_sent = date($date_format, strtotime($personal_messages['messages'][$x]->datetime_sent));
$personal_messages['messages'][$x]->datetime_sent = $this->functions_model->time_since(strtotime($personal_messages['messages'][$x]->datetime_sent));
$avatar = $this->functions_model->site_url().'assets/themes/'.$this->config->item('default_theme').'/images/avatars/avatar.jpg';
if ($this->functions_model->null_check($personal_messages['messages'][$x]->sender_avatar) === FALSE)
{
if ($this->functions_model->is_file('assets/themes/supr/images/avatars/'.$personal_messages['messages'][$x]->sender_avatar, FALSE) === TRUE)
{
$avatar = $this->functions_model->site_url().'assets/themes/'.$this->config->item('default_theme').'/images/avatars/'.$personal_messages['messages'][$x]->sender_avatar;
}
}
$personal_messages['messages'][$x]->sender_avatar = $avatar;
}
$personal_messages['total_unread_messages'] = $this->get_users_unread_messages($user_id);
}
return $personal_messages;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T16:14:21.883",
"Id": "28996",
"Score": "0",
"body": "Any ideas for me?"
}
] |
[
{
"body": "<p>You have a lot of <code>if ($box == 'inbox')</code> statements. Why not bunch them together into one <code>if</code> statement?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T14:51:02.183",
"Id": "18213",
"ParentId": "18119",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T16:31:21.250",
"Id": "18119",
"Score": "1",
"Tags": [
"php",
"codeigniter"
],
"Title": "Getting personal messages function"
}
|
18119
|
<p>I'm a brand new JavaScript guy (currently playing with Meteor) and would love some critique of the following:</p>
<p>The goal: I've got two collections </p>
<ol>
<li>Buckets </li>
<li>Widgets. </li>
</ol>
<p>I'm displaying a <code>select</code> for each bucket, populated with an <code>option</code> for each widget. </p>
<p>The goal is simply to mark the appropriate <code>option</code> as <code>selected</code> if the bucket currently contains that widget.</p>
<p>I wrestled with this a bit and came up with what feels hack-ey </p>
<p>-- I'm explicitly passing the bucket's contents as a Handlebars variable. I feel like there's a better way, but not sure how to get 'er done.</p>
<p>Is there a way to get access to the parent template instance's context from a nested template instance? <code>#each widget</code> is being called from within <code>#each bucket</code> but <code>this</code> only gives me access to the child context. </p>
<p>(This works, I'm just trying to learn here).</p>
<p><strong>HTML:</strong>
</p>
<pre><code><template name="choices">
{{#each bucket}}
<label for='{{bucket_name}}'>{{bucket_description}}</label>
<select id='{{bucket_name}}'>
{{#each widget}}
<option value="{{widget_name}}" {{selected ../bucket_contains}}>{{widget_description}}</option>
{{/each}}
</select>
{{/each}}
</template>
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>if (Meteor.isClient) {
Template.choices.bucket = function () {
return Buckets.find({});
};
Template.choices.widget = function () {
return Widgets.find({});
};
Template.choices.selected = function (parent) {
return (this.widget_name === parent) ? 'selected' : '';
};
Template.choices.events({
'change select': function (event) {
Buckets.update({bucket_name: event.target.id}, {$set: {bucket_contains: event.target.value}});
}
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:49:27.870",
"Id": "40668",
"Score": "0",
"body": "So `bucket_contains` is a property of Buckets and will be the name of a widget if a widget is assigned to a bucket?"
}
] |
[
{
"body": "<p>I've been looking at your code for a few weeks now, the problem is both that there is not a lot to review and there's nothing wrong with it.</p>\n\n<p>Do consider using lowerCamelCasing which is the standard in JS, so <code>bucket_name</code> -> <code>bucketName</code>.</p>\n\n<p>The code seems elegant enough to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T16:04:46.553",
"Id": "41412",
"ParentId": "18120",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T18:23:26.670",
"Id": "18120",
"Score": "8",
"Tags": [
"javascript",
"html",
"node.js",
"meteor"
],
"Title": "Nested template variable access in Meteor"
}
|
18120
|
<blockquote>
<p>Given a string, find its rank among all its permutations sorted
lexicographically. For example, rank of “abc” is 1, rank of “acb” is
2, and rank of “cba” is 6. Assuming there is no duplicated character.</p>
</blockquote>
<p>The following is my code:</p>
<pre><code>#include <iostream>
using namespace std;
// A utility function to find factorial of n
int factorial(int i)
{
if(i == 0)
return 1;
return i*factorial(i-1);
}
// A utility function to count smaller characters
// starting from index of ind
int count_smaller_than_cur(string& s, int ind)
{
int count = 0;
for(int i = ind+1; i < s.size(); ++i)
if(s[i] < s[ind])
count++;
return count;
}
// A function to find rank of a string in all permutations
// of characters
int rank(string& s)
{
int r=1;
int len = s.size();
int f = factorial(len);
for(int i=0; i < len; ++i)
{
f /= (len-i);
// count number of chars smaller than str[i]
// fron str[i+1] to str[len-1]
int t = count_smaller_than_cur(s, i);
r += t*f;
}
return r;
}
int main()
{
string str("string");
cout << rank(str) << endl;
system("pause");
return 0;
}
</code></pre>
<p>Can anyone help me check it?</p>
|
[] |
[
{
"body": "<p>I have a couple of issues with the main function.</p>\n\n<p>First, <code>system(\"pause\")</code> may work for windows but won't elsewhere. You should dump it.</p>\n\n<p>Second, Too many returns at the end.</p>\n\n<p>Third, The hardcoded input makes it kinda hard to test (and doesn't look good). Just read the first parameter from the command line or read in from standard in. Here is an easy way to do so:</p>\n\n<pre><code>int main(int argc, char** argv) {\n string str;\n if(argc >= 2){\n str = argv[1];\n } else {\n cout << \"Enter a string: \";\n cin >> str;\n }\n cout << rank(str) << endl;\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T03:50:34.100",
"Id": "28892",
"Score": "0",
"body": "thanks very much. There is no duplicated character in the string. I'm sorry for not making it clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T03:53:35.330",
"Id": "28893",
"Score": "0",
"body": "Excellent! I took that section out then."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T03:47:17.497",
"Id": "18126",
"ParentId": "18125",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18126",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T01:49:40.963",
"Id": "18125",
"Score": "2",
"Tags": [
"c++",
"interview-questions"
],
"Title": "Lexicographic rank of a string"
}
|
18125
|
<p>I was surprised that I didn't find this approach to logging anywhere while reading up on the subject. So, naturally, I think I may be doing something wrong. I set up some simple tests, and this seems to work:</p>
<p>First, the source: <code>log.py</code></p>
<pre><code>import datetime
import logging
import os
import config
#this is very straightforward, nothing special here.
log = config.Parser('log')
def setup(stream_level=logging.INFO):
"""shared log named {log.name + log.format}.log
call this logging setup method once, in the main function
always refer to the config file when referring to the logger
in modules other than the main file, call a reference to the
already created logger in memory via log.hook(module_name)
as long as this setup() was ran in the main method, the logfile
should already exist in the proper place, with streams created
for use, according to the config file entry for 'log'.
`stream_level` indicates what level of
detail should be printed to the terminal
"""
log.level = log.level.upper()
logger = logging.getLogger(log.name)
logger.setLevel(log.level)
formatter = logging.Formatter(log.format)
formatter.datefmt = log.datefmt
pretty_date = datetime.date.strftime(datetime.datetime.now(), log.datefmt)
date_ext = filter(lambda x: x.isdigit(), pretty_date)
#terminal logging
if stream_level:
ch = logging.StreamHandler()
ch.setLevel(stream_level)
ch.setFormatter(formatter)
#file logging
logname = ''.join([log.name, date_ext, '.log'])
fh = logging.FileHandler(os.path.join(log.dir, logname))
fh.setLevel(log.level)
fh.setFormatter(formatter)
logger.addHandler(fh)
if stream_level:
logger.addHandler(ch)
return logger
def hook(module_name):
"""pass in the special method __name__ for best results
don't call this until you've setup() the logger in your main function
"""
return logging.getLogger('.'.join([log.name, module_name]))
</code></pre>
<p>And the <code>main.py</code></p>
<pre><code>import util
import log
logger = log.setup()
logger.info('starting now')
util.p()
logger.critical('quitting!')
</code></pre>
<p><code>util.py</code></p>
<pre><code>import log
def p():
logger = log.hook(__name__)
for x in range(10):
logger.warn('.')
</code></pre>
|
[] |
[
{
"body": "<p>You can find approach you are looking for in the <a href=\"http://docs.python.org/2/howto/logging-cookbook.html\" rel=\"nofollow\">logging cookbook</a> and <a href=\"http://docs.python.org/2/howto/logging.html\" rel=\"nofollow\">logging howto</a>: Default logging module provides nice configuration feature. </p>\n\n<p>So your code will be like this: </p>\n\n<p>simpleExample.py (main):</p>\n\n<pre><code>import os\nimport logging\nimport logging.config\nlogging.config.fileConfig(os.path.join(os.path.dirname(__file__),\n 'logging.conf') \nimport util\n\n# create logger\nlogger = logging.getLogger(\"simpleExample\") \n\n# 'application' code\nlogger.info('starting now')\n\nutil.p()\n\nlogger.critical('quitting!')\n</code></pre>\n\n<p>util.py</p>\n\n<pre><code>import logging\nlogger = logging.getLogger(\"simpleExample.Utils\")\n\ndef p():\n for x in range(10):\n logger.warn('.')\n</code></pre>\n\n<p>And all the magic of logging configuration will be avalible in config file:\nlogging.cfg: </p>\n\n<pre><code>[loggers]\nkeys=root,simpleExample\n\n[handlers]\nkeys=consoleHandler\n\n[formatters]\nkeys=simpleFormatter\n\n[logger_root]\nlevel=DEBUG\nhandlers=consoleHandler\n\n[logger_simpleExample]\nlevel=DEBUG\nhandlers=consoleHandler\nqualname=simpleExample\npropagate=0\n\n[handler_consoleHandler]\nclass=StreamHandler\nlevel=DEBUG\nformatter=simpleFormatter\nargs=(sys.stdout,)\n\n[formatter_simpleFormatter]\nformat=%(asctime)s - %(name)s - %(levelname)s - %(message)s\ndatefmt=`\n</code></pre>\n\n<p>You can use any handlers you want, and you can change levels, formats etc and you don't have to change your code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T20:40:58.343",
"Id": "18562",
"ParentId": "18132",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18562",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T13:42:33.667",
"Id": "18132",
"Score": "4",
"Tags": [
"python",
"logging"
],
"Title": "How's my approach to logging?"
}
|
18132
|
<p>I have some code that is used to hook into third party code. It goes pretty much like below (mind you CodeWeDontHave can't be posted because we dont have the source). I have an issue where sometimes my code will deadlock on the line commented below. Also, we get a object reference error now and then. </p>
<p>Is this the most effective way to hook into a 3rd party program where we have no source code? Typically, in Winforms we aren't supposed to set controls in this way e.g. Control.Text = "blah"; from another Form, rather via properties & events. In fact, I'm surprised this works at all. Is it safe? </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace BrianTests
{//this code requires a Form with a textbox called textBox1
public partial class CodeWeDontHave : Form
{
[DllImport("user32.dll")]
public extern static bool SetForegroundWindow(IntPtr hWnd);
public CodeWeDontHave()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Text = "structured notes entry";
//create another form that will attach to this one.
Form formThatWeOwn = new Form();
Button button = new Button() { Text = "upload text" };
formThatWeOwn.Controls.Add(button);
formThatWeOwn.Load += (a, b) => GetFormWithNoCode();
button.Click += OtherFormButton_Click;
formThatWeOwn.Show(this);
}
void OtherFormButton_Click(object sender, EventArgs e)
{
Button button = sender as Button;
UploadRtfToNoCodeForm();
//Close(); closes the parent...
button.FindForm().Close();//hackjob
}
private static Form GetFormWithNoCode()
{
Form noCodeForm = null;
System.Threading.Thread.Sleep(50);
noCodeForm = Application.OpenForms
.Cast<Form>()
.Where(form => form.Text.ToLower().StartsWith("structured notes entry"))
.FirstOrDefault();
return noCodeForm;
}
private static void UploadRtfToNoCodeForm()
{
Form noCodeForm = GetFormWithNoCode();
var textBox = noCodeForm.Controls
.Cast<Control>()
.GetChildren(c => c.Controls.Cast<Control>())
.Where(c => c is TextBox && String.Compare(c.Name, "textBox1", true) == 0)
.LastOrDefault() as TextBox;
string rtf = "here be some uploaded text";
SetForegroundWindow(noCodeForm.Handle);//Does this handle need memory cleanup?
noCodeForm.Focus();
textBox.Focus();
textBox.ReadOnly = false;//sometimes this line deadlocks...I can't reproduce in this test code
textBox.Text = rtf;
textBox.Update();
textBox.Focus();
textBox.ReadOnly = true;
}
}
static class ExtensionStuff
{
public static IEnumerable<T> GetChildren<T>(this IEnumerable<T> startingParentSet, Func<T, IEnumerable<T>> childrenSelector, bool includeParent = true)
{
foreach (T item in startingParentSet)
{
foreach (T child in item.GetChildren(childrenSelector, includeParent))
yield return child;
}
}
public static IEnumerable<T> GetChildren<T>(this T parent, Func<T, IEnumerable<T>> childrenSelector, bool includeParent = true)
{
if (parent == null) yield break;
if (includeParent)
yield return parent;
IEnumerable<T> children = childrenSelector(parent);
if (children == null) yield break;
foreach (T child in children)
{
foreach (T grandChild in child.GetChildren(childrenSelector, includeParent))
yield return grandChild;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>TextBox's ReadOnly flag is for <em>user input</em> only, see <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.readonly.aspx\" rel=\"nofollow\">MSDN</a>.</li>\n<li>Update only updates what is Invalidated. If you want to forcefully ensure a control is updated, use <a href=\"http://msdn.microsoft.com/en-us/library/598t492a.aspx\" rel=\"nofollow\">Invalidate</a>.</li>\n<li>I do not see a need to focus the textbox, unless the <code>noCodeForm</code> has some sort of validation or worker that requires it.</li>\n</ul>\n\n<p>So we're removing this weird deadlock line of code because it isn't needed, and making the control update every time. Add back your focuses if you need.</p>\n\n<pre><code> private static void UploadRtfToNoCodeForm()\n {\n Form noCodeForm = GetFormWithNoCode();\n\n var textBox = noCodeForm.Controls\n .Cast<Control>()\n .GetChildren(c => c.Controls.Cast<Control>())\n .Where(c => c is TextBox && String.Compare(c.Name, \"textBox1\", true) == 0)\n .LastOrDefault() as TextBox;\n\n string rtf = \"here be some uploaded text\";\n\n SetForegroundWindow(noCodeForm.Handle);\n\n // No focuses here, unless NoCodeForm requires it explicitly\n textBox.Text = rtf;\n textBox.Invalidate();\n }\n</code></pre>\n\n<p>Edit:\n<code>noCodeForm</code> does not need it's handle cleaned up by you. This handle is the hWnd aka Window Handle. It is the value you would see if using Spy++ to poke around and see things. You could use this hWnd to retrieve it directly or find its parent etc with PInvoke calls like <a href=\"http://www.pinvoke.net/default.aspx/user32/FindWindowEx.html\" rel=\"nofollow\">FindWindowEx</a> does. While you wouldn't actually do this here, just trying to explain what that Handle property is and a related use; tis term Handle is unrelated to pointers and memory.</p>\n\n<p>Edit2:\nAlternatively, you can use <a href=\"http://pinvoke.net/default.aspx/user32.SendMessage\" rel=\"nofollow\">SendMessage</a> and <a href=\"http://www.pinvoke.net/default.aspx/user32/PostMessage.html\" rel=\"nofollow\">PostMessage</a> to update controls. This would be something for StackOverflow, or you can post working code and we'll clean it up here too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-03T12:38:10.983",
"Id": "30732",
"ParentId": "18141",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-01T20:25:33.153",
"Id": "18141",
"Score": "8",
"Tags": [
"c#",
"winforms"
],
"Title": "Is this code to hook into a .NET window that we don't own safe? Can it be made safe?"
}
|
18141
|
<p>I'm implementing a version of the mean shift image processing algorithm for color segmentation in Python/NumPy.</p>
<p>I've written a pure NumPy version of the actual mean shifting per pixel (which I imagine is where the majority of time is taking). It slices an array of RGB values to work on out of the parent image, then creates lower bound and higher bound RGB reference arrays and generates a boolean masking array for the pixels to use for averaging then averages.</p>
<p>Any further optimizations? I suspect vectorizing the x/y for loops might give a speed up but for the life of me, but I haven't figured out how. (Some how generating an array of each pixel grid to work on and then generalizing the mean shift to take array input?) gL is grid length. gS is gL squared - the number of pixels in grid.</p>
<pre><code>for itr in xrange(itrs):
if itr != 0:
img = imgNew
for x in xrange(gL,height-gL):
for y in xrange(gL,width-gL):
cGrid = img[x-gSmp:(x+gSmp+1),y-gSmp:(y+gSmp+1)]
cLow,cUp = np.empty((gL,gL,3)),np.empty((gL,gL,3))
cLow[:] = [img[x,y][0]-tol,img[x,y][1]-tol,img[x,y][2]-tol]
cUp[:] = [img[x,y][0]+tol,img[x,y][1]+tol,img[x,y][2]+tol]
cBool = np.any(((cLow < cGrid) & (cUp > cGrid)),axis=2)
imgNew[x,y] = np.sum(cGrid[cBool],axis=0)/cBool.sum()
</code></pre>
|
[] |
[
{
"body": "<p>The following code is a first shot and it is still not vectorized. The major points here are the extraction of the creation of cLow and cUp (don't create arrays in loops, always 'preallocate' memory), the calculation of the tolerance levels can be done in one operation (under the assumption that broadcasting is possible at this point) and at last I removed the conditional case for copying the imgNew to img (I also doubt that you do not want to copy the last iteration back into img. If so you have to remove the copy line before the loop and move the copy at the beginning of the loop to its end.).</p>\n\n<pre><code>diff_height_gL = height - gL\ndiff_width_gL = width - gL\nsum_gSmp_one = gSmp + 1\n\ncLow, cUp = np.empty((gL, gL, 3)), np.empty((gL, gL, 3))\n\nimgNew = img.copy()\n\nfor itr in xrange(itrs):\n\n img[:] = imgNew\n\n for x in xrange(gL, diff_height_gL):\n for y in xrange(gL, diff_width_gL):\n\n cGrid = img[x-gSmp:(x + sum_gSmp_one), y-gSmp:(y + sum_gSmp_one)]\n\n cLow[:] = img[x, y, :] - tol\n cUp[:] = img[x, y, :] + tol\n\n cBool = np.any(((cLow < cGrid) & (cUp > cGrid)), axis=2)\n\n imgNew[x, y] = np.sum(cGrid[cBool], axis=0) / cBool.sum()\n</code></pre>\n\n<p>This problems seems to be perfectly shaped to do multiprocessing. This could be an alternative/extension to vectorization. If I have time I will try the vectorization...</p>\n\n<p>Kind regeards</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T13:25:27.737",
"Id": "18911",
"ParentId": "18149",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18911",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T08:14:44.973",
"Id": "18149",
"Score": "4",
"Tags": [
"python",
"optimization",
"image",
"numpy"
],
"Title": "Mean shift image processing algorithm for color segmentation"
}
|
18149
|
<p>I was trying, just for fun, to solve <a href="http://code.google.com/codejam/contest/dashboard?c=2075486#s=p4" rel="nofollow">http://code.google.com/codejam/contest/dashboard?c=2075486#s=p4</a> </p>
<p>I can easily solve the small set, but I struggle to solve the big one (my implementation would use approx. 30GB or RAM, which is a bit too much. Any hint or direction is appreciated!</p>
<pre><code>def solve_maze(case_no):
case = cases[case_no]
case_no += 1
edges = case['edges']
#quick and dirty check. Can we reach the goal?
if case['goal'] not in sum([i.values() for i in edges.values()],[]):
return "Case #%s: Infinity" % case_no
last_position = 1
l = 0
states = set()
memory = [1 for i in range(1,1+case['goal'])]
while not last_position==case['goal']:
direction = memory[last_position]
memory[last_position] *= -1
move = edges[last_position][direction]
states.add(hash((move,tuple(memory))))
l+=1
if len(states) != l:
return "Case #%s: Infinity" % case_no
last_position = move
else:
return "Case #%s: %d" % (case_no,len(states))
with open("/xxx/test-small.in","rb") as f:
inp = f.read()[:-1].split("\n")
N = int(inp[0])
cases = []
it = 0
for line in inp[1:]:
if line.find(" ") == -1:
#print int(line)
cases.append({"goal":int(line),"edges":{}})
it = 0
else:
it+=1
cases[-1]['edges'][it] = dict(zip([1,-1],map(int,line.split())))
for i in range(len(cases)):
print solve_maze(i)
</code></pre>
|
[] |
[
{
"body": "<pre><code>def solve_maze(case_no):\n case = cases[case_no]\n</code></pre>\n\n<p>It'd make more sense to pass the case here, and operate on that rather then passing in the case number</p>\n\n<pre><code> case_no += 1\n edges = case['edges']\n #quick and dirty check. Can we reach the goal?\n if case['goal'] not in sum([i.values() for i in edges.values()],[]):\n return \"Case #%s: Infinity\" % case_no\n</code></pre>\n\n<p>I avoid such quick and dirty checks. The problem is that they are easily defeated by a crafted problem. Not enough cases are really eliminated here to make it work.</p>\n\n<pre><code> last_position = 1\n l = 0\n states = set()\n memory = [1 for i in range(1,1+case['goal'])]\n</code></pre>\n\n<p>It's a little odd to add one to both parameters to range and then ignore the count</p>\n\n<pre><code> while not last_position==case['goal']:\n</code></pre>\n\n<p>Use != </p>\n\n<pre><code> direction = memory[last_position]\n memory[last_position] *= -1\n move = edges[last_position][direction]\n states.add(hash((move,tuple(memory))))\n</code></pre>\n\n<p>You aren't guaranteed to have distinct hashes for unequal objects so this must fail. You should really add the whole tuple to the state. Actually, you don't even need to track the states. There are are only so many possible states, and you can simply count the number of transitions, if this gets above the number of possible states, you're in an infinite loop.</p>\n\n<pre><code> l+=1\n if len(states) != l:\n return \"Case #%s: Infinity\" % case_no\n last_position = move\n else:\n return \"Case #%s: %d\" % (case_no,len(states))\n\n\n\nwith open(\"/xxx/test-small.in\",\"rb\") as f:\n inp = f.read()[:-1].split(\"\\n\")\n</code></pre>\n\n<p>This really isn't a good way to read your input. Use <code>f.readline()</code> to fetch a line at a time. It'll be much easier to parse the input that way.</p>\n\n<pre><code> N = int(inp[0])\n cases = []\n it = 0\n for line in inp[1:]:\n</code></pre>\n\n<p>Wrong choice of loop. You really want to repeat the process of reading a single case N times, not do something on each line of the file.</p>\n\n<pre><code> if line.find(\" \") == -1:\n #print int(line)\n cases.append({\"goal\":int(line),\"edges\":{}})\n</code></pre>\n\n<p>Don't treat dictionaries like objects. It'd make more sense to pass goal and edges as parameters rather them stick in a dictionary. At least, you should prefer an object.</p>\n\n<pre><code> it = 0\n else:\n it+=1\n cases[-1]['edges'][it] = dict(zip([1,-1],map(int,line.split())))\n for i in range(len(cases)):\n print solve_maze(i)\n</code></pre>\n\n<p>As for your algorithm. You can't get away with simulating all of the clearings. One can design a test case that takes over 2**39 steps to complete. So you can't simulate the straightforward process of moving one clearing at a time. But any given forest will have patterns in how the states change. You need to find a way to characterize the patterns so that you can simulate the process more quickly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T11:52:11.410",
"Id": "29041",
"Score": "0",
"body": "Thanks for the coding review. I was particularly interested in a comment on the algo but I was happy to see how I could have written a cleaner code. As for the infinite loop, now I am doing it by checking if the node I go to is somehow, optimally connected to the goal. If it's not, then I have an infinite loop. The hash was used in a test version to reduce the amount of memory used by the list, but I was aware of the high chance of collisions. I am now following the suggestion of a friend, i.e. trying to implement some DP on half of the set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T12:44:49.903",
"Id": "29043",
"Score": "0",
"body": "@luke14free, I believe that checking for connection to the goal won't be sufficient for infinite loops. I'm pretty sure I found cases where I was connected, but still in an infinite loop. The half-set DP solution should work, although its not the same solution I implemented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T13:08:50.780",
"Id": "29044",
"Score": "0",
"body": "Now I am tempted about asking for your idea.. :) But I won't! I'll delve a bit deeper and try to figure out other solution schemas"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T03:28:41.680",
"Id": "18201",
"ParentId": "18154",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T13:14:44.727",
"Id": "18154",
"Score": "2",
"Tags": [
"python",
"search"
],
"Title": "Shifting Paths problem (Code Jam)"
}
|
18154
|
<p>Just wondering if anyone can see a way to optimize this piece of code. It is a key piece of my program and needs to run as quickly as possible. The part of the code I am unsure of is the <code>while</code> loop for finding the nearest key -- but any assistance with optimizing the code would be appreciated.</p>
<pre><code>// TODO: Move to snippets lib or create a new collection type that supports this feature
private string _getTrait(SortedList<decimal, string> thisList, decimal thisValue)
{
// Check to see if we need to search the list.
if (thisList == null || thisList.Count <= 0) { return null; }
if (thisList.Count == 1) { return thisList.Values[0]; }
// Setup the variables needed to find the closest index
int lower = 0;
int upper = thisList.Count - 1;
int index = (lower + upper) / 2;
// Find the closest index (rounded down)
bool searching = true;
while (searching)
{
int comparisonResult = Decimal.Compare(thisValue, thisList.Keys[index]);
if (comparisonResult == 0) { return thisList.Values[index]; }
else if (comparisonResult < 0) { upper = index - 1; }
else { lower = index + 1; }
index = (lower + upper) / 2;
if (lower > upper) { searching = false; }
}
// Check to see if we are under or over the max values.
if (index >= thisList.Count - 1) { return thisList.Values[thisList.Count - 1]; }
if (index < 0) { return thisList.Values[0]; }
// Check to see if we should have rounded up instead
if (thisList.Keys[index + 1] - thisValue < thisValue - (thisList.Keys[index])) { index++; }
// Return the correct/closest string
return thisList.Values[index];
}
</code></pre>
<p>I am using C#, .net4.0 -- I need to use a Generic SortedList ( <a href="http://msdn.microsoft.com/en-US/library/ms132319(v=vs.100).aspx" rel="nofollow">http://msdn.microsoft.com/en-US/library/ms132319(v=vs.100).aspx</a> )</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T16:35:48.773",
"Id": "28962",
"Score": "0",
"body": "unrelated: I'm curious to know what a method beginning with an underscore means in your codebase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T17:27:10.677",
"Id": "28966",
"Score": "0",
"body": "This code runs extremely fast, even for big lists. I **strongly doubt** that this is your bottleneck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T18:15:09.833",
"Id": "28972",
"Score": "1",
"body": "@crdx anything with an _ in my database designates it as private. Just makes it easy to find the stuff I want when coding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T18:18:00.347",
"Id": "28973",
"Score": "0",
"body": "@codesparkle -- thanks for the insight, I still consider myself a novice when it comes to programming. The code looks messy to me and I felt there had to be better way to do it... Maybe I am lacking confidence rather than optimization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T20:16:28.533",
"Id": "28975",
"Score": "4",
"body": "Optimization starts with profiling. Don't guess where the bottlenecks are, **know** it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T18:19:01.260",
"Id": "214355",
"Score": "1",
"body": "There's no need for \"optimization\" or anything of the sort in the title. I've already added the relevant tag for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T19:02:27.100",
"Id": "214369",
"Score": "3",
"body": "Hi Anthony, your title should clearly state what your code does and there's no need to state optimisation and such in the question if it's just noise. @Jamal modified your question to better fit in line with our guidelines, but you've reverted the edits. When you post code on CR we are to review **the whole code** (and not just specific sections) on any aspect we see fit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T19:19:52.987",
"Id": "214377",
"Score": "0",
"body": "Languages don't need to be specified in the title of the question because we have tags that specify certain information for us and also allow search engines to see them properly. Code Review as a community has already decided that we should edit languages or other \"tags\" out of the title and add them to the tags list. check out this [Meta Post](http://meta.codereview.stackexchange.com/a/768/18427)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T20:22:34.943",
"Id": "214386",
"Score": "0",
"body": "I disagree -- first of all this question is over 3 years old - there is no need to edit it at this point. Second, having C# in the title makes it much easier to search on through external platforms like Google. If anyone REALLY thinks it necessary to update an old post by removing the word `Optimization` from the title feel free."
}
] |
[
{
"body": "<p>Your loop is pretty well written. The only thing that sticks out to me is your use of a constant in the while loop and manually breaking. I also prefer to use a slightly different version of CompareTo, but it doesn't make much difference:</p>\n\n<pre><code>while ( (lower<=upper))\n{\n int comparisonResult = thisValue.CompareTo( thisList.Keys [index]);\n if (comparisonResult == 0) { return thisList.Values[index]; }\n\n if (comparisonResult < 0)\n {\n upper = index - 1;\n }\n else\n {\n lower = index + 1;\n } \n index = (lower + upper) / 2; \n}\n</code></pre>\n\n<p>You might also be looking for a solution that's just easier to read or shorter. Are you familiar with LINQ? This is one possibility for how your function might look.</p>\n\n<pre><code> private static string GetTraitRefactor (SortedList<decimal, string> thisList, decimal thisValue)\n {\n var keys = thisList.Keys;\n var nearest = thisValue -\n keys.Where(k => k <= thisValue)\n .Min(k => thisValue - k);\n return thisList[nearest];\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T23:26:48.957",
"Id": "28981",
"Score": "0",
"body": "I have the constant bool in there because I need to update the index before it breaks, without the bool I think the index would miss the last update... Maybe I am wrong on that; I will try it a bit later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T23:28:17.147",
"Id": "28982",
"Score": "0",
"body": "Also, I know a little bit about LINQ but still learning. That looks like something that might be worth plugging in and seeing how it runs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:17:01.710",
"Id": "29006",
"Score": "0",
"body": "Marking this as the answer as it's the only one that I got -- thanks. While I didn't user any of the code provided you made me feel more confidant about my code and gave me some alternatives to work through. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T16:16:37.300",
"Id": "29105",
"Score": "2",
"body": "Like I mentioned, your loop is well coded and straightforward enough that there's not too much to do with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T17:14:44.780",
"Id": "214341",
"Score": "1",
"body": "Linq doesn't meet the \"needs to run as quickly as possible\" requirement. It performs a linear search rather than binary. The linq solution can be improved, however, by using `TakeWhile` instead of `Where`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T19:48:08.033",
"Id": "18161",
"ParentId": "18155",
"Score": "3"
}
},
{
"body": "<p>The classic calculation to average indices in binary search is</p>\n\n<pre><code>lower + (upper - lower) / 2\n</code></pre>\n\n<p>That's because (lower + upper) / 2 can overflow. Of course, in the 32-bit world, this is no longer very likely to happen.</p>\n\n<p>The linq soution proposed in another answer does not meet your requirement of \"needs to run as quickly as possible.\" Linq will do a linear search rather than a binary search.</p>\n\n<p>You can get rid of the <code>searching</code> variable (note that you assign it at the very end of the loop body, after all):</p>\n\n<pre><code>while (lower <= upper)\n//...\n</code></pre>\n\n<p>I think there's also no point in adding or subtracting 1. I once long ago did an analysis that showed that this doesn't improve the efficiency of the algorithm. You reduce the search range by 1 on each step, but you lose that because of the division by two. I'm not certain of this, however; it was a long time ago.</p>\n\n<p>You also don't need <code>else</code> if the <code>if</code> branch returns.</p>\n\n<p>Therefore:</p>\n\n<pre><code>while (lower <= upper)\n{\n int comparisonResult = Decimal.Compare(thisValue, thisList.Keys[index]);\n\n if (comparisonResult == 0) { return thisList.Values[index]; }\n\n if (comparisonResult < 0) { upper = index; }\n else { lower = index; }\n\n index = lower + (upper - lower) / 2;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T17:25:18.003",
"Id": "115436",
"ParentId": "18155",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18161",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T15:17:18.143",
"Id": "18155",
"Score": "6",
"Tags": [
"c#",
".net"
],
"Title": "C# Code Optimization -- Finding nearest key in a SortedList"
}
|
18155
|
<p>First, some background. I have a <code>Payment</code> model that <code>has_many :subscriptions</code>. When a user pays (creates a new payment), I have an <code>after_create</code> callback that adds the newly created <code>@payment.id</code> to <code>@subscriptions.payment_id</code>. Here's what it looks like:</p>
<pre><code>def update_subscription
@unpaid_subs = Subscription.where(:user_id => self.user_id).unpaid
@unpaid_subs.each do |sub|
sub.payment_id = self.id
sub.start # call to state_machine to change state from pending -> active
sub.save
end
end
</code></pre>
<p>I know that doing database queries inside a loop is generally not good for performance, but I don't know any way to update multiple records at the same time. Also, is there a way to pass the <code>@unpaid_subs</code> instance variable from my create action to the callback (it's the same query on both) so that I can remove the query here?</p>
|
[] |
[
{
"body": "<p>Considering you have a state machine, you're probably doing the right thing by looping through the records. Although you could change all the subscriptions (including their state) in the database, you'd be bypassing the state machine and whatever checks and callbacks it has in place.</p>\n\n<p>But, if you really want to bypass the state machine, you could probably do something like this:</p>\n\n<pre><code>unpaid_subs = self.user.subscriptions.unpaid # I'm assuming Payment belongs_to User\nunpaid_subs.update_attributes(:payment_id => self.id, :state => 'active')\n</code></pre>\n\n<p>Of course, it would require you to <em>allow mass-assignment</em> of both <code>payment_id</code> and (what I assume is named) <code>state</code>, neither of which sound like good ideas at all.</p>\n\n<p>So you'd have to bypass the state machine <em>and</em> ActiveRecord to directly update the records in the database with some raw SQL... ugh, gross.</p>\n\n<p>So, as I said, you're probably doing the right thing already :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T22:32:09.843",
"Id": "29019",
"Score": "0",
"body": "Well, I'm glad to know I'm doing it right. I was thinking it'd be bad performance wise, but I couldn't think of any other way to do it. I definitely don't want to mass-assign `:payment_id` or `:state`. I actually might get rid of the state_machine in the next version, since it's a bit overkill for my implementation. Payment actually doesn't `belong_to :user` right now, though that's a great idea. I had [asked a question about that a few weeks ago on SO](http://stackoverflow.com/questions/12961706/how-do-i-access-information-from-multiple-associated-models-in-the-controller-in)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T23:34:09.563",
"Id": "29021",
"Score": "0",
"body": "@GorrillaMcD Well, performance-wise it's only \"bad\" if what you're doing is unnecessary. But in this case triggering the state transition is necessary, so you can't avoid loading the records. However, in the interest of robustness (if you keep the state machine), it might be good to tie the state transition directly to setting `payment_id`, so you can't transition without a payment, and can't set a payment without changing state. But that's about robustness rather than performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T04:42:16.490",
"Id": "29030",
"Score": "0",
"body": "Thanks, I didn't think about that. I'll be sure to do that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T21:38:47.357",
"Id": "18194",
"ParentId": "18158",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T16:57:51.207",
"Id": "18158",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"callback"
],
"Title": "Update subscription"
}
|
18158
|
<p>My application has two parts -- a client and a server. Within this, there are different versions for different platforms. The user specifies this in the args, i.e. "make PLATFORM=x11".</p>
<p>However, I feel like I'm separating the client and server build operations in a very inefficient way, and that I have too many variables. It works, but I'm not sure how to improve it. </p>
<p>Any suggested improvements would be much appreciated!</p>
<pre><code>CC=gcc
CFLAGS=-c -Wall
LDFLAGS=
BUILD_DIR = ../build/
OBJ_DIR = $(BUILD_DIR)obj/
LIBS=
CLIENT_NAME_DIR = client/
CLIENT_SRC_FILES := $(wildcard $(CLIENT_NAME_DIR)*.c)
CLIENT_PLATFORM_DIR = $(PLATFORM)/
CLIENT_SRC_FILES += $(wildcard $(CLIENT_NAME_DIR)$(CLIENT_PLATFORM_DIR)*.c)
CLIENT_OBJ_DIR = $(OBJ_DIR)$(CLIENT_NAME_DIR)
CLIENT_OBJ_FILES := $(addprefix $(CLIENT_OBJ_DIR),$(notdir $(CLIENT_SRC_FILES:.c=.o)))
CLIENT_LIBS = $(LIBS) -lX11
CLIENT_EXECUTABLE_NAME = outcast-client
CLIENT_EXECUTABLE=$(BUILD_DIR)$(CLIENT_EXECUTABLE_NAME)
SERVER_NAME_DIR = server/
SERVER_SRC_FILES := $(wildcard $(SERVER_NAME_DIR)*.c)
SERVER_OBJ_DIR = $(OBJ_DIR)$(SERVER_NAME_DIR)
SERVER_OBJ_FILES := $(addprefix $(SERVER_OBJ_DIR),$(notdir $(SERVER_SRC_FILES:.c=.o)))
SERVER_LIBS = $(LIBS)
SERVER_EXECUTABLE_NAME = outcast-server
SERVER_EXECUTABLE=$(BUILD_DIR)$(SERVER_EXECUTABLE_NAME)
all: clean client server
client: $(CLIENT_SRC_FILES) $(CLIENT_EXECUTABLE)
server: $(SERVER_SRC_FILES) $(SERVER_EXECUTABLE)
$(CLIENT_EXECUTABLE): $(CLIENT_OBJ_FILES)
$(CC) $(LDFLAGS) $(CLIENT_OBJ_FILES) -o $@ $(CLIENT_LIBS)
$(CLIENT_OBJ_DIR)%.o: $(CLIENT_NAME_DIR)$(CLIENT_PLATFORM_DIR)%.c
$(CC) $(CFLAGS) -c -o $@ $<
$(CLIENT_OBJ_DIR)%.o: $(CLIENT_NAME_DIR)%.c
$(CC) $(CFLAGS) -c -o $@ $<
$(SERVER_EXECUTABLE): $(SERVER_OBJ_FILES)
$(CC) $(LDFLAGS) $(SERVER_OBJ_FILES) -o $@ $(SERVER_LIBS)
$(SERVER_OBJ_DIR)%.o: $(SERVER_NAME_DIR)%.c
$(CC) $(CFLAGS) -c -o $@ $<
clean:
rm -rf $(BUILD_DIR)
mkdir -p $(CLIENT_OBJ_DIR)
mkdir -p $(SERVER_OBJ_DIR)
</code></pre>
|
[] |
[
{
"body": "<p>You can definitely simplify that:</p>\n\n<pre><code>TARGET ?= CLIENT\n\nSRC_FILES := $(wildcard $($(TARGET)_NAME_DIR)*.c)\n\n ^^^^^^^^^^^\n</code></pre>\n\n<p>Here $(TARGET) will expand first (to CLIENT or what is set on the command line) and then $(CLIENT_NAME_DIR) will be expanded.</p>\n\n<p>So you end up with only a few variables specific to the Client/Server and all the other variables are generalized based on that. The same then applies to all your build rules which can be collapsed down into one set of commands (rather than two).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T21:23:39.610",
"Id": "18162",
"ParentId": "18159",
"Score": "1"
}
},
{
"body": "<p>Conner, I have a few minor points. </p>\n\n<ul>\n<li><p>Firstly, you have no includes (ie, no <code>-Idir</code>). Do you really have no headers? </p></li>\n<li><p>You should make the non-targets 'PHONY' so <code>make</code> knows they will never exist:</p>\n\n<pre><code>.PHONY clean\nclean: \n rm -f ...\n</code></pre>\n\n<p>Same with <code>all</code>, <code>server</code> and <code>client</code></p></li>\n<li><p>It is not normal to clean everything on each build - usually you let <code>make</code> decide what is out of date and needs to be rebuilt. For that you need to have all the dependencies declared to <code>make</code> (eg headers)</p></li>\n<li><p><code>client</code> and <code>server</code> depend upon the build directories and the executables, but not directly upon the sources.</p></li>\n<li><p>the <code>clean</code> target remakes the build directories. To me, these directories should be made when you build the targets:</p>\n\n<pre><code>$(CLIENT_OBJ_DIR) $(SERVER_OBJ_DIR):\n mkdir -p $@ \n\nclient: $(CLIENT_OBJ_DIR) $(CLIENT_EXECUTABLE)\n\nserver: $(SERVER_OBJ_DIR) $(SERVER_EXECUTABLE)\n</code></pre></li>\n<li><p><code>-Wall</code> does not really give you 'all' warnings. There are many more that are worth enabling.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T12:52:30.753",
"Id": "88568",
"Score": "0",
"body": "Very sorry that it took me a year and a half to accept your answer... better late than never? :) Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T01:52:52.230",
"Id": "18168",
"ParentId": "18159",
"Score": "3"
}
},
{
"body": "<p>Not exactly what you are asking for but I would suggest using\n<strong><a href=\"http://www.cmake.org\" rel=\"nofollow noreferrer\">cmake</a></strong> instead. Some benefits:</p>\n\n<ul>\n<li>less code</li>\n<li>support for a separate build tree</li>\n<li>avoiding the white-space (tab) bugs that occur easily in a Makefile</li>\n</ul>\n\n<p>First create a file called CMakeLists.txt with this content:</p>\n\n<pre><code>cmake_minimum_required(VERSION 2.8)\nproject(outcast)\nset(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -Wall\")\nfile(GLOB client_sources \"client/${PLATFORM}/*.c\")\nadd_executable(outcast-client ${client_sources})\ntarget_link_libraries(outcast-client x11)\ninstall(TARGETS outcast-client RUNTIME DESTINATION bin)\nfile(GLOB server_sources \"server/*.c\")\nadd_executable(outcast-server ${server_sources})\ninstall(TARGETS outcast-server RUNTIME DESTINATION bin)\n</code></pre>\n\n<p>then build and install your programs <strong>outcast-client</strong> and <strong>outcast-server</strong> like this</p>\n\n<pre><code>erik@linux:~$ ls ~/outcast_source\nCMakeLists.txt client/ server/\nerik@linux:~$ mkdir /tmp/build\nerik@linux:~$ mkdir /tmp/install\nerik@linux:~$ cd /tmp/build/\nerik@linux:/tmp/build$ CC=gcc cmake -DPLATFORM=X11 -DCMAKE_INSTALL_PREFIX=/tmp/install ~/outcast_source\n</code></pre>\n\n<p>Instead of finding the source files with a GLOB expression it is\nprobably better to list them one by one. See\n<a href=\"https://stackoverflow.com/questions/1027247/best-way-to-specify-sourcefiles-in-cmake\">https://stackoverflow.com/questions/1027247/best-way-to-specify-sourcefiles-in-cmake</a></p>\n\n<p>CMake has great support for detecting properties of the build system. You could for instance write something like this in your CMakeLists.txt</p>\n\n<pre><code>find_package(X11)\nif(${X11_FOUND})\n file(GLOB client_sources \"client/X11/*.c\")\n add_executable(outcast-client ${client_sources})\n target_link_libraries(outcast-client ${X11_LIBRARIES})\n install(TARGETS outcast-client RUNTIME DESTINATION bin)\nendif()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T12:53:26.067",
"Id": "88569",
"Score": "0",
"body": "For what it's worth, I did end up switching to CMake (as well as using it for most later projects). Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T18:48:01.743",
"Id": "18288",
"ParentId": "18159",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18168",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T18:53:02.183",
"Id": "18159",
"Score": "4",
"Tags": [
"c",
"makefile"
],
"Title": "Makefile -- Platform Dependency"
}
|
18159
|
<p>I have the following <code>.click()</code> functions:</p>
<pre><code>$('.tab').click(function(){
$('.tab').removeClass('activeTab');
$(this).addClass('activeTab');
});
$('.edit').click(function(){
$(this).hide();
$(this).next().show();
});
$('.cancel').click(function(){
$(this).parent().hide();
$(this).parent().prev().show();
});
</code></pre>
<p><em>Is it possible to combine these functions doing something like this?</em></p>
<p><strong>Pseudocode:</strong></p>
<pre><code>$.click(function(){
for $('.tab'){
//do this
}
for $('.edit'){
//do this
}
for $('.cancel'){
//do this
}
});
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><a href="javascript:void(0);" class="edit">Edit</a>
<span class="controls">
<a href="javascript:void(0);" class="cancel">Cancel</a> |
<a href="javascript:void(0);" class="save">Save</a>
</span>
</code></pre>
|
[] |
[
{
"body": "<p>I think you're looking for something along the lines of:</p>\n\n<pre><code>$('.tab, .edit, .cancel').click(function(){\n switch(this.className){\n case 'tab' : {\n $('.tab').removeClass('activeTab');\n $(this).addClass('activeTab');\n }break;\n case 'edit' : {\n $(this).hide();\n $(this).next().show();\n } break;\n case 'cancel' : {\n $(this).parent().hide();\n $(this).parent().prev().show();\n } break;\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:57:47.177",
"Id": "29011",
"Score": "1",
"body": "I fixed your selector. But -1: your code still does not work. You can't switch on the element and expect that the comparison will magically check the class of the element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T20:59:11.463",
"Id": "29015",
"Score": "0",
"body": "@ANeves: Sorry, was 4:30am here whenI wrote it. I'll correct it now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T21:13:57.057",
"Id": "29017",
"Score": "0",
"body": "@ANeves I'll take a +1 now that the code works :) and again, my apologies for writing incorrect code...never code sans sleep."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T01:47:54.667",
"Id": "29070",
"Score": "2",
"body": "This would fail if an element had more than one class. For example: `<div class=\"cancel button\"><div>`. The `className` of that is `cancel button` which obviously does not equal cancel."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T08:32:06.453",
"Id": "18176",
"ParentId": "18160",
"Score": "4"
}
},
{
"body": "<p>I'm not sure about this but I think you can use your own manager in order to keep spaghetti code to a minimum.</p>\n\n<p>Demo: <a href=\"http://jsfiddle.net/8C5wR/1/\" rel=\"nofollow\">http://jsfiddle.net/8C5wR/1/</a></p>\n\n<pre><code>function ClickManager(element) {\n this.el = $(element);\n this.check = function(){\n if (this.el.hasClass('class1')) {\n console.log('class 1 detected'); \n }\n\n if (this.el.hasClass('class2')) {\n console.log('class 2 detected'); \n }\n\n if (this.el.hasClass('class3')){\n console.log('class 3 detected'); \n }\n };\n}\n\n(function(){\n $('.class1, .class2, .class3').on('click', function(){\n manager = new ClickManager(this);\n manager.check();\n });\n})();\n</code></pre>\n\n<p>Maybe others can weigh in to point out possible fallouts of this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T21:11:51.543",
"Id": "29016",
"Score": "0",
"body": "Why can't we simply do `this.el = element`, or `new ClickManager(this);`? Also, you are recreating the ClickManager in every click; shouldn't it be done only once, and then `.check()` called repeatedly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T21:34:54.300",
"Id": "29018",
"Score": "0",
"body": "Right. I already change it to ClickManager(this). As for repeating the instantiation, well, yes, what about this? http://jsfiddle.net/ePYmz/. It required some changes but I don't know whether this is the right approach or not in situations where extensibility is needed. Is there a way to keep new ClickManager outside of every click call and yet being able to use something like this.el = $(element)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T06:32:14.007",
"Id": "29031",
"Score": "0",
"body": "Much better, IMO. (Well, but then you don't need the ClickManager, only the handler... sorry, I really don't like the question you're trying to answer.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T06:56:09.233",
"Id": "29032",
"Score": "1",
"body": "The `ClickManager` seems way overkill. http://jsfiddle.net/8C5wR/5/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T07:35:54.583",
"Id": "29033",
"Score": "2",
"body": "@Corbin That's exactly what I want to avoid. Try to use that approach in a serious application and you will end up dealing with messy code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T07:39:35.703",
"Id": "29034",
"Score": "1",
"body": "@ANeves As I said before, we have to consider that something like this is going to be used in something with a good deal of functionality, so we need a manager. Although, I would like to know if there are alternatives that work in complex code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T21:00:00.497",
"Id": "29064",
"Score": "1",
"body": "@RobertSmith So rather than managing three handlers, you'd rather manager three handlers *and* their wrapper? It's just adding complexity. What if you want to use the handlers independently? What if you want to only bind two of them at some point? (Oh, by the way, part of the confusion might be the jsfiddle I posted. I disagree with the code in that fiddle. I think the proper way is as I said in my answer: leave them separate. I just think if you aren't going to separate them, there's no reason to add yet another coupling.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T00:37:50.157",
"Id": "29068",
"Score": "0",
"body": "@Corbin The question here is not whether we are going to use three handlers or not, but how we are going to manage them. Obviously, if you want to provide more functionality, another solution would be appropriate. As always, this solution doesn't have to be the ultimate solution to every problem. Another solution would be to use different classes for each action, so you could reuse every class in different buttons, passing parameters depending on context. Of course, this assuming that you're going to do a lot in every action which may or may not be true."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T01:45:28.177",
"Id": "29069",
"Score": "2",
"body": "@RobertSmith It sounds to me like you're jumping the gun with making classes. These handlers don't hold state, so they don't particularly need a class-style context associated with them. To each his own though, I suppose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T01:52:39.137",
"Id": "29071",
"Score": "0",
"body": "By handlers you mean each $('#something').on('click', ... right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T04:03:23.393",
"Id": "29080",
"Score": "0",
"body": "@RobertSmith Yes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T23:18:44.217",
"Id": "29128",
"Score": "0",
"body": "@Corbin Oh, sorry, I meant to say \"Another solution would be to use different methods for each action...\". Having said that, not sure what you mean by '... (handlers) don't particularly need a class-style context...' Is that a kind of rule for using classes? A few months ago I wrote quite a bit of functionality for textareas and it worked just fine but as I was suggesting, that functionality wasn't focused on handlers but in providing methods and properties to a given object (in this case, textareas). It seems to me I couldn't have been able to do that using Flambinos' solution, for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T23:19:22.423",
"Id": "29129",
"Score": "0",
"body": "Although for a small piece of code it's absolutely ok."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-07T01:10:43.577",
"Id": "29153",
"Score": "0",
"body": "@RobertSmith In certain situations, like the one you described, I can see where that would be beneficial. That is basically what jQuery is doing after all, and I think we can all agree that jQuery is doing it right :). In the snippet in your answer though, the class *isn't* adding anything. It's basically acting as a very thin wrapper around the `check` method. If it's not adding anything, and it's making the API more difficult to use, why bother having the ClickManager class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T17:06:54.397",
"Id": "29357",
"Score": "0",
"body": "@Corbin It's not adding anything because it's an example. In a real situation, it would get methods and properties. That is when you get the benefits of using an object-oriented approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T19:41:03.217",
"Id": "29361",
"Score": "0",
"body": "Even if I cede that point, your one check method should be 3 methods. And, the hasClass should probably not be in the check method. That could make sense in a few situations (like if the class were the code responsible for adding/remove the classes), but here it does not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T19:55:53.283",
"Id": "29363",
"Score": "0",
"body": "It could be. What are the other 2 methods? One for each class detection?"
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T19:30:38.663",
"Id": "18189",
"ParentId": "18160",
"Score": "0"
}
},
{
"body": "<p>To answer your question directly: yes, it's possible to combine them into one function.</p>\n\n<p>Is it advisable in the way you presented though? No.</p>\n\n<p>I would argue that anytime there's a function with hard coded functionality controls, something is probably wrong.</p>\n\n<p>Consider this for example:</p>\n\n<pre><code>function someHandler() {\n var $this = $(this);\n if ($this.hasClass('class-a')) {\n //do something specific to a\n }\n if ($this.hasClass('class-b')) {\n //do something specific to b\n }\n if ($this.hasClass('class-c')) {\n //do something specific to c\n }\n}\n\n$(\".class-a, .class-b, .class-c\").click(someHandler);\n</code></pre>\n\n<p>The easiest way to illustrate why this is a problem is to consider what happens if you want to reuse any of the specific functionalities.</p>\n\n<p>How would you reuse the functionality in the <code>//do something specific to a</code> segment on something that doesn't have the class <code>class-a</code> without copying and pasting the code? You couldn't. (Well, not cleanly anyway.)</p>\n\n<p>For this reason, it's good to try to separate functionalities and their bindings:</p>\n\n<pre><code>function someHandlerA() {\n //do something specific to a\n}\nfunction someHandlerB() {\n //do something specific to b\n}\nfunction someHandlerC() {\n //do something specific to b\n}\n$(\".class-a\").click(someHandlerA);\n$(\".class-b\").click(someHandlerB);\n$(\".class-c\").click(someHandlerC);\n</code></pre>\n\n<p>Now what if you want to reuse the functionality? It's easy: <code>$(\"some selector\").bind(\"some event\", someHandler);</code></p>\n\n<p>Obviously in large applications it becomes a lot more complex than this. There are of course times when it's ok to switch functionalities based on some condition. It's typically best to keep different functionalities as atomic as possible though. It relates back to the idea of separation of concerns. Each segment of code should do only one thing, even if that one thing is just dispatching to more than one thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T03:52:11.623",
"Id": "29077",
"Score": "0",
"body": "I agree with the TL;DR part. Separate handlers for separate ideas but the rest of this is not really an answer. Why are switch statements typically a bad sign? How can this be improved using this idea that the handlers can stay separate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T04:02:58.230",
"Id": "29079",
"Score": "1",
"body": "@JamesKhoury I should have been a lot more specific in my answer, I suppose. A switch that controls the functionality of a function is typically a bad sign (or a switch-fallthrough type construct like his example uses -- not sure now why I read that as a switch). It means that potentially disjoint functionalities are being crammed into the same place for convenience. (Or, in some situations, because responsibilities are not placed in the right segments.) I don't have time now, but I will update my answer later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-07T01:24:36.307",
"Id": "29155",
"Score": "0",
"body": "@JamesKhoury Have updated it to be more specific :)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T06:30:24.300",
"Id": "18204",
"ParentId": "18160",
"Score": "5"
}
},
{
"body": "<p>First off, I'd rewrite the HTML to get rid of the javascript <code>href</code> attributes. I'd also use a <code>data-action</code> attribute for the action name. You can still use class to do the styling of course, but style is not behavior, so keep those things separate (i.e. the class might be <code>action-button primary highlighted</code> or something, but the <em>action</em> would still be <code>save</code>):</p>\n\n<pre><code><a href=\"#\" data-action=\"edit\">Edit</a>\n<span class=\"controls\">\n <a href=\"#\" data-action=\"cancel\">Cancel</a> |\n <a href=\"#\" data-action=\"save\">Save</a> \n</span>\n</code></pre>\n\n<p>Code-wise, what each link has in common is that they should <code>preventDefault</code> so the links aren't \"followed\" when clicked. So at the very least, we'll need this:</p>\n\n<pre><code>$(\"a[data-action]\").on(\"click\", function (event) {\n event.preventDefault();\n});\n</code></pre>\n\n<p>Then of course, there are the actions/behaviors themselves. I'd suggest putting the logic for each in an object, and expanding the generic click handler like so:</p>\n\n<pre><code>var actions = {\n edit: function (event) { ... },\n cancel: function (event) { ... },\n save: function (event) { ... }\n};\n\n$(\"a[data-action]\").on(\"click\", function (event) {\n var link = $(this),\n action = link.data(\"action\");\n\n event.preventDefault();\n\n // If there's an action with the given name, call it\n if( typeof actions[action] === \"function\" ) {\n actions[action].call(this, event);\n }\n});\n</code></pre>\n\n<p>Now you have a generic click handler, and an easily extensible list of actions. The action functions themselves behave exactly like normal jQuery event handlers (i.e. <code>this</code> will refer to the link clicked, and the first argument will be the event).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T02:41:23.907",
"Id": "29074",
"Score": "2",
"body": "*slowclap* this was the answer I said japanFour should wait for!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T15:25:19.877",
"Id": "18215",
"ParentId": "18160",
"Score": "30"
}
}
] |
{
"AcceptedAnswerId": "18215",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T19:04:01.393",
"Id": "18160",
"Score": "11",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Different way of writing multiple click functions"
}
|
18160
|
<p>With some free time, I decided to study artificial neural networks as an academic exercise (not homework). Over the course of my studies, I decided to write a Python application that would allow me to create and train arbitrary feed forward networks so I could see the concrete math. So far, the test harness only includes simple AND, OR, NOT, and (slightly less simple) XOR with perfect inputs.</p>
<p>Quite honestly, in 8 years of professional development, I've never had my code reviewed. What I am looking for in code review is commentary on:</p>
<ul>
<li>my use of Python language features (not the decision to use Python, mind)</li>
<li>the data structures and logical flows - especially if I have a logical flaw somewhere</li>
<li>general program design</li>
</ul>
<p>I'd also gladly welcome expert advice on ANN in general.</p>
<p><strong>perceptron.py</strong></p>
<pre><code>"""
Equations from http://ecee.colorado.edu/~ecen4831/lectures/NNet3.html
t[i] = desired output of unit i
a[i] = actual output of unit i
a[i] = f(u[i]) = 1 / (1 - exp(-u[i])) # or experiment with other sigmoid functions
u[i] = sum(j=0..numinputs, W[i][j]*a[j]) + theta[i]
delta[i] = t[i] - a[i]
E = sum(i, pow(delta, 2)) # only over output units because we don't know what the activation of hidden units should be
dW[i][j] proportional to -(derivative(E) / derivative(W[i][j]))
. # apply chain rule
. = -(derivative(E)/derivative(a[i]))(derivative(a[i])/derivative(W[i][j]))
. = 2(t[i] - a[i])*a[i]*(1-a[i])*a[j]
. (NOTE: df[i] / du[i] = f[i]*(1 - f[i]) = a[i]*(1 - a[i]))
if unit i is output:
. change_rate[i] = (t[i] - a[i]) * a[i] * (1-a[i])
if unit i is hidden, we don't know the target activation, so we estimate it:
. change_rate[i] = (sum(k, dr1[k] * W[k][i])) * a[i] * (1-a[i])
. ASSUME: sum(k, dr1[k] * W[k][i]) is approximately (t[i] - a[i])
. (The sum over k is the sum over the units that receive input from the ith unit.)
dW[i][j](n+1) = learning rate * change_rate[i] * a[j] + alpha*dW[i][j](n), j=0..numinputs
"""
import math
def i_report_pattern(activations, training_values, change_rates, weights, dweights):
"""
Empty prototype for reporting the state of a network following a training pattern.
activations:
. A dictionary of node index and output value. This must include the raw
. input nodes, and must have as many elements as nodes in the ANN.
change_rates:
. A dictionary of node index and delta function value used to calculate weight
. changes in training.
weights:
. A dictionary of node index and array of weights with theta appended.
dweights:
. A dictionary of node index and array of deltas to be applied to the
. weights and theta.
Example from perceptron of 2 inputs, 1 hidden node, and 1 output node
(1st epoch, 1st pattern):
. activations = { 0:0.00, 1:0.00, 2:0.50, 3:0.50 }
. training_values = { 3:0.00 }
. change_rates = { 2:0.0000, 3: -0.1250 }
. weights = { 2:[0.0000,0.0000,0.0000], 3:[0.0000,0.0000,0.0000,0.0000] }
. dweights = { 2:[0.0000,0.0000,0.0000], 3:[0.0000,0.0000,-0.0156,-0.0312] }
"""
pass
class TrainingStrategy(object):
PATTERN = "P"
EPOCH = "E"
class Node(object):
"""
Represents one neuron in a perceptron with memory of last input and all
weight changes applied during the life of this instance.
"""
def __init__(self, numinputs):
self.numinputs = numinputs
self.weights = [0]*numinputs
self.theta = 0
self.last_input = None
# Remember all dW & dTheta values until they are applied to the weights and theta.
self.temp_delta_memory = []
# Remember all dW & dTheta values for life. dTheta is appended to dW here for simplicity.
self.perm_delta_memory = [([0]*(numinputs),0)]
def __str__(self): return '{} ; {} ; {}'.format(str(self.weights), self.theta, str(self.temp_delta_memory))
def accept_input(self, input_vector, transform_function):
"""
Apply the transform function to the results of sum(V[i] * W[i]) + Theta,
i indexes each element in the input_vector.
input_vector: an enumerable of scalar values, the length of which must
. match the number inputs specified during initialization.
transform_function: a scalar function with one scalar input. Examples
. include the step function (1 if x >= 0 else 0) and
. the sigmoid function 1 / (1 - exp(-x)).
"""
def sum_function(V, W, Theta):
return sum(v * W[vi] for vi,v in enumerate(V)) + Theta
self.last_input = input_vector
return transform_function(sum_function(input_vector, self.weights, self.theta))
def remember_deltas(self, delta, learning_epsilon, learning_acceleration):
"""
Calculate dW[i] and dTheta based on the last input value, the training delta,
learning rate, learning acceleration, and pervious dW[i] and dTheta values.
These values are temporarily stored instead of immediately applied so they can
be applied following an epoch, if desired. These values are also permanently
stored for the life of this node.
delta: scalar value representing the difference between expected output and actual.
learning_epsilon: multiplier to control the magnitude of weight change
learning_acceleration: provides momentum in the learning process and is multiplier
. on previous values of dW[i] and dTheta
"""
# add the previous deltas times a learning acceleration factor (learning_acceleration) both to
# help prevent radical weight changes and to apply some momentum to learning.
p_dweights, p_dtheta = self.perm_delta_memory[-1]
magnitude = delta * learning_epsilon
dW = [magnitude * self.last_input[vi] + learning_acceleration * p_dweights[vi] for vi in range(self.numinputs)]
dTheta = magnitude + learning_acceleration * p_dtheta
self.temp_delta_memory.append((dW, dTheta)) # remember until deltas are applied to weights
self.perm_delta_memory.append((dW, dTheta)) # remember for life.
def apply_deltas(self):
"""
Add all previously calculated dW[i] and dTheta values to W[i] and Theta, then
forget the dWs and dThetas.
"""
for dW, dTheta in self.temp_delta_memory:
self.weights = [w + dW[wi] for wi,w in enumerate(self.weights)]
self.theta += dTheta
self.temp_delta_memory = []
class FFPerceptron(object):
"""
A feed-forward artificial neural network with configurable neural pathways.
"""
def __init__(self, transform_function, links):
"""
transform_function:
. Any scalar function with one input, which will be applied to the output of every
. node. The intent is to support arbitrarily step functions, sigmoid functions, and
. unmodified output.
links:
. A collection of pairs of input vectors and output vectors.
. Inputs will be sent in specified order to each output. Order of processing within
. a particular output vector is not guaranteed.
. LIMITATIONS:
. Output nodes should only appear once in any given output vector.
. An output must have a consistent number of inputs if it is to exist in
. multiple output vectors.
. A node may only receive one input vector, because it will only be
. processed once per system input.
"""
from collections import defaultdict
sender_node_ixs = set(ni for iv,ov in links for ni in iv) # all nodes that send input to another node.
receiver_node_ixs = set(ni for iv,ov in links for ni in ov) # all nodes that receive input from another node.
nodes = defaultdict(lambda:None) # all nodes with calculation function
output_paths = defaultdict(list) # tracks which inputs go to which nodes
# generate node instances and build output paths.
for input_vector,output_vector in links:
for node_index in output_vector:
if node_index not in nodes: # In case a node shows up in multiple output vectors.
nodes[node_index] = Node(len(input_vector))
for node_position,node_index in enumerate(input_vector):
output_paths[node_index].extend([{'atposition':node_position, 'tonode':output_node_index} for output_node_index in output_vector])
self.links = links
self.output_node_ixs = receiver_node_ixs - sender_node_ixs # nodes that output from the system.
self.input_node_ixs = sender_node_ixs - receiver_node_ixs # nodes that are input to the system.
self.nodes = nodes
self.output_paths = output_paths
self.transform_function = transform_function
self.activation_memory = [{i:0 for i in range(len(self.nodes))}]
def __str__(self): return '::'.join(str(n) for n in self.nodes)
def accept_input(self, input_vector):
"""
Processes the input vector through all nodes and returns the final activation
value(s). Remembers all activations for future training.
input_vector: an enumerable of scalar values, the length of which must
. match the number input nodes specified in the links parameter
. during initialization
"""
from collections import defaultdict
# remember all activations by node index.
activations = defaultdict(lambda:0)
# input values are easy.
for vi,v in enumerate(input_vector): activations[vi] = v
for linkin,linkoutlist in self.links:
# Sequentally calculate and remember the activations for all non-input nodes.
# Only process a node once.
for node_index in linkoutlist:
if node_index not in activations:
v = tuple(activations[i] for i in linkin)
node = self.nodes[node_index]
activations[node_index] = node.accept_input(v, self.transform_function)
self.activation_memory.append(activations)
return (activations[i] for i in self.output_node_ixs)
def train(self, reporter, tset, error_precision, learning_epsilon, learning_acceleration, max_iterations, training_strategy):
"""
Attempt to train the network according to scenarios specified in tset, iterating the scenarios until the
network is trained or max_iterations is reached. Report the states of all nodes after each pattern is run.
reporter: a class containing a concrete implementation of the method i_report_pattern (top of file).
tset: an array of tuples containing an input vector and a dictionary of expected outputs. The collection
. represents one training epoch; each element one training pattern.
. (e.g.): [((0,0),{2:0}), ((0,1),{2:1}), ((1,0),{2:1}), ((1,1),{2:0})]
error_precision: error epsilon is calculated 10^-error_precision. The network is trained when the
. epoch error <= error epsilon.
. (e.g.): error_precision = 3, error_epsilon = 0.001
learning_epsilon: (learning rate) the rate at which the network learns. Too low a value will cause the
. network to learn too slowly and not train within the max_iterations. Too high a value could cause
. the network to continuously overshoot the target and fail to learn.
learning_acceleration: similar to learning rate, this provides some momentum to learning as previous
. deltas multiplied by this value are added to the deltas of the current training session. Too high
. a value here could cause a numeric overflow, while too low can make learning too slow.
training_strategy: A value from TrainingStrategy - indicates when to modify the weights (after a pattern
. is complete or after an epoch).
"""
def run_pattern(V, T):
"""
Execute one training pattern in the training set. Calculate and save learning values.
Report state of all nodes. Train if specified by training_strategy. Return error.
V: input vector
T: expected output(s) of system.
"""
from collections import defaultdict
self.accept_input(V)
activations = self.activation_memory[-1] # these are the outputs from this run.
delta_error = 0
# calculate change rate for output nodes
change_rate = defaultdict(lambda:0)
for node_index in self.output_node_ixs:
a = activations[node_index]
diff = T[node_index] - a
delta_error += diff
# Literature concerning single-layer perceptrons seem to only use the delta-rule (T[i] - a) in the
# training equation, where-as (T[i]-a) * a * (1 - a) comes up with multi-layer perceptrons. I
# observe that the latter works well with single-layers as well. However, using a step-function
# guarantees the latter is always 0. (e.g.): a * (1 - a) == 0 for a in [0,1].
change_rate[node_index] = diff if a in (0,1) else diff * a * (1 - a)
self.nodes[node_index].remember_deltas(learning_epsilon, change_rate[node_index], learning_acceleration)
# calculate change rate for hidden nodes (dr for output nodes required)
for node_index in sorted(self.output_paths.keys(), reverse=True):
if node_index not in self.nodes: continue ## Must be a raw input node.
path = self.output_paths[node_index]
a = activations[node_index]
change_rate[node_index] = sum(change_rate[step["tonode"]] * self.nodes[step["tonode"]].weights[step["atposition"]] for step in path) * a * (1 - a)
self.nodes[node_index].remember_deltas(learning_epsilon, change_rate[node_index], learning_acceleration)
reporter.report_pattern(activations, T, change_rate,
{ni:n.weights+[n.theta] for ni,n in self.nodes.items()},
# perm memory is a tuple of weights, theta
# index -1 points to most recent memory.
{ni:n.perm_delta_memory[-1][0]+[n.perm_delta_memory[-1][1]] for ni,n in self.nodes.items()})
if training_strategy == TrainingStrategy.PATTERN:
for node in self.nodes.values():
node.apply_deltas()
return (delta_error * delta_error)
EPSILON = math.pow(10, -error_precision)
epochs = []
epoch = 0
trained = False
while not trained and epoch < max_iterations:
error = 0
reporter.start_epoch()
for V, T in tset:
error += run_pattern(V, T)
reporter.end_epoch(error)
trained = round(math.fabs(error), error_precision) <= EPSILON
if training_strategy == TrainingStrategy.EPOCH and not trained:
for node in self.nodes.values():
node.apply_deltas()
epoch += 1
return trained
</code></pre>
<p><strong>perceptron_test.py</strong></p>
<pre><code>import math
import itertools
import perceptron
class Reporter(object):
"""
The purpose of this class is to capture values from an ANN throughout the course
of training, and then display those values in a tabular report. The display is
dynamically generated based on the network's configuration, which is specified
explicitly during initialization.
At least one call to start_epoch is required before reporting any data can be
reported. The assumption is that each epoch will be marked with matching calls
to start_epoch and end_epoch, so that report data can be grouped by epoch and
the Error Function per epoch can be reported.
Assume that the activation threshold theta is part of the sum function and
behaves as a weight with an internal input value (typically 1).
Terms:
epoch - one training cycle
activation - the output of a particular node (note raw input nodes have the
. same output as input)
pattern - one set of inputs and expected outputs. An epoch typically consists
. of multiple patterns.
Fields displayed:
. * Activations from all nodes including raw input nodes.
. * Expected activations from all output nodes (training values).
. * Activation deltas for output nodes.
. * The weights for all nodes in the network when the activations were calculated.
. * The deltas to be applied to each weight during the training cycle.
(e.g.):
. Given a network with 2 raw inputs and 1 output node (as in a simple AND gate),
. the report would contain this header (the line is broken here, but not in the
. report):
. A0 | A1 | A2 | T2 | Dr2 | W20 | W21 |
. Th2 | dW20 | dW21 | dTh2 |
. * Note A0, A1 are the raw inputs. Observe that fields match along the node
. * indexes (Dr2 is derived from T2 and A2 and applied to the change values
. * for W2* and Th2).
.
. Given a network with 2 raw inputs, 1 hidden node, and 1 output node (as in an XOR
. gate), the report would contain this header (the line is broken here, but not in
. the report):
. A0 | A1 | A2 | A3 | T3 | Dr2 | Dr4 | W20 |
. W21 | Th2 | W40 | W41 | W42 | Th4 | dW20 | dW21 |
. dTh2 | dW40 | dW41 | dW42 | dTh4 |
"""
HFMT = "{:^11s}|"
FMT = "{:^11,.3g}|"
def __init__(self, inputnodes, weightconfig, outputnodes):
"""
inputnodes:
. Iterable of node indices for values input into the network. Used to calculate
. the number of fields expected in all reported values. (e.g.): [0,1]
weightconfig:
. Dictionary of nodes by index with number of weights as a value. Do not account
. for the threshold theta in this number as it will be accounted for implicitly.
. This configuration is used to calculate the number of fields expected in all
. reported values.
. (e.g.): {2:2, 3:2, 4:2} for a system with 2 inputs, 2 hidden nodes with 2
. weights each, and a single output node with 2 weights.
. In this case, the hidden nodes 2&3 are the only inputs
. into the output node, 4.
outputnodes:
. Iterable of node indices. Used only to create
. Training field headers (e.g.): [node_index,...]
"""
fields = ['A{}'.format(ni) for ni in range(len(inputnodes) + len(weightconfig))]
fields += ['T{}'.format(ni) for ni in outputnodes]
fields += ['CR{}'.format(ni) for ni,nw in weightconfig.items()]
fields += ['Th{}'.format(li) if nwi==nw else 'W{}{}'.format(li,nwi) for li,nw in weightconfig.items() for nwi in range(nw+1)]
fields += ['dTh{}'.format(li) if nwi==nw else 'dW{}{}'.format(li,nwi) for li,nw in weightconfig.items() for nwi in range(nw+1)]
self.epochs = []
self.fields = fields
self.numfields = len(self.fields)
def start_epoch(self):
"""
Mark the beginning of a training cycle. This is useful for grouping
purposes and for reporting the Error Function value for the cycle.
"""
self.epochs.append({"error":0,"patterns":[]})
def end_epoch(self, error):
"""
Mark the end of a training cycle.
"""
epoch = self.epochs[-1]
epoch["error"] = error
def report_pattern(self, activations, training_values, change_rates, weights, dweights):
"""
Concrete implementation of perceptron.i_report_pattern
NOTE: The length of each array in weights and dweights is one more than the
weightconfig specified in initialization. This extra element is, of course, the
activation threshold, theta.
"""
# flatten all fields into a 1-D array for ease of later printing.
pattern = [activations[k] for k in sorted(activations.keys())]
pattern += [training_values[k] for k in sorted(training_values.keys())]
pattern += [change_rates[k] for k in sorted(change_rates.keys())]
pattern += list(itertools.chain.from_iterable(weights.values()))
pattern += list(itertools.chain.from_iterable(dweights.values()))
self.epochs[-1]["patterns"].append(pattern)
def decipher_training_result(self, trained):
""" Convert tri-state value (boo nullable boolean) trained to single-character identifier. """
if trained is None: return "E"
return "T" if trained else "F"
def write_summary(self, scenario, trained, f):
"""
Display the results of a training session in a fixed-column format.
scenario: Tuple identifies name of scenario and all parameters:
. (scenario name, transform function, training strategy, learning epsilon, learning acceleration)
trained: boolean value indicating whether the ANN was successfully trained.
f: an open file for text writing
Output fields:
. Name - 17 chrs
. Transform Function - 24 chrs
. Training Strategy - 3 chrs (P - train after each pattern, E - train after each epoch)
. Learning Epsilon - 7 chrs
. Learning Acceleration - 7 chrs
. Training Results - 3 chrs (E - error, F - failed, T - trained)
. Number of epochs trained.
"""
name,tf,tp,le,la = scenario
f.write('{:17s}{:24s}{:3s}{:<7,.4g}{:<7,.4g}{:3s}{:<4,d}\n'.format(name, tf.__name__, tp, le, la, self.decipher_training_result(trained), len(self.epochs)))
def write_details(self, scenario, trained, f):
"""
Display the results of a training session with tabular detail.
scenario: Tuple identifies name of scenario and all parameters:
. (scenario name, transform function, training strategy, learning epsilon, learning acceleration)
trained: boolean value indicating whether the ANN was successfully trained.
f: an open file for text writing
"""
def print_header():
f.write(''.join(self.HFMT.format(k) for k in (self.fields)))
f.write('\n')
def print_separator():
f.write(''.join(["-----------+" for i in range(self.numfields)]))
f.write('\n')
name,tf,tp,le,la = scenario
f.write('{}[TF:{}, T:{}, LE:{:g}, LA:{:g}] {} in {} epochs.\n'.format(name,
tf.__name__,
tp, le, la,
self.decipher_training_result(trained),
len(self.epochs)))
print_header()
print_separator()
for epoch in self.epochs:
# All fields were flattened into a 1-D array for ease here.
f.write('\n'.join(''.join(self.FMT.format(k) for k in pattern) for pattern in epoch["patterns"]))
f.write('Error: {:.9f}\n'.format(epoch["error"]))
print_separator()
def transform_step(x): return 1 if x >= 0 else 0
def transform_sigmoid_abs(x): return x / (1 + math.fabs(x))
def transform_sigmoid_exp(x): return 1 / (1 + math.exp(-x))
def truncate_file(fname):
with open(fname, "w+") as f:
pass
BITS = (0,1)
TSET = { # Training Sets
"OR":[((x,y),{2:int(x or y)}) for x in BITS for y in BITS],
"AND":[((x,y),{2:int(x and y)}) for x in BITS for y in BITS],
"NOT":[((x,),{1:int(not x)}) for x in BITS],
"XOR":[((x,y),{3:int(x^y)}) for x in BITS for y in BITS]
}
MAX_ITERATIONS = 256
ERROR_PRECISION = 3
PERMS = [(le, la, tf, ts)
for tf in [transform_step, transform_sigmoid_abs, transform_sigmoid_exp]
for ts in [perceptron.TrainingStrategy.PATTERN, perceptron.TrainingStrategy.EPOCH]
for le in [0.25, 0.5, 0.75]
for la in [0.75, 0.995, 1.0, 1.005, 1.1]]
SCENARIOS = [("OR", TSET["OR"], [((0,1),(2,))], le, la, tf, ts) for le, la, tf, ts in PERMS] + [
("AND", TSET["AND"], [((0,1),(2,))], le, la, tf, ts) for le, la, tf, ts in PERMS] + [
("NOT", TSET["NOT"], [((0,),(1,))], le, la, tf, ts) for le, la, tf, ts in PERMS] + [
("XOR", TSET["XOR"], [((0,1),(2,)),((0,1,2),(3,))], le, la, tf, ts) for le, la, tf, ts in PERMS]
LOG_FILE = r"c:\temp\perceptron_error.log"
SUMMARY_FILE = r"c:\temp\perceptron_summary.txt"
DETAILS_FILE = r"c:\temp\perceptron_details.txt"
WRITE_DETAILS = True
truncate_file(LOG_FILE)
truncate_file(SUMMARY_FILE)
truncate_file(DETAILS_FILE)
for name, tset, pconfig, epsilon, acceleration, xform_function, training_strategy in SCENARIOS:
p = perceptron.FFPerceptron(xform_function, pconfig)
reporter = Reporter(p.input_node_ixs, {ni:len(n.weights) for ni,n in p.nodes.items()}, p.output_node_ixs)
try:
trained = p.train(reporter, tset, ERROR_PRECISION, epsilon, acceleration, MAX_ITERATIONS, training_strategy)
except Exception as err:
with open(LOG_FILE, "a+") as flog:
flog.write('{}\n{}\n'.format(str(p),repr(err)))
trained = None
#raise
scenario = (name, xform_function, training_strategy, epsilon, acceleration)
with open(SUMMARY_FILE, "a") as fsummary:
reporter.write_summary(scenario, trained, fsummary)
if WRITE_DETAILS:
with open(DETAILS_FILE, "a") as fdetails:
reporter.write_details(scenario, trained, fdetails)
</code></pre>
|
[] |
[
{
"body": "<p>Consider breaknig out the training logic from the network so there can be instances of non-trainable perceptrons. Presumably in this case there would be a mechanism for saving and loading weight data (by using pickle for example), which becomes easier without the pollution of the training data.</p>\n\n<p>The \"enum\" TrainingStrategy is for controlling program flow. There should be a more organic way of doing this - \"train_pattern(...)\" and \"train_epoch(...)\".</p>\n\n<p>The training sets include node index with the expected output. This prevents using the same training set on different configurations - or at least - severely complicates it. It would be more flexible for expected outputs to be a tuple that the training logic can interpret based on network configuration.</p>\n\n<p>Here is example using a graph to implement node connections (doesn't include training logic):</p>\n\n<pre><code>class Node:\n def __init__(self, node_index):\n self.node_index = node_index\n self.output_map = []\n\n def map_output(self, node, position):\n self.output_map.append((node,position))\n\n def __repr__(self):\n return '{}:{}'.format(self.node_index, repr(self.output_map))\n\nclass InputNode(Node):\n def __init__(self, node_index):\n Node.__init__(self, node_index)\n self.input = 0\n\n def evaluate(self):\n a = self.input\n for node,position in self.output_map:\n node.input[position] = a\n\nclass Neuron(Node):\n def __init__(self, node_index, num_inputs):\n Node.__init__(self, node_index)\n self.weights = [0] * (num_inputs + 1)\n self.input = [0] * (num_inputs) + [1]\n self.u = 0\n self.a = 0\n\n def evaluate(self):\n def g(v, w):\n return sum(v[i] * w[i] for i in range(len(v)))\n\n def f(u):\n return 0 if u < 0 else 1\n\n self.u = g(self.input, self.weights)\n self.a = f(self.u)\n\n for node,position in self.output_map:\n node.input[position] = self.a\n\ndef configure(config):\n in_idx, map_output = config\n nodes = [InputNode(idx) for idx in in_idx]\n for node_index, mapping in map_output:\n node = Neuron(node_index, len(mapping))\n nodes.append(node)\n for position, in_node_index in enumerate(mapping):\n nodes[in_node_index].map_output(node, position)\n return nodes\n\ndef test(nodes, tset):\n for i,t in tset:\n nodes[0].input = i[0]\n nodes[1].input = i[1]\n\n for n in nodes:\n n.evaluate()\n\n output_nodes = [node for node in nodes if len(node.output_map) == 0]\n first = min(node.node_index for node in output_nodes)\n for node in output_nodes:\n node_index = node.node_index\n tn = t[node_index - first]\n print ('V{} = {}, A{} = {}, T{} = {}, D{} = {}'.format(node_index, node.input, node_index, node.a, node_index, tn, node_index, tn - node.a))\n\ntmnodes = configure(((0,1,2,3),[(4,(0,1,2,3)),(5,(0,1,2,3)),(6,(4,5)),(7,(4,5)),(8,(4,5)),(9,(4,5))]))\ntnodes = configure(((0,1),[(2,(0,1)),(3,(0,2,1))]))\n\nmnodes = [InputNode(0), InputNode(1), Neuron(2, 2), Neuron(3, 3)]\nmnodes[0].map_output(mnodes[2], 0)\nmnodes[0].map_output(mnodes[3], 0)\nmnodes[1].map_output(mnodes[2], 1)\nmnodes[1].map_output(mnodes[3], 2)\nmnodes[2].map_output(mnodes[3], 1)\n\nprint (tnodes)\nprint (mnodes)\nprint (tmnodes)\n\nBITS = (0,1)\nTSET_XOR = [((x,y),((x^y),)) for x in BITS for y in BITS]\nTSET_ENCODER = [((w,x,y,z),(w,x,y,z)) for w in BITS for x in BITS for y in BITS for z in BITS]\n\ntest(tnodes, TSET_XOR)\ntest(mnodes, TSET_XOR)\ntest(tmnodes, TSET_ENCODER)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T12:33:02.887",
"Id": "18243",
"ParentId": "18164",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T22:00:26.067",
"Id": "18164",
"Score": "4",
"Tags": [
"python",
"ai",
"neural-network"
],
"Title": "Academic implementation of artificial neural network"
}
|
18164
|
<p>This has taken me months to complete. From what little testing I have done, it seems to work. Let me know what I can do to spruce things up. I can't wait to start learning some more advanced concepts that would have made this easier. </p>
<pre><code># Imports, lots of imports,
from random import randint
from random import choice
import pprint
from sys import exit
#Setting some core stats
wins = 0
times_trained = 0
gold = randint(1, 3) + 2
# Start Streen
def start_screen():
print"""
\t\tTHE LEGEND OF DOOBIEUS ARENA
\t\tProgrammed poorly by Ray Weiss
"""
next()
#Some Quips for the barracks
def gladiator_quips():
q = []
q.append('A warrior grunts, "A sword is more versatile than other weapons."')
q.append('A rogue remarks "Oi I heard that training improves your primary skills."')
q.append('A wench stats "At least you can fight for your freedom %s."' % character_class)
q.append('A drunk sings you a song of the legend of Doobieus poorly.')
q.append('A guard remarks how his polearm gets more lucky hits')
q.append('A slave mentions that maces pack a heavy punch.')
q.append('A barkeep laments "I need a vacation."')
q.append('A one eyed gladiator recalls his youth before slavers killed his family.')
q.append('A child remarks how training can affect abilities.')
quips = choice(q)
print quips
#nice little function that brings up the next page prompt
def next():
raw_input("Press Enter To Continue...")
# Barracks need to restrict training after training. Also need to
# add training restrictions.
def barracks():
print """
Welcome to the barracks %s
^^^^ ^^^^^^^^^^^^^^^^
>----<|arena|training|>
~ MMM ~ <|shop<| _ | __ |>
{ } mmm ~~~ [~~~] { } mmm ~~~ <| <|{}\ | /{}\ |>
{ } |||D _______ [~~~] { } |||D _______ <| -||- | -||- |>
{ } ||| <uuuuuuu> [~~~] { } ||| <uuuuuuu> <| ||| | || |>
-------------------------------------------------------------------------
There are several other gladiators moving around, you may 'talk' to them.
You can take a look at your 'stats'
You can 'shop' for new weapons.
You may enroll in skill 'training' nearby.
You may face your next opponent in the 'arena'.
You may give up on your quest for freedom & 'quit'
Current HP: %s Gold Pieces: %s
""" % (name, current_hp, gold)
answer = raw_input(":> ")
if "talk" in answer:
gladiator_quips()
next()
barracks()
elif "stats" in answer:
pp = pprint.PrettyPrinter(indent=30)
pp.pprint(character_sheet)
next()
barracks()
elif "training" in answer:
if times_trained == 0:
train()
else:
print "The training center is now closed."
next()
barracks()
elif "arena" in answer:
combat_engine()
elif "quit" in answer:
print "You are now a slave forever. Goodbye %s." % name
exit(0)
elif "shop" in answer:
if wins == 0:
print "The shop is closed for the day, you must win your first fight"
next()
barracks()
elif wins == 1:
buy_weapon(level_one_weapons)
elif wins == 2:
buy_weapon(level_two_weapons)
elif wins == 3:
buy_weapon(level_three_weapons)
elif wins == 4:
buy_weapon(level_four_weapons)
else:
print "Ray left a bug somewhere. Ballz."
exit(0)
else:
print "I didn't understand %s, please try again." % answer
next()
barracks()
#training code
def train_code(stat):
global gold, times_trained, str, dex, con
if check != 1:
gold = gold - 7
character_sheet.remove(character_sheet[9])
character_sheet.insert(9, "You have %d gold pieces." % gold)
if stat == str:
times_trained = 1
str = str + 1
character_sheet.remove(character_sheet[3])
character_sheet.insert(3, "Strength: %s" % str)
print "You feel stronger and return to the barracks as training closes."
next()
barracks()
elif stat == dex:
times_trained = 1
dex = dex + 1
character_sheet.remove(character_sheet[4])
character_sheet.insert(3, "Dexterity: %s" % dex)
print "You feel dexterous and return to the barracks as training closes."
next()
barracks()
elif stat == con:
times_trained = 1
con = con + 1
character_sheet.remove(character_sheet[5])
character_sheet.insert(3, "Constiution: %s" % con)
print "You feel hardier and return to the barracks as training closes."
next()
barracks()
else:
print "Ray left a stupid bug somewhere"
else:
times_trained = 1
gold = gold - 7
character_sheet.remove(character_sheet[9])
character_sheet.insert(9, "You have %s gold pieces." % gold)
print "You feel like the training was useless. You return to the barracks as training closes."
next()
barracks()
# training room
def train():
global gold, str, dex, con, check
print """
Welcome %s to the training center.
You currently have %d gold pieces.
You may enroll in one class before each battle.
Keep in mind, there is a chance you will fail to learn anything.
Training costs 7 gold pieces.
You may train 'str', 'dex', or 'con'
Type 'quit' if you wish to return to the barracks.
Which stat do you wish to train?
""" % (name, gold)
answer = raw_input(":> ")
check = randint(1, 6)
if 'str' in answer and gold >= 7:
train_code(str)
elif 'dex' in answer and gold >= 7:
train_code(dex)
elif 'con' in answer and gold >= 7:
train_code(con)
elif 'quit' in answer:
print "You leave the training area."
next()
barracks()
else:
print """"You either dont have enough gold (%s gp,) or you typed in an error (%s)
""" % (gold, answer)
next()
train()
#dice
def d20():
return randint(1, 20)
def d100():
return randint(1, 100)
def d6():
return randint(1, 6)
# Doing Stuff for weapons and the shopkeeper. #################################
def level_zero_price():
"""Generates the price for level one weapons"""
return randint(1, 3)
def level_one_price():
"""Generates the price for level two weapons"""
return randint(3, 6)
def level_two_price():
"""Generates the price for level three weapons"""
return randint(6, 9)
def level_three_price():
"""Generates the price for level four weapons"""
return randint(9, 12)
def level_four_price():
"Generates the price for level four weapons"""
return randint(12, 15)
#weapon inventory code
def weapon_code(weapons):
global current_weapon
weapon_choice = raw_input(":> ")
if weapons[0] in weapon_choice and gold >= sword_price:
gold_math(sword_price)
if wins != 0:
current_weapon = weapons[0]
inventory(weapons[0])
character_sheet.remove(character_sheet[10])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
else:
current_weapon = weapons[0]
inventory(weapons[0])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
elif weapons[1] in weapon_choice and gold >= blunt_price:
gold_math(blunt_price)
if wins != 0:
current_weapon = weapons[1]
inventory(weapons[1])
character_sheet.remove(character_sheet[10])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
else:
current_weapon = weapons[1]
inventory(weapons[1])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
elif weapons[2] in weapon_choice and gold >= agile_price:
gold_math(agile_price)
if wins != 0:
current_weapon = weapons[2]
inventory(weapons[2])
character_sheet.remove(character_sheet[10])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
else:
current_weapon = weapons[2]
inventory(weapons[2])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
elif "quit" in weapon_choice and wins != 0:
barracks()
elif "quit" in weapon_choice and wins == 0:
print "You must buy a weapon first before you can go to the barracks."
next()
buy_weapon(level_zero_weapons)
else:
print "Either you dont have enough money, or I dont know what %s means" % weapon_choice
next()
buy_weapon(weapons)
# price display
def prices(weapons):
print """
Please type in the weapon you want to buy.
%s, price: %d gold pieces
%s, price: %d gold pieces
%s, price: %d gold pieces.
""" % (weapons[0], sword_price, weapons[1], blunt_price,weapons[2],
agile_price)
# gold buying
def gold_math(weapon_price):
global gold
character_sheet.remove(character_sheet[9])
gold = gold - weapon_price
character_sheet.insert(9, "You have %s gold pieces." % gold)
### Shop / buy weapons room ###############
def buy_weapon(weapons):
global gold, sword_price, blunt_price, agile_price, current_weapon
"""big bit of code that allows you to buy a weapons from a weapon list.
The function acts a little differently after level zero weapons"""
global current_weapon
if weapons == level_zero_weapons:
sword_price = level_zero_price()
blunt_price = level_zero_price()
agile_price = level_zero_price()
prices(level_zero_weapons)
weapon_code(level_zero_weapons)
raw_input("""
Your current weapon is now a %s. Press Enter To Continue
""" % current_weapon)
elif weapons == level_one_weapons:
sword_price = level_one_price()
blunt_price = level_one_price()
agile_price = level_one_price()
prices(level_one_weapons)
weapon_code(level_one_weapons)
raw_input("""
Your current weapon is now a %s. Press Enter To Continue
""" % current_weapon)
elif weapons == level_two_weapons:
sword_price = level_two_price()
blunt_price = level_two_price()
agile_price = level_two_price()
prices(level_two_weapons)
weapon_code(level_two_weapons)
raw_input("""
Your current weapon is now a %s. Press Enter To Continue
""" % current_weapon)
elif weapons == level_three_weapons:
sword_price = level_three_price()
blunt_price = level_three_price()
agile_price = level_three_price()
prices(level_three_weapons)
weapon_code(level_three_weapons)
raw_input("""
Your current weapon is now a %s. Press Enter To Continue
""" % current_weapon)
elif weapons == level_four_weapons:
sword_price = level_four_price()
blunt_price = level_four_price()
agile_price = level_four_price()
prices(level_four_weapons)
weapon_code(level_four_weapons)
raw_input("""
Your current weapon is now a %s. Press Enter To Continue
""" % current_weapon)
else:
print"~~~There is a bug somwhere, forgot to assign (weapons)\n\n\n"
def inventory(current_weapon):
"""Attaches modifiers to secondary stats according to current weapon """
global mod_dmg, mod_crit
if current_weapon == level_zero_weapons[0]:
mod_dmg = dmg
mod_crit = crit
elif current_weapon == level_zero_weapons[1]:
mod_dmg = dmg + 1
mod_crit = crit
elif current_weapon == level_zero_weapons[2]:
mod_dmg = dmg
mod_crit = crit + 3
elif current_weapon == level_one_weapons[0]:
mod_dmg = dmg + 1
mod_crit = crit + 3
elif current_weapon == level_one_weapons[1]:
mod_dmg = dmg + 2
mod_crit = crit
elif current_weapon == level_one_weapons[2]:
mod_dmg = dmg
mod_crit = crit + 5
elif current_weapon == level_two_weapons[0]:
mod_dmg = dmg + 1
mod_crit = crit + 5
elif current_weapon == level_two_weapons[1]:
mod_dmg = dmg + 3
mod_crit = crit
elif current_weapon == level_two_weapons[2]:
mod_dmg = dmg
mod_dmg = crit + 6
elif current_weapon == level_three_weapons[0]:
mod_dmg = dmg + 2
mod_crit = crit + 5
elif current_weapon == level_three_weapons[1]:
mod_dmg = dmg + 4
mod_crit = crit + 3
elif current_weapon == level_three_weapons[2]:
mod_dmg = dmg + 1
mod_crit = + 8
elif current_weapon == level_four_weapons[0]:
mod_dmg = dmg + 3
mod_crit = crit + 7
elif current_weapon == level_four_weapons[1]:
mod_dmg = dmg + 5
mod_crit = crit + 5
elif current_weapon == level_four_weapons[2]:
mod_dmg = dmg + 2
mod_crit = crit + 10
else:
print"There is a bug, ray forgot a weapon or typed shit wrong."
exit(0)
#End Of Buying / Inventory functions ##########################################
#function for monster damage
def monster_dice(a, b):
return randint(a, b)
#Function for monster stats
def monster_stats(a, b, c, d):
global monster_current_hp, monster_crit, monster_dmg, monster_to_hit
monster_current_hp = a
monster_crit = b
monster_dmg = monster_dice(1, c)
monster_to_hit = d
# Chooses a random monster and sets stats
def choose_monster(monster_list):
global monster, description
if monster_list == level_zero_monsters:
monster = choice(level_zero_monsters)
if monster == 'wolf':
monster_stats(4, 5, 6, 12)
description = "A small and angry dog like creature."
elif monster == 'goblin':
monster_stats(5, 7, 5, 10)
description = "A tiny miserable creature that lives to eat shit."
elif monster == 'kobold':
monster_stats(6, 10, 4, 9)
description = "A small humaniod lizard, very sneaky and annoying"
else:
print "Bug in choose monster level 0"
exit(0)
elif monster_list == level_one_monsters:
monster = choice(level_one_monsters)
if monster == 'orc':
monster_stats(6, 8, 6, 10)
description = "A human sized horrid creature, smells awful."
elif monster == 'gnoll':
monster_stats(7, 10, 8, 12)
description = "A large humanoid dog, they can cackle for hours."
elif monster == 'giant ant':
monster_stats(8, 7, 7, 11)
description = "A large and terrifying insect, it makes clicking noises."
else:
print "Bug in choose monster level 1"
exit(0)
elif monster_list == level_two_monsters:
monster = choice(level_two_monsters)
if monster == 'wight':
monster_stats(9, 10, 10, 12)
description = "A powerful undead warrior, terrifying in size."
elif monster == 'komodo dragon':
monster_stats(7, 12, 8, 10)
description = "A deadly man sized lizard, very sharp teeth."
elif monster == 'ogre':
monster_stats(10, 5, 12, 11)
description = "A Big and strong stupid ogre."
else:
print "Bug in monster level 2"
elif monster_list == level_three_monsters:
monster = choice(level_three_monsters)
if monster == 'troll':
monster_stats(12, 7, 12, 11)
elif monster == 'owlbear':
monster_stats(10, 12, 11, 10)
elif monster == 'dark priest':
monster_stats(9, 13, 10, 9)
else:
print "Bug in monster level 3"
elif monster_list == level_four_monsters:
monster = choice(level_four_monsters)
if monster == 'dark wizard':
monster_stats(11, 15, 12, 9)
elif monster == 'hydra':
monster_stats(12, 14, 15, 10)
elif monster == 'stone golem':
monster_stats(15, 13, 13, 11)
else:
print "Problem with monster level 4"
else:
print "Ray left diddnt assign a correct choose monster(argv)"
exit(0)
#Check to hit and applies damage / crit + damage use p for player and m for monster
def hit_check(x):
global current_hp, monster_current_hp, to_hit, monster_to_hit, crit
global monster_crit, dmg, monster, monster_dmg
if x == 'p':
if d20() >= to_hit and d100() <= crit:
monster_current_hp = monster_current_hp - dmg * 3
print "You critically wounded the %s!" % monster
next()
elif d20() >= to_hit and d100() > crit:
monster_current_hp = monster_current_hp - dmg
print "You wounded the %s!" % monster
next()
else:
print "You missed the %s." % monster
next()
elif x == 'm':
if d20() >= monster_to_hit and d100() <= monster_crit:
current_hp = current_hp - monster_dmg * 3
print "The %s critically wounded %s!" % (monster, name)
next()
elif d20() >= to_hit and d100() > crit:
current_hp = current_hp - monster_dmg
print "The %s wounded %s." % (monster, name)
next()
else:
print "The %s missed %s." % (monster, name)
next()
else:
print "Ray diddnt correctly assign a hit check"
exit(0)
# Combat engine / prompt
def combat_engine():
global current_hp, monster_current_hp, wins, gold, hit_points, p, m, wins
"""Will choose a monster, and then allow the player to fight monster"""
global current_hp, monster_current_hp, prompt
if wins == 0:
choose_monster(level_zero_monsters)
elif wins == 1:
choose_monster(level_one_monsters)
elif wins == 2:
choose_monster(level_two_monsters)
elif wins == 3:
choose_monster(level_three_monsters)
elif wins == 4:
choose_monster(level_four_monsters)
else:
print "bug in choosing monsters over wins"
exit(0)
print """
Welcome %s to the Arena
Today you will be fighting a %s
Description of monster: %s
""" % (name, monster, description)
next()
running = True
while running:
if current_hp > 0 and monster_current_hp > 0:
prompt = raw_input("Type 'a' to attack, 'q' for quit HP: %d :> " % current_hp)
if prompt == 'a':
hit_check('p')
hit_check('m')
elif current_hp <= 0:
print "You were killed by the %s, better luck next time." % monster
exit()
elif monster_current_hp <= 0:
print "You defeated the %s! Great Job!" % monster
next()
if wins == 0:
gold_earned = d6() + 2
elif wins == 1:
gold_earned = d6() + d6() + 2
elif wins == 2:
gold_earned = d6() + d6() + 4
elif wins == 3:
gold_earned = d6() + d6() + 5
elif wins == 4:
gold_earned = d6() + d6() + 6
else:
print "There is a bug you have wins than allowed"
exit(0)
if wins != 5:
gold = gold + gold_earned
character_sheet.remove(character_sheet[9])
character_sheet.insert(9, "You have %s gold pieces." % gold)
print "You win %d gold, you have %d gold total." % (gold_earned,
gold)
times_trained = 0
wins = wins + 1
hit_points = hit_points + d6()
current_hp = hit_points
character_sheet.remove(character_sheet[8])
character_sheet.insert(8, "Hit Points: %d/%d" % (hit_points, current_hp))
print "You feel hardier. You make your way back to the barracks."
next()
barracks()
else:
you_win()
else:
print "Bug in combat engine"
exit(0)
def you_win():
print """
YOU WIN!
CONGRATULATIONS!
THANKS FOR PLAYING!
"""
# Monster List
level_zero_monsters = ['wolf', 'goblin', 'kobold']
level_one_monsters = ['orc', 'gnoll', 'giant ant',]
level_two_monsters = ['wight', 'komodo dragon', 'ogre']
level_three_monsters = ['troll', 'owlbear', 'dark priest']
level_four_monsters = ['dark wizard', 'hydra', 'stone golem']
# Weapon lists
level_zero_weapons = ['short sword', 'club', 'dagger']
level_one_weapons = ['sword', 'mace', 'rapier']
level_two_weapons = ['long sword', 'morningstar', 'trident']
level_three_weapons = ['claymore', 'flail', 'sycthe']
level_four_weapons = ['bastard sword', 'dragon bone', 'crystal halbred']
def roll_3d6():
"""This rolls 3D6, and returns the sum."""
return randint(1, 6) + randint(1, 6) + randint(1, 6)
def character_gen():
"""Creates A character and also can call character sheet"""
global name, str, dex, con, hit_points, dmg, crit, character_class
global gender, damage_print, current_hp, character_sheet, to_hit
character_sheet = []
name = raw_input("Please tell me your name brave soul. :> ")
print "\n\t\tLets now randomly generate brave gladiator %s." % name
str = roll_3d6()
if str > 12:
dmg = randint(1, 6) + 1
damage_print = "1D6 + 1"
else:
dmg = randint(1, 6)
damage_print = "1D6"
dex = roll_3d6()
if dex >= 13:
crit = 15
to_hit = 9
elif dex >= 9 and dex <=12:
crit = 10
to_hit = 10
else:
crit = 10
to_hit = 11
con = roll_3d6()
if con > 14:
hit_points = 8
current_hp = hit_points
else:
hit_points = 6
current_hp = hit_points
if str >= dex:
character_class = "Warrior"
else:
character_class = "Rogue"
random_gender = randint(1, 2)
if random_gender == 1:
gender = "Male"
else:
gender = "Female"
character_sheet.append("Name: %s:" % name)
character_sheet.append("Gender: %s" % gender)
character_sheet.append("Character Class: %s" % character_class)
character_sheet.append("Strength: %s" % str)
character_sheet.append("Dexterity: %s" % dex)
character_sheet.append("Constitution: %s" % con)
character_sheet.append("Damage %s" % damage_print)
character_sheet.append("Crit Chance {}%".format(crit))
character_sheet.append("Hit Points: %s/%s" % (hit_points, current_hp))
character_sheet.append("You have %s gold pieces." % gold)
pp = pprint.PrettyPrinter(indent=30)
pp.pprint(character_sheet)
raw_input("Please Press Enter To Buy A Weapon")
buy_weapon(level_zero_weapons)
#main
start_screen()
character_gen()
</code></pre>
|
[] |
[
{
"body": "<p>The good news - you'll have to totally rewrite your game. But first...</p>\n\n<p><code>gladiator_quips</code> - quips would be better as a global constant, considering that it never changes, although one entry will need to be added after the character is generated.</p>\n\n<p>The training code contains a serious error - you pass the <em>value</em> of the statistic to be changed, but you don't allow the possibility that there may be more than one with the same value. Instead, pass the name of the stat.</p>\n\n<pre><code>if 'str' in answer and gold >= 7:\n train_code('str')\n</code></pre>\n\n<p>and then use it as follows:</p>\n\n<pre><code>if stat == 'str':\n</code></pre>\n\n<p><code>train</code> includes <code>global</code> for variables that it doesn't use. I shall refer you to <a href=\"https://codereview.stackexchange.com/questions/16304/how-can-i-condense-this-bit-of-code\">Console weapons shop for adventure game</a> -\ntry to avoid (restrict) the use of <code>global</code>. It also doesn't <code>global</code> something it should (<code>check</code>). Remember - <code>global</code> is tricky.</p>\n\n<p>Also wrt <code>check</code>, it's only used in two places, one function to set it, the other to use it - there's no need for it at all, since it doesn't really serve any purpose - just do</p>\n\n<pre><code>`if random.randint( 1, 6 ) != 1:`\n</code></pre>\n\n<p>on the one occasion it's used, and eliminate one global!</p>\n\n<p><code>train</code> can also be simplified (and improved) a bit by noticing that part of each condition is repeated:</p>\n\n<pre><code>def train():\n print TRAIN_STATEMENT % (name, gold)\n answer = raw_input(\":> \")\n if 'quit' in answer:\n print \"You leave the training area.\"\n next()\n barracks()\n elif gold >= 7:\n if 'str' in answer:\n train_code(\"str\")\n elif 'dex' in answer:\n train_code(\"dex\")\n elif 'con' in answer:\n train_code(\"con\")\n else: \n print \"\"\"\"You typed in an error (%s)\"\"\" % (answer)\n next()\n train()\n else:\n print \"\"\"\"You don't have enough gold (%d gp,)\"\"\" % (gold)\n next()\n train()\n</code></pre>\n\n<p>I'm going to suggest (again!) isolating the use of a global to a specific function, so you have functions similar to:</p>\n\n<pre><code>def change_gold( delta_gold ):\n global gold\n gold = gold + delta_gold\n character_sheet[9] = \"You have %s gold pieces.\" % gold\n</code></pre>\n\n<p>There's no need to remove and reinsert list elements, just change them.\nAlso, <code>change_strength</code>, <code>change_dexterity</code>, <code>change_weapon</code> etc. There is a very good reason for this, which you will learn as soon as you learn about classes. I note that you already have a function called <code>gold_math</code> which does the above function, but there are two problems:\n 1) the parameter is called weapon_price, which doesn't make sense if that's not the function is used for - it could also be used for training costs, thereby reducing duplication.\n 2) the name itself doesn't say what the function does, 'math' doesn't mean anything.</p>\n\n<p><code>times_trained</code> is also badly used - it's used as a boolean, so use <code>True</code> and <code>False</code> for its values, and rename it to something like has_been_trained, since that's what it represents.</p>\n\n<p>I'm uncertain whether <code>hit_check</code> does what you want - do you really intend to call <code>d20</code> etc multiple times, or do you intend only once?</p>\n\n<pre><code>this_to_hit = d20()\nthis_crit = d100()\nif x == 'p':\n if this_to_hit >= to_hit and this_crit <= crit:\n monster_current_hp = monster_current_hp - dmg * 3\n print \"You critically wounded the %s!\" % monster\n next()\n elif this_to_hit >= to_hit: # this_crit > crit is implied\n monster_current_hp = monster_current_hp - dmg\n print \"You wounded the %s!\" % monster\n next()\n else: \n print \"You missed the %s.\" % monster\n next()\n#etc\n</code></pre>\n\n<p>There is (a lot) more to say, but it's now time to say something about the structure of the program, since you've now learnt about <code>while</code> loops.</p>\n\n<p>If you follow the function calls that your program is making, they go something like:</p>\n\n<pre><code>start_screen()\ncharacter_gen()\n buy_weapon()\n weapon_code()\n barracks()\n train()\n train_code()\n barracks()\n etc\n</code></pre>\n\n<p>where every function call chains off to another call, never returning - you can see this by the stack trace that occurs when, for example, you're killed.\nThis was OK while you didn't know about loops, but this can (and should!) now be improved. What you need to do is adapt your code such that it follows the following structure:</p>\n\n<pre><code>start_screen()\ncharacter_gen()\nbuy_weapon()\nwhile True:\n action = barracks()\n if action == \"talk\":\n print gladiator_quips()\n elif action == \"training\":\n train()\n elif action == \"stats\":\n stats()\n elif action == \"arena\":\n alive = combat_engine()\n if ( not alive ) or beaten_all_arena:\n break\n elif action == \"quit\"\n break\ndo_closing_action()\n</code></pre>\n\n<p>It will take some time, but it will be well worth it for your project.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T00:12:43.753",
"Id": "29067",
"Score": "0",
"body": "Thank you for your detailed answer @Glenn Rogers! I shall have some fun going over this for the next few days!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T23:28:24.640",
"Id": "18227",
"ParentId": "18167",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "18227",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-02T23:08:45.733",
"Id": "18167",
"Score": "6",
"Tags": [
"python",
"game",
"dice",
"role-playing-game"
],
"Title": "LPTHW exercise 36 game"
}
|
18167
|
<p>Below is my written code to determine if, based on the hypotenuse, a Pythagorean triple is possible, and what are the lengths. I was wondering if there is a more efficient way of doing so.</p>
<pre><code>#Victor C
#Determines if a right triangle with user inputted hypotenuse is capable of being a Pythagorean Triple
import math
triplecheck = True
while True:
hypotenuse = int(input("Please enter the hypotentuse:")) #Smallest hypotenuse which results in a pythagorean triple is 5.
if hypotenuse > 4:
break
c = csqr = hypotenuse**2 #sets two variables to be equivalent to c^^2. c is to be modified to shorten factoring, csqr as a reference to set a value
if c % 2 != 0: #even, odd check of value c, to create an integer when dividing by half.
c = (c+1)//2
else:
c = c//2
for b in range(1,c+1): #let b^^2 = b || b is equal to each iteration of factors of c^^2, a is set to be remainder of c^^2 minus length b.
a = csqr-b
if (math.sqrt(a))%1 == 0 and (math.sqrt(b))%1 == 0: #if squareroots of a and b are both equal to 0, they are integers, therefore fulfilling conditions
tripleprompt = "You have a Pythagorean Triple, with the lengths of "+str(int(math.sqrt(b)))+", "+str(int(math.sqrt(a)))+" and "+str(hypotenuse)
print(tripleprompt)
triplecheck = False
if triplecheck == True:
print("Sorry, your hypotenuse does not make a Pythagorean Triple.")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T01:13:01.627",
"Id": "28988",
"Score": "0",
"body": "please format your code in a readable format"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T01:24:04.630",
"Id": "28989",
"Score": "0",
"body": "(`) Change `if math.sqrt(a)%1 == 0` to `if not math.sqrt(a)%1`. (2) Put everything inside `while True` in a function and call that function inside `while True`. Otherwise, this is a better fit for codereview.SE"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T02:25:39.657",
"Id": "62805",
"Score": "0",
"body": "There is a significantly more mathematically advanced method called the Hermite-Serret method; you can find details at http://math.stackexchange.com/questions/5877/efficiently-finding-two-squares-which-sum-to-a-prime"
}
] |
[
{
"body": "<p>First, let's write this with a little style, and go from there:</p>\n\n<pre><code>import math\n\ndef is_triple(hypotenuse):\n \"\"\"return (a, b, c) if Pythagrean Triple, else None\"\"\"\n if hypotenuse < 4:\n return None\n\n c = hypotenuse ** 2\n\n for a in xrange(3, hypotenuse):\n b = math.sqrt(c - (a ** 2)) \n if b == int(b):\n return a, int(b), hypotenuse\n\n return None\n</code></pre>\n\n<p>Now, I'll walk you through it, line by line, and show you how I got this.</p>\n\n<p>I have no idea if this is more efficient, but it is written in better style, which is an important thing to consider.</p>\n\n<pre><code>import math\n</code></pre>\n\n<p>Always put your imports at the top of the module.</p>\n\n<pre><code>def is_triple(hypotenuse):\n</code></pre>\n\n<p>Here is say 'let's <strong>def</strong><em>ine</em> some functionality, and encase a repeatable, reusable pattern of logic within it. The rest of my answer revolves around this, and is a major first step to programming in Python.</p>\n\n<pre><code>def is_triple(hypotenuse):\n \"\"\"return (a, b, c) if Pythagrean Triple, else None\"\"\"\n</code></pre>\n\n<p>Note the <code>\"\"\"</code> triple quotes. That's your <a href=\"http://www.python.org/dev/peps/pep-0257/#one-line-docstrings\">docstring</a>, something that reminds you later what you were thinking when you wrote something. Try to keep it under 65 characters or so.</p>\n\n<pre><code>if hypotenuse < 4:\n return None\n</code></pre>\n\n<p>In the first line, <code>def is_triple(hypotenuse):</code>, I ask the user to give me something; a variable that I can use later. If I later <em>call</em> this function in the manner <code>is_triple(5)</code>, I am basically telling the function that my hypotenuse is 5, and for the rest of the time here, we'll call it <code>hypotenuse</code>. </p>\n\n<pre><code>c = hypotenuse ** 2\n</code></pre>\n\n<p>That's really all you need for this calculation right now.</p>\n\n<pre><code>for a in xrange(3, hypotenuse):\n b = math.sqrt(c - (a ** 2)) \n if b == int(b):\n return a, int(b), hypotenuse\n</code></pre>\n\n<p><code>for a in xrange(3, hypotenuse)</code> basically says <em>for each whole number between 3 and the hypotenuse, do the stuff I'm about to write</em>.</p>\n\n<p>Following the previous example,</p>\n\n<pre><code>>>> range(3, hypotenuse) #hypotenuse is == 5\n[3, 4]\n</code></pre>\n\n<p>Nevermind that I call <code>xrange()</code>, it functions the same as far as we're concerned here, and importantly, is more efficient.</p>\n\n<p>So now that we've made a <strong>loop</strong>, <code>a</code> will act as though it is <em>each number in [3, 4]</em>, so first, it's 3:</p>\n\n<pre><code>b = math.sqrt(c - (a ** 2))\nb = math.sqrt(25 - (3 ** 2))\nb = math.sqrt(25 - (9))\nb = math.sqrt(16)\nb = 4.0\n</code></pre>\n\n<p>Just like you would on pencil and paper. Notice I put a <code>.0</code> after, the four. That's important here:</p>\n\n<pre><code>if b == int(b):\n</code></pre>\n\n<p>Basically, <code>int</code> puts the number <code>b</code> from a decimal to a whole number. We just check if they're the same.</p>\n\n<pre><code>>>> int(4.0)\n4\n>>> int(4.0) == 4\nTrue\n</code></pre>\n\n<p>So, if the number we got for <code>b</code> is the same as the whole number representation of <code>b</code>, do the next part:</p>\n\n<pre><code>return a, int(b), hypotenuse\n</code></pre>\n\n<p>Which maps a value back to whatever you called as an assignment for the function call.</p>\n\n<pre><code>>>> values = is_triple(5)\n>>> values\n(3, 4, 5)\n>>> wrong = is_triple(7)\n>>> wrong\n>>> #it didn't print anything, because it gave me back None\n</code></pre>\n\n<p>Finally, at the bottom:</p>\n\n<pre><code>return None\n</code></pre>\n\n<p>That's the last thing to catch, in case nothing else happens. Obviously, if you've gone through this loop and you haven't gotten an answer? Well, looks like you don't have a match. Give back a <code>None</code> to denote this.</p>\n\n<p>To see this work in action, try this:</p>\n\n<pre><code>>>> import pprint\n>>> pprint.pprint([{x: is_triple(x)} for x in xrange(101)])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-11T01:52:40.290",
"Id": "29424",
"Score": "0",
"body": "Thank you to everybody that replied with an answer. I am in grade 11, and have been getting into coding from september. I appreciate all the feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T02:21:22.607",
"Id": "18172",
"ParentId": "18171",
"Score": "9"
}
},
{
"body": "<p>I'm going to point to one thing that is a potential big source of confusion. Imagine you come back to this a year from now, and you've seen some error on one line of this code. You want to fix that line of code, and you're in a rush. You're not going to read the whole function if you can get away with it. Quick - what do <code>a</code>, <code>b,</code> and<code>c</code> mean?</p>\n\n<p>Usually <code>a</code>, <code>b</code>, and <code>c</code> are the lengths of the sides. Here you've got them as the square of the lengths of the sides. That's going to confuse you when you try to revisit this code.</p>\n\n<p>You've even got some of that confusion going on already - you've set </p>\n\n<p><code>c=csqr</code></p>\n\n<p>So you're thinking of <code>c</code> as something, and at the same time you're thinking of that same thing as being csquared. You've got two different concepts of <code>c</code>. Similarly, your comment <code>#let b^^2 = b</code>. That's just asking for trouble. In your comments you clearly think of <code>b</code> as something different from what the code thinks of it as. So somewhere else where your comments might refer to <code>b</code> - is that the same <code>b</code> you meant in your comment earlier, or is it the version of <code>b</code> now in the code? (and note it's really <code>b**2</code>, not <code>b^^2</code>). You don't get any bonus for just having 3 one letter variable names.</p>\n\n<p>If you want to do your calculations in the squared variable, use <code>asq</code>, <code>bsq</code>, and <code>csq</code>. (and consider writing out <code>aSquared</code> etc to make it clear).</p>\n\n<p>I wrote my own version without looking at the other solution, but in Python there should be one and only one obvious way to do things (though you may have to be Dutch to see it). The solutions are almost identical:</p>\n\n<pre><code>def test(hypotenuse):\n factor = 1\n while hypotenuse %2 == 0:\n factor *=2\n hypotenuse/= 2\n\n hsq = hypotenuse**2\n\n success = False\n for b in xrange(1,hypotenuse):\n a = math.sqrt(hsq-b**2)\n if a == int(a):\n return sorted([factor*int(a), factor*b, factor*hypotenuse])\n return (None,None,None)\n\n\n\nhypotenuse = int(input(\"Please enter the hypotentuse:\"))\n\n(a,b,c) = test(hypotenuse)\n\nif a is None:\n print \"failure, utter, utter failure\"\nelse:\n print a, b, c\n</code></pre>\n\n<p>The only real difference is that I took advantage of the fact that one can prove it we have a pythagorean triple with an even hypotenuse, then dividing by 2 yields a new pythagorean triple.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T16:21:02.307",
"Id": "135292",
"Score": "0",
"body": "\"Quick - what do a, b, and c mean?\" +50"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T02:10:41.947",
"Id": "73791",
"ParentId": "18171",
"Score": "3"
}
},
{
"body": "<p><strong>A simple optimisation</strong></p>\n\n<p>Riding on <a href=\"https://codereview.stackexchange.com/a/18172/9452\">Droogan's very good answer</a>, you can add a simple optimisation. Indeed, instead of doing <code>for a in xrange(3, hypotenuse):</code>, you can try a smaller range.</p>\n\n<p>Also, I took this chance to remove the <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"nofollow noreferrer\">(premature?)</a> optimisation about <code>if hypotenuse < 4</code>.</p>\n\n<p>The point is to limit yourself to solutions with <code>a <= b</code> (which is what Droogan is doing anyway because this is the first solution you'd find).</p>\n\n<p>Then, you can dive into simple maths and get :</p>\n\n<pre><code>def is_triple(hypotenuse):\n \"\"\"return (a, b, c) if Pythagrean Triple, else None\"\"\"\n # We have :\n # 0 < a < c and 0 < b < c (egality corresponds to uninteresting solutions).\n # If a = b, 2 * a^2 = c^2, impossible in |N\n # Therefore a != b.\n # We can assume a < b\n # 0 < a^2 < c^2/2 < b^2 < c^2\n c_sqr = hypotenuse ** 2\n for a in xrange(1, int(math.ceil(hypotenuse / math.sqrt(2)))):\n b = math.sqrt(c_sqr - (a ** 2))\n if b == int(b):\n return a, int(b), hypotenuse\n return None\n</code></pre>\n\n<p>One can easily check that :</p>\n\n<ul>\n<li><p>you have the same results</p></li>\n<li><p>it is faster.</p></li>\n</ul>\n\n<p><strong>A more subtle optimisation</strong></p>\n\n<p>This is inspired by <a href=\"https://codereview.stackexchange.com/a/73791/9452\">Joel's solution</a>. He noticed that somehow, factors of 2 can be removed out of the problem and used as a multiplying factor when we find the solution. In fact, it is even better than this as other prime numbers have the same property.</p>\n\n<p>Indeed, according to the <a href=\"http://en.wikipedia.org/wiki/Pythagorean_triple#Elementary_properties_of_primitive_Pythagorean_triples\" rel=\"nofollow noreferrer\">properties of <em>primitive</em> Pythagorean triples</a> :</p>\n\n<blockquote>\n <p>All prime factors of c are primes of the form 4n + 1.</p>\n</blockquote>\n\n<p>Therefore, we can go through the prime factors of the hypothenuse and if they can't be written <code>4*n + 1</code>, then they must be part of the multiplicative factor.</p>\n\n<p>Thus, one can write something like :</p>\n\n<pre><code>def prime_factors(n):\n \"\"\"Yields prime factors of a positive number.\"\"\"\n assert n > 0\n d = 2\n while d * d <= n:\n while n % d == 0:\n n //= d\n yield d\n d += 1\n if n > 1: # to avoid 1 as a factor\n assert d <= n\n yield n\n\ndef is_triple(hypotenuse):\n \"\"\"return (a, b, c) if Pythagrean Triple, else None\"\"\"\n # We have :\n # 0 < a < c and 0 < b < c.\n # If a = b, 2 * a^2 = c^2, impossible in |N\n # Therefore a != b.\n # We can assume a < b\n # 0 < a^2 < c^2/2 < b^2 < c^2\n if hypotenuse:\n factor = 1\n for prime, power in collections.Counter(prime_factors(hypotenuse)).iteritems():\n if prime % 4 != 1:\n factor *= prime ** power\n c = hypotenuse / factor\n c_sqr = c ** 2\n for a in xrange(1, int(math.ceil(c / math.sqrt(2)))):\n b = math.sqrt(c_sqr - (a ** 2))\n if b == int(b):\n return factor * a, factor * int(b), factor * c\n</code></pre>\n\n<p>This seems to be at least 10 times faster than the code I started with.</p>\n\n<p><strong>Faster faster</strong></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple\" rel=\"nofollow noreferrer\">According to Wikipedia</a>:</p>\n\n<blockquote>\n <p>Euclid's formula<a href=\"https://codereview.stackexchange.com/a/18172/9452\">1</a> is a fundamental formula for generating Pythagorean triples given an arbitrary pair of positive integers m and n with m > n. The formula states that the integers</p>\n \n <p>a = m^2 - n^2 , b = 2mn , c = m^2 + n^2 </p>\n \n <p>form a Pythagorean triple. The triple generated by Euclid's formula is primitive if and only if m and n are coprime and m − n is odd. If both m and n are odd, then a, b, and c will be even, and so the triple will not be primitive; however, dividing a, b, and c by 2 will yield a primitive triple if m and n are coprime.<a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"nofollow noreferrer\">2</a></p>\n</blockquote>\n\n<p>Thus, you can write a faster code (O(sqrt(c)) instead of O(c)). Please note that it can give different results than the original code. Also, this optimisation makes the factorising trick somewhat less impressive and you get easily get rid of it.</p>\n\n<pre><code>def is_triple(hypotenuse):\n \"\"\"return (a, b, c) if Pythagrean Triple, else None\"\"\"\n # We have :\n # a = m^2 - n^2, b = 2mn , c = m^2 + n^2 with m > n > 0\n # c >= 2 * n^2\n # 0 < n <= sqrt(c/2)\n if hypotenuse:\n factor = 1\n for prime, power in collections.Counter(prime_factors(hypotenuse)).iteritems():\n if prime % 4 != 1:\n factor *= prime ** power\n c = hypotenuse / factor\n c_sqr = c ** 2\n for n in xrange(1, int(math.ceil(math.sqrt(c/2)))):\n m = math.sqrt(c - n ** 2)\n if m == int(m):\n m = int(m)\n return factor*(m*m - n*n), 2*m*n*factor, hypotenuse\n return None\n</code></pre>\n\n<p>This seems to be 100 times faster than your code for values up to 20000 (and the bigger the values your consider, the more dramatic the improvement is).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T14:29:21.960",
"Id": "134167",
"Score": "0",
"body": "Merry WinterBash! Have a HAT!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T14:27:34.827",
"Id": "73830",
"ParentId": "18171",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18172",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T01:09:31.610",
"Id": "18171",
"Score": "11",
"Tags": [
"python",
"performance",
"mathematics"
],
"Title": "Determining Pythagorean triples based on the hypotenuse"
}
|
18171
|
<p>This code snippet is intended for validating the value of a property of an object. The min and max range is supplied as an .xml file like Nhibernate .hbm files. Since the data-type of the property is also read from the .xml file, we can only know the type of the property at run-time.</p>
<p>Is there any better way of improving the code in C# and .NET 2.0?</p>
<pre><code>public static void ValidateMinMax(Property prop, Object value)
{
Type type = Type.GetType(prop.TypeName);
Object minValue = PropertyDataExtractor.GetMinValue(prop);
Object maxValue = PropertyDataExtractor.GetMaxValue(prop);
Object actualVaue = null;
bool minValueOk = false;
bool maxValueOk = false;
if (minValue != null)
{
switch (type.Name)
{
case "Boolean":
break;
case "SByte":
actualVaue = Convert.ToSByte(value);
if (actualVaue != null)
{
minValueOk = ((sbyte)minValue) <= ((sbyte)actualVaue);
}
else
{
minValue = true;
}
break;
case "Byte":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
minValueOk = ((byte)minValue) <= ((byte)actualVaue);
}
else
{
minValue = true;
}
break;
case "Byte[]":
break;
case "DateTime":
actualVaue = Convert.ToDateTime(value);
if (actualVaue != null)
{
minValueOk = ((DateTime)minValue).Date <= ((DateTime)actualVaue).Date;
}
else
{
minValue = true;
}
break;
case "Int16":
actualVaue = Convert.ToInt16(value);
if (actualVaue != null)
{
minValueOk = ((short)minValue) <= ((Int16)actualVaue);
}
else
{
minValue = true;
}
break;
case "Int32":
actualVaue = Convert.ToInt32(value);
if (actualVaue != null)
{
minValueOk = ((int)minValue) <= ((Int32)actualVaue);
}
else
{
minValue = true;
}
break;
case "Int64":
actualVaue = Convert.ToInt64(value);
if (actualVaue != null)
{
minValueOk = ((long)minValue) <= ((Int64)actualVaue);
}
else
{
minValue = true;
}
break;
case "Single":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
minValueOk = ((float)minValue) <= ((Single)actualVaue);
}
else
{
minValue = true;
}
break;
case "Double":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
minValueOk = ((double)minValue) <= ((double)actualVaue);
}
else
{
minValue = true;
}
break;
case "Decimal":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
minValueOk = ((decimal)minValue) <= ((decimal)actualVaue);
}
else
{
minValue = true;
}
break;
case "Char":
actualVaue = Convert.ToChar(value);
if (actualVaue != null)
{
minValueOk = ((char)minValue) <= ((char)actualVaue);
}
else
{
minValue = true;
}
break;
case "String":
actualVaue = Convert.ToString(value);
if (actualVaue != null)
{
minValueOk = ((int)minValue) <= ((string)actualVaue).Length;
}
else
{
minValue = true;
}
break;
case "Guid":
break;
}
}
if (maxValue != null)
{
switch (type.Name)
{
case "Boolean":
break;
case "SByte":
actualVaue = Convert.ToSByte(value);
if (actualVaue != null)
{
maxValueOk = ((sbyte)minValue) >= ((sbyte)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Byte":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
maxValueOk = ((byte)minValue) >= ((byte)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Byte[]":
break;
case "DateTime":
actualVaue = Convert.ToDateTime(value);
if (actualVaue != null)
{
maxValueOk = ((DateTime)maxValue).Date >= ((DateTime)actualVaue).Date;
}
else
{
maxValue = true;
}
break;
case "Int16":
actualVaue = Convert.ToInt16(value);
if (actualVaue != null)
{
maxValueOk = ((short)minValue) >= ((Int16)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Int32":
actualVaue = Convert.ToInt32(value);
if (actualVaue != null)
{
maxValueOk = ((int)minValue) >= ((Int32)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Int64":
actualVaue = Convert.ToInt64(value);
if (actualVaue != null)
{
maxValueOk = ((long)minValue) >= ((Int64)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Single":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
maxValueOk = ((float)minValue) >= ((Single)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Double":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
maxValueOk = ((double)minValue) >= ((double)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Decimal":
actualVaue = Convert.ToByte(value);
if (actualVaue != null)
{
maxValueOk = ((decimal)minValue) >= ((decimal)actualVaue);
}
else
{
maxValue = true;
}
break;
case "Char":
actualVaue = Convert.ToChar(value);
if (actualVaue != null)
{
maxValueOk = ((char)minValue) >= ((char)actualVaue);
}
else
{
maxValue = true;
}
break;
case "String":
actualVaue = Convert.ToString(value);
if (actualVaue != null)
{
maxValueOk = ((int)maxValue) >= ((string)actualVaue).Length;
}
else
{
maxValue = true;
}
break;
case "Guid":
break;
}
}
if (minValue == null)
{
minValueOk = true;
}
if (maxValue == null)
{
maxValueOk = true;
}
if (!(minValueOk && maxValueOk))
{
throw new Exception("Property : " + PropertyDataExtractor.GetName(prop) +".\nMessage : "+ PropertyDataExtractor.GetMinValueErrorMessage(prop) + " " + PropertyDataExtractor.GetMaxValueErrorMessage(prop));
}
else if (!minValueOk)
{
throw new Exception("Property : " + PropertyDataExtractor.GetName(prop) + ".\nMessage : " + PropertyDataExtractor.GetMinValueErrorMessage(prop));
}
else if (!maxValueOk)
{
throw new Exception("Property : " + PropertyDataExtractor.GetName(prop) + ".\nMessage : " + PropertyDataExtractor.GetMaxValueErrorMessage(prop));
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T07:30:02.830",
"Id": "28992",
"Score": "0",
"body": "You seem to duplicate your switch statements twice. Perhaps using polymorphism might be an approach worth considering here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T17:11:31.423",
"Id": "28999",
"Score": "0",
"body": "What is the value of the parameter \"value\"? You are using Convert, which is used to convert from one type to another. But it looks like it should either be the type you need to deal with already, or a string/xml fragment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T17:12:12.333",
"Id": "29000",
"Score": "1",
"body": "There's a lot of logical errors in that code... normally we would prefer actual working code."
}
] |
[
{
"body": "<p>Here's an attempt to use a bit of polymorphism. While doing this some things I did note were:</p>\n\n<p>1) The if statement at the end means that !minValueOk and !maxValueOk are irrelevant and will never be true. The first if should be !minValueOk and !maxValueOk rather than !(minValueOk && maxValueOk.</p>\n\n<p>2) Assuming value is never null for some of the checks you do not need to double check for null. For example <code>Convert.ToSByte(value)</code> should always return a non-null value assuming it will convert.</p>\n\n<p>3) I typically try not to through Exception where I can. Perhaps a custom exception might be worthwhile here.</p>\n\n<p>Here's my attempt at a refactor. I'm not 100% sure it will compile but it should at least give an idea:</p>\n\n<p>The new Validate method:</p>\n\n<pre><code>public static void ValidateMinMax(object prop, Object value)\n{\n PropertyValidator validator = new PropertyValidatorFactory().CreateValidator(prop.GetType().Name);\n\n if (!validator.Validate(prop, value))\n {\n if (!isMinValid && !isMaxValid)\n {\n message = PropertyDataExtractor.GetMinValueErrorMessage(prop) + \" \" + PropertyDataExtractor.GetMaxValueErrorMessage(prop);\n }\n else if (!isMinValid)\n {\n message = PropertyDataExtractor.GetMinValueErrorMessage(prop);\n }\n else\n {\n message = PropertyDataExtractor.GetMaxValueErrorMessage(prop);\n }\n\n return InvalidPropertyRangeException(\"Property : \" + PropertyDataExtractor.GetName(prop) + \".\\nMessage : \" + message);\n }\n}\n</code></pre>\n\n<p>Using a custom exception and a Factory class to create the objects that will do the validation</p>\n\n<pre><code>class InvalidPropertyRangeException : Exception\n{\n public InvalidPropertyRangeException(string message) : base(message)\n {\n }\n}\n\nclass PropertyValidatorFactory\n{\n public PropertyValidator CreateValidator(string typeName)\n {\n switch (typeName)\n {\n case \"Boolean\":\n return new EmptyValidator();\n case \"String\":\n return new StringValidator();\n // Rest of validators go here\n default:\n throw new NotImplementedException(string.Format(\"Type {0} is not supported\", typeName));\n }\n }\n}\n</code></pre>\n\n<p>The base validator class</p>\n\n<pre><code> abstract class PropertyValidator\n {\n public bool IsMinValid { get; private set; }\n public bool IsMaxValid { get; private set; }\n\n protected Object OriginalValue { get; private set; }\n\n protected PropertyValidator()\n {\n IsMinValid = IsMaxValid = true;\n }\n\n public bool Validate(object prop, Object value)\n {\n if(value == null)\n {\n throw new NullReferenceException(\"Value supplied for validation is null\");\n }\n\n Object minValue = PropertyDataExtractor.GetMinValue(prop);\n Object maxValue = PropertyDataExtractor.GetMaxValue(prop);\n\n if(minValue == null && maxValue == null)\n {\n return true;\n }\n\n OriginalValue = value;\n\n return IsValid(minValue, maxValue);\n }\n\n private bool IsValid(object minValue, object maxValue)\n {\n IsMinValid = ValidateMinimum(minValue);\n IsMaxValid = ValidateMaximum(maxValue);\n\n return IsMinValid && IsMaxValid;\n }\n\n protected abstract bool ValidateMinimum(object minValue);\n protected abstract bool ValidateMaximum(object maxValue);\n}\n</code></pre>\n\n<p>Examples of specific validator classes</p>\n\n<pre><code>class EmptyValidator : PropertyValidator\n{\n protected override bool ValidateMinimum(object minValue)\n {\n return true;\n }\n\n protected override bool ValidateMaximum(object maxValue)\n {\n return true;\n }\n}\n\nclass SbyteValidator : PropertyValidator\n{\n protected override bool ValidateMinimum(object minValue)\n {\n sbyte actualVaue = GetValue();\n\n return ((sbyte)minValue) <= actualVaue; \n }\n\n protected override bool ValidateMaximum(object maxValue)\n {\n sbyte actualVaue = GetValue();\n\n return ((sbyte)maxValue) >= actualVaue;\n }\n\n private sbyte GetValue()\n {\n return Convert.ToSByte(OriginalValue);\n }\n}\n\nclass StringValidator : PropertyValidator\n{\n protected override bool ValidateMinimum(object minValue)\n {\n string actualVaue = GetValue();\n if (actualVaue != null)\n {\n return ((int)minValue) <= actualVaue.Length;\n }\n\n return false;\n\n }\n\n protected override bool ValidateMaximum(object maxValue)\n {\n string actualVaue = GetValue();\n if (actualVaue != null)\n {\n return ((int)maxValue) >= actualVaue.Length;\n }\n\n return false;\n }\n\n private string GetValue()\n {\n return Convert.ToString(OriginalValue);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T08:50:56.177",
"Id": "18177",
"ParentId": "18175",
"Score": "3"
}
},
{
"body": "<p>This might be a good place to use the strategy pattern. By using the strategy pattern each method is independent of each other. It does end up being more code but it also separates the code but it honors the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Prinicipal</a>, and is much easier more flexible (easy to add additional types in the future), easier to understand and maintain, and easier to unit test. You can easily comparing additional types just by addings another class and registering it, instead of continuing to have to add items to a switch statement and creating one huge method.</p>\n\n<p>(Note this was written in NotePad so it probably is not perfect, but should give you a good idea).</p>\n\n<pre><code>public interface IValidateMinMax\n{\n bool ValidateMin(object minValue, object value);\n bool ValidateMax(object maxValue, object value);\n}\n\npublic static class Validator\n{\n public static bool ValidateMin<T>(T minValue, T value) where T : struct\n {\n return ((T)minValue) <= ((T)actualVaue);\n }\n public static bool ValidateMax<T>(T minValue, T value) where T : struct\n {\n return ((T)minValue) >= ((T)actualVaue);\n }\n}\n\npublic class ValidateMinMaxSByte : IValidateMinMax\n{\n public bool ValidateMin(object minValue, object value)\n {\n return Validator.ValidateMin<sbyte>(minValue, value);\n }\n\n public bool ValidateMax(object maxValue, object value)\n {\n return Validator.ValidateMax<sbyte>(minValue, value);\n }\n}\n\npublic class ValidateMinMaxByte : IValidateMinMax\n{\n public bool ValidateMin(object minValue, object value)\n {\n return Validator.ValidateMin<byte>(minValue, value);\n }\n\n public bool ValidateMax(object maxValue, object value)\n {\n return Validator.ValidateMax<byte>(minValue, value);\n }\n}\n\npublic class ValidateMinMaxDateTime : IValidateMinMax\n{\n public bool ValidateMin(object minValue, object value)\n {\n return Validator.ValidateMin<DateTime>(minValue, value);\n }\n\n public bool ValidateMax(object maxValue, object value)\n {\n return Validator.ValidateMax<DateTime>(minValue, value);\n }\n}\n\netc...\n</code></pre>\n\n<p>Then you would create the class which would register all the validators and call the appropriate one...</p>\n\n<pre><code>public class ValidatorMinMaxController\n{\npublic IDictionary<Type, IValidateMinMax> _validators = new Dictionary<Type, IValidateMinMax>();\npublic void Register()\n{\n _validators.Add(typeof(sbyte), new ValidateMinMaxSByte());\n _validators.Add(typeof(byte), new ValidateMinMaxByte());\n _validators.Add(typeof(DateTime), new ValidateMinMaxDateTime());\n etc...\n}\n\npublic void ValidateMinMax(Property prop, Object value)\n{\n Type type = Type.GetType(prop.TypeName);\n\n Object minValue = PropertyDataExtractor.GetMinValue(prop);\n Object maxValue = PropertyDataExtractor.GetMaxValue(prop);\n Object actualVaue = null;\n\n bool minValueOk = true;\n bool maxValueOk = true;\n\n IValidateMinMax instance;\n if (_validators.TryGetValue(type, out instance))\n {\n if (minValue != null)\n minValueOk = instance.ValidateMin(minValue, value);\n\n if (maxValue != null)\n maxValueOk = instance.ValidateMax(maxValue, value);\n }\n\n if (!(minValueOk && maxValueOk))\n {\n throw new Exception(\"Property : \" + PropertyDataExtractor.GetName(prop) +\".\\nMessage : \"+ PropertyDataExtractor.GetMinValueErrorMessage(prop) + \" \" + PropertyDataExtractor.GetMaxValueErrorMessage(prop));\n }\n else if (!minValueOk)\n {\n throw new Exception(\"Property : \" + PropertyDataExtractor.GetName(prop) + \".\\nMessage : \" + PropertyDataExtractor.GetMinValueErrorMessage(prop));\n }\n else if (!maxValueOk)\n {\n throw new Exception(\"Property : \" + PropertyDataExtractor.GetName(prop) + \".\\nMessage : \" + PropertyDataExtractor.GetMaxValueErrorMessage(prop));\n } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T19:34:38.553",
"Id": "29121",
"Score": "0",
"body": "Will the TryGetValue work on type even though it's a dictionary of strings? Would you not ant type.Name? I do like this pattern though. I've seen it used quite a bit in Microsoft MVC's framework."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T19:57:15.620",
"Id": "29122",
"Score": "0",
"body": "OH...looks like I got my types intermingled. You can either use the type or string. But I should code one or the other, not both :) Code has been fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T15:34:27.560",
"Id": "18252",
"ParentId": "18175",
"Score": "1"
}
},
{
"body": "<p>This is the snippet, add appropriate run-time checks and you're good to go:</p>\n\n<pre><code>public enum ErrorCode { Undef = -1, OK, TooSmall, TooBig, Err }\n\npublic class MyValidator\n{\n private static Type ValidateAs(Type type)\n {\n if (type.Equals(typeof(String)))\n return typeof (Int32);\n return type;\n }\n\n private static object TypeCheckConvertion(object obj)\n {\n if (obj is DateTime)\n return ((DateTime)obj).Date; \n if (obj is String)\n return (Int32) (obj.ToString().Length); \n return obj;\n }\n\n public static ErrorCode ValidateProperty<T>(T min, T max, T val) where T : IComparable\n {\n Console.WriteLine(String.Format(\"Is {0} in range [{1}-{2}] ?\", val, min, max));\n ErrorCode res = ErrorCode.OK; \n if (val.CompareTo(min) < 0)\n res |= ErrorCode.TooSmall;\n if (val.CompareTo(max) > 0)\n res |= ErrorCode.TooBig; \n return res;\n }\n\n public static ErrorCode ValidateMinMax(Property prop, Object obj)\n {\n var type = ValidateAs(Type.GetType(prop.TypeName));\n var minValue = TypeCheckConvertion(Property.GetMinValue(prop));\n var maxValue = TypeCheckConvertion(Property.GetMaxValue(prop));\n var val = TypeCheckConvertion(obj);\n\n return (ErrorCode) typeof(MyValidator).GetMethod(\"ValidateProperty\").MakeGenericMethod(\n new [] {type}).Invoke(null, new[] { minValue, maxValue, val });\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T02:07:41.437",
"Id": "29134",
"Score": "0",
"body": "Would this work also for the String validation, given that it is working off .Length?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T03:02:53.987",
"Id": "29136",
"Score": "0",
"body": "Perhaps you could expand on your post how your answer covers that scenario just to cover all bases?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T05:31:50.360",
"Id": "29139",
"Score": "0",
"body": "@dreza: I've edited the code to cover all mentioned cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T06:25:35.063",
"Id": "29140",
"Score": "0",
"body": "no prob. I was just interested to see where it was going given string had slightly different requirements. Interesting approach."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T01:57:10.693",
"Id": "18273",
"ParentId": "18175",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T06:13:37.517",
"Id": "18175",
"Score": "3",
"Tags": [
"c#",
"validation",
".net-2.0"
],
"Title": "Validating the value of a property of an object"
}
|
18175
|
<p>I am using the Jersey client to make API calls to validate a session. This call is being made at a rate of around 5 calls/second. I want to ensure that the client call doesn't have performance issues.</p>
<pre><code>String sessionUrlPrefix = Config.getInstance().getString(Helper.SESSION_SERVICE_URL);
String urlParameters = getParameters(sessionId);
String sessionURL = sessionUrlPrefix + "?" + urlParameters;
WebResource webResource = client.resource(sessionURL);
logger.debug("Session URL is " + sessionURL);
ClientResponse response = webResource
.accept(MediaType.TEXT_PLAIN_TYPE)
.type(MediaType.TEXT_PLAIN_TYPE)
.get(ClientResponse.class);
String responseStr = response.getEntity(String.class);
logger.debug("Response received is " + responseStr);
if (response.getStatus() != HttpStatus.OK.value())
{
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
// Could throw more appropriate HttpException.
}
return responseStr;
</code></pre>
|
[] |
[
{
"body": "<p>I'm not familiar with Jersey at all, so just two generic notes:</p>\n\n<ol>\n<li><p>You might want/could use <a href=\"https://stackoverflow.com/questions/7132967/is-the-head-response-faster-than-the-get\">HEAD instead GET which does not download the message body</a>.</p></li>\n<li><p>I don't know what is logging framework but if it's SLF4J you should use the <a href=\"https://en.wikipedia.org/wiki/SLF4J\" rel=\"nofollow noreferrer\"><code>{}</code> pattern instead of string concatenation</a>.</p>\n\n<pre><code>logger.debug(\"Session URL is {}\", sessionURL);\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T02:14:12.093",
"Id": "29072",
"Score": "0",
"body": "I am using log4j as my logging framework. I will look at using {} pattern if it is supported in log4j."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T02:14:48.487",
"Id": "29073",
"Score": "0",
"body": "I also need the Message body as it contains the email id of the user etc. which is required for further validation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T21:12:55.437",
"Id": "18226",
"ParentId": "18178",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T09:30:56.307",
"Id": "18178",
"Score": "2",
"Tags": [
"java",
"performance",
"jersey"
],
"Title": "Calling API (with rate of 5 calls/second) using Jersey client"
}
|
18178
|
<p>I've written this relatively simple class to help with managing arrays of anonymous objects in my scripts. </p>
<pre><code>/**
* AoHandler - accepts an array of objects or creates a new array
* @param {array} ao
*/
function AOHandler(ao)
{
this.ao = typeof ao === 'object' ? ao : [];
/**
* pluck()
* @param {object} search
* @param {boolean} retKey
*/
this.pluck = function (search, retKey)
{
for (i = 0; i < this.ao.length; i++ )
{
var tmpObj = this.ao[i];
if (tmpObj[search.key] == search.value)
{
return (retKey === true) ? i : tmpObj;
}
}
return false;
}
}
/**
* get()
* @param {object} search
* @return first matching object in ao array or false on failure
*/
AOHandler.prototype.get = function(search)
{
return this.pluck(search);
}
/**
* add()
* @param {object} pushObj
* @return false on failure
*/
AOHandler.prototype.add = function(pushObj)
{
return typeof pushObj === 'object' ? this.ao.push(pushObj) : false;
}
/**
* update()
* @param {object} search
* @param {object) updObj
* @param {boolean} merge
*/
AOHandler.prototype.update = function(search, updObj, merge)
{
var key = this.pluck(search, true);
if (merge === true && key !== false)
{
$.extend(this.ao[key], updObj);
return true;
}
else if (key !== false)
{
this.ao[key] = updObj;
return true;
}
return false;
}
/**
* remove()
* Finds the array item and removes it from the array
* @param {object} search
* @return first matching object in ao array
*/
AOHandler.prototype.remove = function(search)
{
var key = this.pluck(search, true);
return key !== false ? this.ao.splice(key, 1) : false;
}
</code></pre>
<p>Usage</p>
<pre><code>var aoArray = new AOHandler();
aoArray.add({
id : '50ef3ac',
name : 'example',
});
aoArray.add({
id : '50ef3ad',
name : 'A new object'
});
var searchFor = {
key : 'id',
value : '50ef3ad'
}
console.log(aoArray.get(searchFor);
</code></pre>
<p>I'm unhappy with the one jQuery call with $.extend() but this proved the easiest way to accomplish an object merge and I use jQuery quite predominantly in the majority of my projects. Despite that can anyone suggest a different way to do this?</p>
<p>While this works fine I know it's far from perfect as it's limited to one search term. My thought was to add in another loop within <code>pluck()</code> but I'd prefer to avoid doing that, my second thought was to map the object and perform the lookup once I'd found an object with the first property match. Again any suggestions on how I might accomplish this whilst keeping the script clean and fast I'd really appreciate it.</p>
<p>Any other suggestions welcome, thank you for taking a look. :)</p>
|
[] |
[
{
"body": "<p>To answer your specific concern about jQuery-dependence, the jQuery <code>extend</code> function is basically this:</p>\n\n<pre><code>var key;\nfor(key in objB) {\n objA[key] = objB[key]; // copy each value from objB into objA\n}\n</code></pre>\n\n<p>That's all there is to it really.</p>\n\n<p>However, I see a number of other things in your code that I think deserve attention.</p>\n\n<p><strong>1.</strong> Why define <code>pluck</code> insides the <code>AOHandler</code> constructor, and everything else in its prototype? Just wondering, since it's an unnecessary mixing of style. <code>pluck</code> can just as easily go in the prototype.</p>\n\n<p><strong>2.</strong> You're using <code>typeof ao === 'object'</code> when determining whether to use the argument passed to the constructor or not. Use <code>ao instanceof Array</code> instead. Almost everything in JS is \"typeof object\", but what you're looking for is an array and only an array. (I'd probably be strict about it too and throw an exception if a non-array argument is passed).</p>\n\n<p><strong>3.</strong> Your code doesn't seem to handle multiple identical values very well. Say I do this:</p>\n\n<pre><code>var ao = new AOHandler(),\n obj = { foo: \"bar\" },\n dup = $.extend({}, obj);\n\nao.add(obj);\nao.add(dup);\nao.add(obj);\n</code></pre>\n\n<p>Now there are three items in the AOHandler's list, two of which are the exact same object, and the third being a copy. None of you functions seem prepared to deal with such a situation. For instance, calling <code>update</code> would update the first item, which happens to also be the third item, so in fact 2 items get updated. However, the 2nd item (which has the same values, but isn't the same object) would be untouched. Could get pretty confusing.</p>\n\n<p><strong>4.</strong> Your function names seems a little off to me. <code>pluck</code> usually means to pick out values from each item in a list (i.e. a <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow\"><code>map</code></a>-like function); not the items themselves, and certainly not only the first one. <code>filter</code>, <code>select</code>, <code>find</code>, <code>search</code>, or <code>fetch</code> would all be better names, provided the function actually returns <em>all</em> the matches. <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow\"><code>filter</code></a> is indeed the name used for the native JS function (available in ECMA 5) that, well, filters an array and return the subset that matches a comparison function.</p>\n\n<p>However, your <code>pluck</code> can also return the index of an item. You call it <code>key</code>, but since <code>this.ao</code> is a normal numerically-indexed array <code>index</code> is the word to use. Key implies it won't change, but indices of an array <em>do</em> change when other items are added or removed.<br>\nAnyway, the usual JS name for a function that finds the index of a certain thing in an array is <code>indexOf</code>. So I'd suggest that you break the <code>pluck</code> function into an <code>indexOf</code> function and a <code>filter</code> function, since those are separate things.</p>\n\n<p>You could also make the case for <code>push</code> instead of <code>add</code>, since <code>AOHandler</code> is pretty much a wrapper around an array, and you <code>push</code> items to arrays. But <code>add</code> is plain English (and the same that Java uses for its <code>ArrayList</code>), so it's fine to use.</p>\n\n<p><code>update</code> is more problematic though, because it really does 2 (very) different things: Merge or replace. Merge will update the object in-place, so whereever else you have a reference to it, the updates will be visible. Replacing the object is a different story altogether. Again, I'd suggest 2 functions, since the effects are so very different, and the implementations have little in common.</p>\n\n<p>Here's me take:</p>\n\n<pre><code>function AOHandler(ao) {\n // if anything's passed, it must be an array\n if(typeof ao !== \"undefined\" && !(ao instanceof Array)) {\n throw new TypeError;\n }\n this.ao = ao || [];\n}\n\nAOHandler.prototype.indexOf = function (predicate, offset) {\n var i, l = this.ao.length;\n if(typeof predicate !== 'object') { throw new TypeError; } // type check\n offset = parseInt(offset, 10) || 0;\n // match native indexOf's handling of negative offset\n // see: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf\n offset = (offset < 0 ? l - offset : offset);\n offset = offset < 0 ? 0 : offset;\n for( i = offset ; i < l ; i++ ) {\n if(this.ao[i][predicate.key] === this.ao[i][predicate.value]) {\n return i;\n }\n }\n return -1;\n};\n\nAOHandler.prototype.filter = function (predicate) {\n var offset = 0, index, results = [];\n while((index = this.indexOf(predicate, offset)) !== -1) {\n results.push(this.ao[index]);\n offset = index + 1;\n }\n return results;\n};\n\n// This, by the way, is a pluck function\nAOHandler.prototype.pluck = function (key) {\n var i, l, results = [];\n for( i = 0, l = this.ao.length ; i < l ; i++ ) {\n results.push(this.ao[i][key]);\n }\n return results;\n};\n\nAOHandler.prototype.add = function (obj) {\n if(typeof obj !== 'object') { throw new TypeError; } // type check\n return this.ao.push(obj);\n};\n\nAOHandler.prototype.get = function (predicate) {\n var index = this.indexof(predicate);\n // return null - not false - if no obj is found\n return (index === -1 ? null : this.ao[index]);\n};\n\n// Simple jQuery-less merge function\nAOHandler.prototype.update = function (predicate, source) {\n var matches = this.filter(predicate), i, l, key;\n if(typeof source !== 'object') { throw new TypeError; } // type check\n for( i = 0, l = matches.length ; i < l ; i++ ) {\n for(key in source) {\n // it may be a good idea to do a source.hasOwnProperty[key] check here\n matches[i][key] = source[key];\n }\n }\n};\n\n// replace all matches\nAOHandler.prototype.replace = function (predicate, replacement) {\n var matches = this.filter(predicate), index, l, offset, key;\n if(typeof replacement !== 'object') { throw new TypeError; } // type check\n while((index = this.indexOf(predicate, offset)) !== -1) {\n this.ao[index] = replacement;\n offset = index + 1;\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T10:39:02.813",
"Id": "29036",
"Score": "0",
"body": "Thank you for such a detailed answer! Ok I've seen the light in terms of making this far more extensible than I had it. I've followed your outline and now having it working far better! I'm unsure what the use if any of the pluck function is? You just give it a property name and it returns all values that have the property name across all objects. What's the use of that? Either way many many thanks for the guidance! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T13:57:13.363",
"Id": "29048",
"Score": "0",
"body": "@DavidBarker You're welcome. I included the `pluck` function just to illustrate; I can't say it's necessarily useful in your particular case. However, like any `map`-like function it can be very useful. For instance if you have an array of, say, book chapters. Each has a title and some content, and you want to make a table of contents, so you do `chapters.pluck('title')` (pseudo code) to get list of chapter titles. Simple example, but hopefully one that makes sense. Again, it's just a specialized `map` function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T14:35:45.157",
"Id": "29049",
"Score": "0",
"body": "Yes that does make a lot of sense, thanks again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T20:52:00.407",
"Id": "18192",
"ParentId": "18179",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18192",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T11:26:49.967",
"Id": "18179",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Array of objects handler"
}
|
18179
|
<p>I would like to submit my enhanced concatenating function for your review. Originally, its method signature is:</p>
<pre><code>char *concat (const *char1, const *char2);
</code></pre>
<p>but after knowing that <a href="http://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Statements/Functions" rel="nofollow"><em>the calling code must supply all the arguments when it calls the function</em></a>, I modified the method signature to:</p>
<pre><code>char *enhconcat (const char *str1, int start_index1, int end_index1, const char *str2, int start_index2, int end_index2);
</code></pre>
<p>supplying the necessary positional arguments, so I think the code is more secured and adaptable to future changes.</p>
<p>Please suggest ways to improve this code and make it more secure.</p>
<pre><code>/* enhconcat.c: enhanced concat - for more secured concatenating */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
enhconcat (const char *str1, int start_index1, int end_index1,
const char *str2, int start_index2, int end_index2);
int main (void) {
const char *part1 = "Cuius est solum, ";
const char *part2 = "eius est usque ad coelum et ad inferos.";
printf ("%s\n", enhconcat (part1, 0, strlen (part1), part2, 0, strlen (part2)));
return (EXIT_SUCCESS);
}
char *
enhconcat (const char *str1, int start_index1, int end_index1,
const char *str2, int start_index2, int end_index2)
{
int m = end_index1 - start_index1;
int n = end_index2 - start_index2;
char *concatstr;
concatstr = malloc (m + n + 1);
if (!concatstr) {
printf ("Unable to allocate memory.\n");
exit (EXIT_FAILURE);
}
char *chrptr;
chrptr = concatstr; // store address of concatstr
for (int i = start_index1; i < m; i++) {
*chrptr = str1[i];
chrptr++;
}
for (int j = start_index2; j < n; j++) {
*chrptr = str2[j];
chrptr++;
}
*chrptr = '\0';
return concatstr;
} /* end of enhconcat() */
</code></pre>
|
[] |
[
{
"body": "<p>Chris, you have misunderstood the text quoted about the caller supplying all of the arguments. Your original prototype was okay. I imagine the text you read meant that if a function declares parameters a, b and c, then the caller must supply arguments (ie values of some sort) for all of those parameters. If there are 3 it must supply 3,, and of the correct types.</p>\n\n<p>Given the prototype you imposed upon yourself, your implementation was not bad, but you should learn to use the standard library functions. Your loops for copying characters are better implemented using <code>memcpy</code>.</p>\n\n<p>Also when you declare a variable, if you can it is often better to assign a value to it immediately, not on the next line. In C, this doesn't really matter, but in C++ doing this (assigning, or constructing immediately) is more efficient.</p>\n\n<p>Here is my version of your function with its original prototype. Note that instead of exiting on malloc failure, I print a message and return NULL. The caller must handle the failure. Note also that allocated memory must be freed. In a simple program like this, it is not important, as it will be freed on exit from the program. But remember that you have to do it normally.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic char *\nenhconcat (const char *str1, const char *str2)\n{\n size_t len1 = strlen(str1);\n size_t len2 = strlen(str2);\n\n char *concatstr = malloc(len1 + len2 + 1);\n if (!concatstr) {\n perror(\"malloc\");\n return NULL;\n }\n memcpy(concatstr, str1, len1);\n memcpy(concatstr + len1, str2, len2);\n concatstr[len1+len2] = '\\0';\n return concatstr;\n}\n\nint main (void) \n{\n const char *part1 = \"Cuius est solum, \";\n const char *part2 = \"eius est usque ad coelum et ad inferos.\";\n\n char *cat = enhconcat(part1, part2);\n if (cat != NULL) {\n printf (\"%s\\n\", cat);\n free(cat);\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:22:04.413",
"Id": "29008",
"Score": "0",
"body": "actually, I'm just starting to learn C programming, that's why I used only simple constructs. I'm not yet familiar on some functions you've provided like perror, memcpy, free. your implementation is actually clean, and i will up vote it. i'll be studying some of your provided functions so that i can grasp the whole logic behind your implementation. thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:38:00.017",
"Id": "29010",
"Score": "0",
"body": "Chris, you shouldn't learn about `malloc` without also learning `free`; they are two sides of a coin. If you are on linux/osx/unix etc you should use the manual pages. The command `man memcpy` will give you what you want to know about the function, but be sure to scroll to the bottom and follow the functions in \"See Also\". Browse around these pages and you will learn a lot about the standard library."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:08:30.280",
"Id": "18186",
"ParentId": "18182",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T16:59:40.317",
"Id": "18182",
"Score": "1",
"Tags": [
"c",
"strings"
],
"Title": "Enhanced concatenating function"
}
|
18182
|
<p>I just wrote this function and am wondering if it's secure enough for storing passwords in a database:</p>
<pre><code>public static function hash($salt, $str) {
$salt = md5($salt);
$salt = '$2y$12$HfuPgoDY94nHJssqQeVLmH' . $salt . '$';
return crypt($str, $salt);
}
</code></pre>
|
[] |
[
{
"body": "<h2>Yes</h2>\n<p>Blowfish is a great algorithm for storing passwords, it makes generating a hash slow such that brute force attacks are unviable. It's also <a href=\"http://php.net/manual/en/faq.passwords.php\" rel=\"nofollow noreferrer\">php's recommended means of storing passwords</a>.</p>\n<h3>But</h3>\n<p>The salt for blowfish is <a href=\"http://es1.php.net/manual/en/function.crypt.php\" rel=\"nofollow noreferrer\">supposed to be</a>:</p>\n<blockquote>\n<p>22 digits from the alphabet "./0-9A-Za-z".</p>\n</blockquote>\n<p>This applies to the salt string which in the question is:</p>\n<pre><code>'HfuPgoDY94nHJssqQeVLmH' . $salt . '$'\n</code></pre>\n<p>That's 22 chars + 32 chars + '$', which is 65 characters long and contains an illegal '$'. The consequence of that is that the salt actually used is a fixed string, the first 22 characters and is the same for all generated hashes.</p>\n<p>The salt should be random, and for example you could use something as simple as this:</p>\n<pre><code>$salt = '$2y$12$' . substr(md5(time()), 0, 22);\nreturn crypt($str, $salt);\n</code></pre>\n<p>Note however that this code is simple for brevity and can be significantly improved upon since the salt will only be made up of hexadecimal (0-9a-f) characters. <a href=\"https://stackoverflow.com/questions/4356289/php-random-string-generator\">Here's an example implementation that could be used to generate a better salt</a>.</p>\n<h3>Make cost a parameter</h3>\n<p>A cost of 12 is fine for passwords, but you may wish to make it a parameter so that e.g. unit tests are not needlessly slow whenever they generate a password.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T21:39:07.300",
"Id": "29150",
"Score": "0",
"body": "Thanks very much, marked as top answer. Sorry for late reply, was away over the last couple of days."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T06:13:10.937",
"Id": "40808",
"Score": "2",
"body": "If you take partial md5 hash as salt, you are effectively narrowing the namespace down to 16 characters (md5 is 0-9 a-f), when it could be around 60 characters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T20:46:49.440",
"Id": "51633",
"Score": "0",
"body": "The salt should be at least 64 characters, and it should be generated using a cryptographically secure random number generator. It needs to be unique for each hash. It should be the same size as the hash. Any less is too little entropy. Any more is wasted. Always pass work units into key stretching algorithms like bcrypt, PDKDF2, etc... That way you can increase the work required as CPUs get faster. Double the work every 2 years."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T21:03:55.633",
"Id": "51634",
"Score": "0",
"body": "@EricElliott `The salt should be at least 64 characters` - as quoted and stated in the linked reference in the question `CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: \"$2a$\", \"$2x$\" or \"$2y$\", a two digit cost parameter, \"$\", and 22 characters from the alphabet \"./0-9A-Za-z\"` - using 64 characters will simply mean the first 22 chars are used and the rest discarded. As pointed out by @user1615903 using md5(anything) will lead to a lower entropy salt, however it was used as a simple example of generating a 22 char random salt. I'm not sure what you wish to say regarding work units."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T01:58:47.540",
"Id": "51650",
"Score": "0",
"body": "In that case, I could consider this algorithm obsolete and try to find a PBKDF2 implementation that can take hash length / salt length as parameters, and let you specify iterations. CPU power doubles every year, and botnets are gigantic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T08:28:34.270",
"Id": "51669",
"Score": "0",
"body": "[PBKDF2 is weaker than bcrypt](http://blog.ircmaxell.com/2012/11/designing-api-simplified-password.html) - if you forgoe bcrypt for something that is known to be less secure (and not implemented in php itself), I'd say you've already chosen the wrong solution"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T11:04:41.787",
"Id": "18208",
"ParentId": "18183",
"Score": "6"
}
},
{
"body": "<h1>No</h1>\n\n<p>md5 gives you a hexadecimal output, 0-9 & a-f. Salt for bcrypt takes base64 encoded string. This means that if you use (partial) md5 as salt, you are loosing a lot of entropy. See <a href=\"http://blog.ircmaxell.com/2012/12/seven-ways-to-screw-up-bcrypt.html\" rel=\"nofollow\">#9: Bonus 2 from this post</a>. It's a good read on the subject.</p>\n\n<p>I have the same advice as that poster: <a href=\"http://www.openwall.com/phpass/\" rel=\"nofollow\">use a library</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T09:41:58.787",
"Id": "40884",
"Score": "2",
"body": "Re: use a library, PHP 5.5 will be including [simplified password hashing](http://blog.ircmaxell.com/2012/11/designing-api-simplified-password.html) functions. So, in the future it may be as simple as using these."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T06:28:55.240",
"Id": "26404",
"ParentId": "18183",
"Score": "3"
}
},
{
"body": "<h1>No</h1>\n\n<p>If you can't pass hash length, salt length, and work units (iterations) into the hash function, you have no way of keeping up with faster CPU speeds.</p>\n\n<p>The salt should be at least 64 characters, and it should be generated using a cryptographically secure random number generator. It needs to be unique for each hash. It should be the same size as the hash. Any less is too little entropy. Any more is wasted. Always pass work units into key stretching algorithms like bcrypt, PBKDF2, etc... That way you can increase the work required as CPUs get faster.</p>\n\n<p>In 2014, a PBKDF2/HMAC+Sha1 algorithm needs 128,000 work units. Double the work every 2 years.</p>\n\n<p>You need to store the work units with the hash so that you know how many to use for comparison, and you'll know to ask the users to select a new password when its time to upgrade their hash.</p>\n\n<h2>Addressing comments (there wasn't enough room in the comments field):</h2>\n\n<p>The salt should be at least 64 characters because the hash should be at least 64 characters. The salt should be the same size as the hash in order to prevent attackers from creating lookup tables for every possible salt. This is why it's a very bad idea to use a username as a salt -- especially now that we're fighting off attackers with enormous amounts of storage, CPU, and memory space compared to just a few years ago. In other words, having an equal length salt guarantees that generating tables for each salt (combining tables + dictionary attacks of the most common passwords) would take at least as long as a brute force attack.</p>\n\n<p>The minimum length of 64 characters is the current recommendation (for the year 2014, 2013 is almost over) in response to changing CPU speeds. The recommendation of 22 was first made years ago -- CPUs double in speed every year, and current botnets exist with over 90,000 nodes, capable of generating billions of salts per second. Super cheap supercomputing clusters can be built today for less than $2k. The old standards just don't cut it anymore.</p>\n\n<p>Salts need to be generated by a CSRNG in order to prevent collisions. Pseudo-random generators that are not CSRNGs are notoriously bad at that, often generating a collision within a few thousand hashes. For sites with hundreds of thousands or millions of users, that's not an acceptable rate.</p>\n\n<p>It's important to prevent collisions because a collision means that the same tables can be used to attack multiple hashes at the same time.</p>\n\n<blockquote>\n <p>Work units = cost parameter?</p>\n</blockquote>\n\n<p>Work units = cost parameter, yes, but the original question is about a function which does not take a cost parameter. The cost is hard-coded in the function.</p>\n\n<blockquote>\n <p>Sha1+HMAC is inappropriate</p>\n</blockquote>\n\n<p>No, \"HMACs are substantially less affected by collisions than their underlying hashing algorithms alone.\" Sha1+HMAC is far more secure than Sha1, and it is a currently accepted standard for password hashing.</p>\n\n<blockquote>\n <p>and PBKDF2 is weaker than bcrypt so overall..</p>\n</blockquote>\n\n<p>No, it isn't. Once you go over 60 characters or so, the cost of PBKDF2 trumps bcrypt by orders of magnitude.</p>\n\n<blockquote>\n <p>It's ubiquitous and time-tested with an academic pedigree from RSA Labs, you know, the guys who invented much of the cryptographic ecosystem we use today. Like bcrypt, PBKDF2 has an adjustable work factor. Unlike bcrypt, PBKDF2 has been the subject of intense research and still remains the best conservative choice.\n There has been considerably less research into the soundness of bcrypt as a key derivation function as compared to PBKDF2, and simply for that reason alone bcrypt is much more of an unknown as to what future attacks may be discovered against it.</p>\n</blockquote>\n\n<p>In other words, bcrypt is overrated. Especially if you think it's better than PBKDF2.</p>\n\n<p>Source: <a href=\"http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html\" rel=\"nofollow\">http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T08:27:31.937",
"Id": "51668",
"Score": "0",
"body": "There are no references given here, and it seems to me (I'm no expert) to be mostly misinformation. `The salt should be at least 64 characters` - why? `[the salt] should be cryptographically secure` - this is [commonly(?) held to be untrue](https://wiki.php.net/rfc/password_hash#salts_need_to_be_cryptographically_secure); `Always pass work units` - isn't that the cost parameter, if it's not - what is it? I'm not clear on your recommendation but sha1 is inappropriate and [\\[PBKDF2\\] is weaker than bcrypt](http://blog.ircmaxell.com/2012/11/designing-api-simplified-password.html) so overall.. -1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T16:20:08.140",
"Id": "51721",
"Score": "0",
"body": "@AD7six See my edits, above. There wasn't enough space to respond to your comments appropriately here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T16:39:23.180",
"Id": "51722",
"Score": "0",
"body": "A much better answer! Though `The salt should be at least 64 characters because the hash should be at least 64 characters.` this doesn't clarify anything - why? I don't feel the explanation for _requiring_ a cryptographically secure salt (I repeat: salt) addresses why; The cost paramter being hard coded isn't the same thing as a cost parameter not being used (that's how I understood all comments/references to it to date); `Once you go over 60 characters or so` how many passwords are that long? I'll remove my DV but I think saying bcrypt is inappropriate is still a _huge_ overstatement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T16:49:31.693",
"Id": "51723",
"Score": "0",
"body": "Additional point: If the code in the question isn't appropriate a link or example of (php) code that is appropriate would be a good idea, otherwise the read is left with \"OK but what can I use instead?\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T17:50:05.727",
"Id": "51798",
"Score": "0",
"body": "Added: Having an equal length salt guarantees that generating tables for each salt (combining tables + dictionary attacks of the most common passwords) would take at least as long as a brute force attack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T17:51:08.153",
"Id": "51799",
"Score": "0",
"body": "Having the cost parameter hard-coded is functionally equivalent to a cost parameter not being used. The whole point of the cost parameter is to ensure that the hashed passwords can be upgraded over time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T17:53:17.087",
"Id": "51800",
"Score": "0",
"body": "When I said over 60 characters or so, I was talking about the hash length, not the password length.\n\nThe password can be of any length (though I recommend at least 12 characters). I'm not saying that bcrypt is inappropriate, I'm saying that a hash length of 22 is obsolete, and any algorithm that can't satisfy the requirements that I've hopefully clarified should not be used for password hashing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T18:16:13.860",
"Id": "51801",
"Score": "0",
"body": "\"The whole point\" - wat :)? The point of the cost parameter is to affect the number of itterations. It should be a parameter; it not being a parameter is not the same thing as the cost parameter not being used ( I.e. set to a value of 1). Anyways, I feel we're basically way off topic the question was `Can I use this function to store passwords?` not \"is this the absolute most secure means of hashing a string?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T19:55:58.613",
"Id": "51901",
"Score": "0",
"body": "If you didn't need to be able to change the cost parameter over time, it wouldn't need to be a parameter at all, it could just be built in to the hash function. It's a parameter for a reason, and your function wrapper needs to expose that parameter so it can be changed going forward.\n\n\"wondering if it's secure enough to store passwords in a database\" -- The answer to that question is clearly \"no\". It would be irresponsible. Even for a simple web game, password db's are stolen regularly and then used to crack things like bank accounts."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T01:57:49.127",
"Id": "32356",
"ParentId": "18183",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "18208",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:01:07.580",
"Id": "18183",
"Score": "8",
"Tags": [
"php",
"security"
],
"Title": "Storing passwords in a database"
}
|
18183
|
<p>I'm trying to create my user.class.php constructor but I don't know really much about POO so I'm going to tell you what I'm doing and I hope you could help me.</p>
<p><strong>user.class.php</strong></p>
<pre><code>class user {
private $fullname;
private $age;
private $email;
private $sex;
private $nacionality;
public function __construct($usrId){
$mysqli = new connection_mysqli(); // I've already implemented this and it works.
$query = "SELECT * FROM USERS WHERE USER_ID = $userId";
if ($result = $mysqli->query($query)) {
$userData = $result->fetch_assoc();
$this->fullname = $userData['fullname'];
$this->age = $userData['age'];
$this->email = $userData['email'];
//.....
}
parent::__construct($usrId);
}
}
</code></pre>
<p>What I'm going to do on my index.php is this:</p>
<p><strong>index.php</strong></p>
<pre><code><?php
include('scripts/class/user.class.php');
$user = new user($_SESSION['userid'];
echo $user->fullname;
?>
</code></pre>
<p>So, is this going to work right? Is this well-programmed? Any tips?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-11T02:54:43.200",
"Id": "126814",
"Score": "0",
"body": "All your instance vars are private, this will not work. echo $user->fullname;"
}
] |
[
{
"body": "<p>First of all I recommend you to setup a local webserver to test your php code, if you have not done so jet (I assume you haven't tried your code, since your asking if it's going to work).</p>\n\n<p>Secondly you should abandon mysqli for <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow\">PDO</a>. Read <a href=\"http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/\" rel=\"nofollow\">PHP Database Access: Are You Doing It Correctly?</a></p>\n\n<p>Also, why are you calling the parent's constructor when the user class has no parent (eg. the class does not extend another class)?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T01:42:38.370",
"Id": "18198",
"ParentId": "18187",
"Score": "4"
}
},
{
"body": "<p>I just have a couple of small points:</p>\n\n<ul>\n<li>class names should be uppercase,</li>\n<li>when writing SQL queries, use uppercase either for keywords, or for names, but not both (it's easier to read that way). </li>\n<li>don't use <code>select *</code>, but only select what you actually need.</li>\n<li>nationality is misspelled.</li>\n<li>you control the session, but who knows how the id actually got there. I would always use prepared statements with non-constant data (or at least escape the data) to avoid SQL injection.</li>\n<li>your indentation is slightly off.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-10T22:12:18.093",
"Id": "69428",
"ParentId": "18187",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T18:22:09.223",
"Id": "18187",
"Score": "3",
"Tags": [
"php"
],
"Title": "User function construct user.class"
}
|
18187
|
<p>I would appreciate some feedback on my design of a few classes to query the <a href="http://trakt.tv/api-docs" rel="nofollow">Trakt.tv API</a>. </p>
<pre><code>public abstract class TraktQuery
{
private const string baseUrl = "http://api.trakt.tv/";
private const string apiKey = "[API key here]";
protected abstract string QueryUrl { get; }
protected abstract List<string> QueryParameters { get; }
protected abstract TraktResponse ParseResponse(string response);
public TraktResponse PerformQuery()
{
//exception handling removed for brevity
WebClient webClient = new WebClient();
string url = baseUrl + QueryUrl + "/" + apiKey + "/" + string.Join("/", QueryParameters);
string response = webClient.DownloadString(url);
return ParseResponse(response);
}
}
public class TraktQueryEpisodeSummary : TraktQuery
{
private string _showName;
private int _season;
private int _episodeNumber;
public TraktQueryEpisodeSummary(string showName, int season, int episodeNumber)
{
_showName = showName;
_season = season;
_episodeNumber = episodeNumber;
}
protected override string QueryUrl
{
get { return "show/episode/summary.json"; }
}
protected override List<string> QueryParameters
{
get
{
List<string> paramters = new List<string>();
paramters.Add(_showName);
paramters.Add("" + _season);
paramters.Add("" + _episodeNumber);
return paramters;
}
}
protected override TraktResponse ParseResponse(string response)
{
return JsonConvert.DeserializeObject<TraktResponseEpisodeSummary>(response);
}
public class TraktResponseEpisodeSummary : TraktResponse
{
public TraktShowInformation show { get; set; }
public TraktEpisode episode { get; set; }
}
</code></pre>
<p>Currently <code>TraktResponse</code> is an empty abstract class but I'll probably add to it soon.</p>
<p>This code is then used as follows:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
TraktQueryEpisodeSummary query = new TraktQueryEpisodeSummary("House", 1, 1);
TraktResponseEpisodeSummary summary = (TraktResponseEpisodeSummary)query.PerformQuery();
Console.WriteLine("Title: " + summary.show.title);
Console.WriteLine("Poster image: " + summary.show.images.poster);
Console.WriteLine("Genres: " + string.Join(", ", summary.show.genres));
Console.WriteLine("Episode name: " + summary.episode.title);
Console.WriteLine("Overview: " + summary.episode.overview);
}
}
</code></pre>
<p>What makes me think my design isn't quite right is that I have to cast from <code>TraktResponse</code> to the more specific <code>TraktResponseEpisodeSummary</code> in order to access the information I need. What I would like to do is make <code>TraktQueryEpisodeSummary.ParseResponse()</code> return a <code>TraktResponseEpisodeSummary</code> instead of a <code>TraktResponse</code> however I'm aware that C# doesn't support return type covariance which I think is what this is.</p>
<p>Are my concerns well-founded or not? Is there a better design that avoids this casting or is it perfectly normal and acceptable?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T20:32:01.740",
"Id": "29014",
"Score": "0",
"body": "Could you use generics to turn PerformQuery into PerformQuery<T>() where T: TraktResponse"
}
] |
[
{
"body": "<p>Dreza has outlined the correct approach (the same used in <code>IComparable<T></code>). You can make your class generic, with a type constraint:</p>\n\n<pre><code>public abstract class TraktQuery<TResponse> where TResponse : TraktResponse\n</code></pre>\n\n<p>And change every occurence of <code>TraktResponse</code> to <code>TResponse</code>:</p>\n\n<pre><code>protected abstract TResponse ParseResponse(string response);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public TResponse PerformQuery()\n{\n //...\n}\n</code></pre>\n\n<p>Then, your deriving class can be defined as</p>\n\n<pre><code>public class TraktQueryEpisodeSummary : TraktQuery<TraktResponseEpisodeSummary>\n{\n //...\n protected override TraktResponseEpisodeSummary ParseResponse(string response)\n {\n //...\n }\n //...\n}\n</code></pre>\n\n<p>Voila, no cast necessary: </p>\n\n<pre><code>TraktResponseEpisodeSummary summary = query.PerformQuery();\n</code></pre>\n\n<hr>\n\n<p>Further suggestions:</p>\n\n<ul>\n<li><p>Use collection and object initializers, for instance in the overridden <code>QueryParameters</code>:</p>\n\n<pre><code> return new List<string> {_showName, _season.ToString(), _episodeNumber.ToString()};\n</code></pre></li>\n<li><p>Or turn them into an <code>IEnumerable<string></code> and use an iterator block:</p>\n\n<pre><code>protected override IEnumerable<string> QueryParameters\n{\n get\n {\n yield return _showName;\n yield return _season.ToString();\n yield return _episodeNumber.ToString();\n }\n}\n</code></pre></li>\n<li><p>Be careful when concatenating strings to form a URL like this:</p>\n\n<pre><code>string url = baseUrl + QueryUrl + \"/\" + apiKey + \"/\" + string.Join(\"/\",QueryParameters);\n</code></pre>\n\n<p>It might be better to</p>\n\n<ol>\n<li>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.uri%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Uri</code></a> and/or <a href=\"http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx\" rel=\"nofollow\"><code>UriBuilder</code></a> class</li>\n<li>Put the first three parts into an sequence, then call <a href=\"http://msdn.microsoft.com/en-us/library/bb302894.aspx\" rel=\"nofollow\"><code>IEnumerable<T>.Concat</code></a> and finally <code>string.Join</code></li>\n<li>There's probably some even better options.</li>\n</ol></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T22:35:15.967",
"Id": "29020",
"Score": "0",
"body": "That's a great way to solve the problem. Extra bonus points for the other points of advice as well. Thanks very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T20:53:24.107",
"Id": "18193",
"ParentId": "18190",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18193",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T19:47:20.757",
"Id": "18190",
"Score": "3",
"Tags": [
"c#",
"casting"
],
"Title": "Returning a more specific class"
}
|
18190
|
<p>I've been working on my own PHP framework for my projects. I just finished coding my DI container. There is always room for improvement. Any input be it good or bad on my code would be appreciated.</p>
<p>Also, would using exceptions instead of <code>die()</code> be a better approach?</p>
<p>Should I move the higher API functions (<code>register()</code> and <code>addParameter()</code>) to a separate class?</p>
<pre><code><?php
class Reference
{
private $id;
public function __construct($id) {
$this->id = strtolower($id);
}
public function __toString() {
return (string) $this->id;
}
}
class ServiceContainer
{
private $services;
private $lastRegistered;
/**
* Register a service with the DI container
*
* @param string $id Name of the service
*
* @param string $class Class to attach to service
*
* @return object $this
*/
public function register($id, $class) {
$this->addService($id, $class);
return $this;
}
/**
* Add a parameter to a service
*
* @param mixed $parameter Parameter to add
*
* @param string $id Name of the service
*
* @return object $this
*/
public function addParameter($parameter, $id = null) {
$id = isset($id) ? $id : $this->lastRegistered;
$this->addService($id, null, array($parameter));
return $this;
}
/**
* Check if a service is registered
*
* @param string $id Name of the service
*
* @return bool
*/
public function isRegistered($id) {
$id = strtolower($id);
return array_key_exists($id, $this->services);
}
/**
* Add a service to the DI container
*
* @param string $id Name of the service
*
* @param string $class Class to attach to service
*
* @param array $parameters Array of parameters
*/
public function addService($id, $class, array $parameters = array()) {
$id = strtolower($id);
// Initialize the parameter array
if (! isset($this->services[$id]['parameters'])) $this->services[$id]['parameters'] = array();
foreach ($parameters as $parameter) {
$this->services[$id]['parameters'][] = $parameter;
}
if (isset($class)) $this->services[$id]['class'] = $class;
$this->lastRegistered = $id;
}
/**
* Get a service
*
* @param string $id Name of the service
*
* @return object Return the service
*/
public function getService($id) {
$id = strtolower($id);
if ($this->isRegistered($id)) {
// Build only when needed
return (is_object($this->services[$id])) ? $this->services[$id] : $this->buildService($id);
} else {
throw new \InvalidArgumentException(sprintf('Service "%s" does not exist.', $id));
}
}
/**
* Build the service
*
* This a low level function with all the DI container magic
*
* @param string $id Name of the service
*
* @return object Return the service
*/
private function buildService($id) {
if (! $this->isRegistered($id)) {
throw new \InvalidArgumentException(sprintf('Service "%s" does not exist.', $id));
}
if (! isset($this->services[$id]['class'])) {
throw new \RuntimeException(sprintf('Service "%s" has no class to construct.', $id));
}
$reflection = new \ReflectionClass($this->services[$id]['class']);
// If the paramters is a reference replace the parameter with the referenced service object
foreach ($this->services[$id]['parameters'] as &$parameter) {
if ($parameter instanceof Reference) {
$parameter = (string) $parameter;
$parameter = $this->buildService($parameter);
}
}
// Replace the whole array with the service object, this is destructive for the parameters
// but they are no longer needed
// If the constructor is null pass no arguments to the class
$this->services[$id] = (null === $reflection->getConstructor()) ? $reflection->newInstance() : $reflection->newInstanceArgs($this->services[$id]['parameters']);
return $this->services[$id];
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Throwing Exceptions is better than die(), yes. However, you should consider throwing your own defined Exceptions instead of any built in php ones. For example, you could throw and InvalidService Exception from the getService method.</p>\n\n<p>Using namespaces will help you avoid naming collisions. A class named \"Reference\" is bound to collide (perhaps you are already and left them out here for simplicity).</p>\n\n<p>You could combine register and add Parameter such that register accepts a second argument: an array of parameters:</p>\n\n<pre><code>$svc->register('foo', array(5, 'bar'));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T01:03:52.063",
"Id": "19243",
"ParentId": "18191",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T19:54:17.810",
"Id": "18191",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"dependency-injection"
],
"Title": "Dependency Injector Container"
}
|
18191
|
<p>I'd love to improve this code. I know I should put a lot of stuff in another class but I have no idea how.</p>
<pre><code>import java.util.Scanner;
public class UserInteraction {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice = 0;
String[] subjects = new String[10];
int grades[] = new int[10];
double sum = 0.0;
do
{
System.out.println("1. Enter a course name and a grade");
System.out.println("2. Display all grades");
System.out.println("3. Calculate the average grade");
System.out.println("4. Exit program");
choice = scan.nextInt();
if ( choice == 1 )
{
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Enter 10 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 10; i++ )
{
System.out.println("Subject:");
String temp = scansubjects.nextLine();
subjects[i] = temp.toLowerCase();
System.out.println("Grade:");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length - 1 ) )
{
System.out.println("Thank you!");
System.out.println();
}
}
}
if ( choice == 2 )
{
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for(int p = 0; p < subjects.length; p++)
{
System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
}
}
if ( choice == 3 )
{
System.out.println("Total of grades: " + getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + getAverage(grades));
System.out.println();
}
} while ( choice != 4);
}
public static double getAverage(int[] array)
{
int sum = 0;
for(int i : array) sum += i;
return ((double) sum)/array.length;
}
public static double getSum(int[] array)
{
int sum = 0;
for (int i : array)
{
sum += i;
}
return sum;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Let's go through refactoring your code step by step.</p>\n\n<h1>Get (almost) everything out of main()</h1>\n\n<p><code>main()</code> should consist of the fewest lines to launch the program. In this case you only need one.</p>\n\n<pre><code> new UserInteraction().run();\n</code></pre>\n\n<p>Or, for clarity, you can break that into two lines.</p>\n\n<pre><code> UserInteraction ui = new UserInteraction();\n ui.run();\n</code></pre>\n\n<p>You would then put everything from <code>main()</code> into a method called <code>run()</code>. The actually name of the new method is not important. You can use <code>start()</code> if you like.</p>\n\n<p>This step may seem almost silly at first, but it is very important. First, all your methods and variables stop needing to be static. For a beginner, you should avoid static as much as possible. Second, it starts you thinking in an object oriented way (as opposed to procedurally). Here's the first consequence of getting everything out of <code>main()</code>:</p>\n\n<pre><code> private double getAverage(int[] array)\n ...\n private double getSum(int[] array)\n</code></pre>\n\n<p>Notice that the methods are no longer static. This is a good thing. I also changed the accessibility to private. Like static, a member should be private unless there is a good reason for it not to be.</p>\n\n<h1>Methods should do one thing well</h1>\n\n<p>So now we have a monolithic <code>run()</code> method doing all sorts of this. Let's make <code>run()</code> only do one thing well. We're shooting for something like this:</p>\n\n<pre><code> private void run() {\n int choice = 0;\n\n do {\n showMenu();\n choice = scan.nextInt();\n\n switch (choice) {\n case 1:\n enterCourses();\n break;\n case 2:\n displayGrades();\n break;\n case 3:\n displayAverageGrade();\n }\n } while (choice != 4);\n }\n</code></pre>\n\n<p>Now <code>run()</code> only concerns itself with one thing: running the basic flow of the program.</p>\n\n<h1>Declare variables in the tightest scope possible</h1>\n\n<p>So where are all the variable declarations? In general, you want to declare your variables \"as close as you can.\" Variable scope is a little tricky but for a beginner, try to declare your variables in the same block as their used. (A block is roughly the code between braces {}). <code>choice</code> needs to be declared where it is because it's used outside the <code>switch</code> block. </p>\n\n<p>You only need one <code>scanner</code> object and it needs to be declared once. It will be used in several methods, so it needs to be declared outside of all methods but inside of a class. </p>\n\n<pre><code> public class UserInteraction {\n Scanner scan = new Scanner(System.in);\n\n public static void main(String[] args) { // ...\n</code></pre>\n\n<p>Let's leave the rest of the variable declarations and initializations for later and move code into our new methods.</p>\n\n<pre><code> private void showMenu() {\n System.out.println(\"1. Enter a course name and a grade\");\n System.out.println(\"2. Display all grades\");\n System.out.println(\"3. Calculate the average grade\");\n System.out.println(\"4. Exit program\");\n }\n\n private void enterCourses() {\n System.out.println(\"Enter 10 subjects and their corresponding grades:\");\n System.out.println();\n\n for (int i = 0; i < subjects.length; i++) {\n System.out.println(\"Subject:\");\n subjects[i] = scan.nextLine();\n\n System.out.println(\"Grade:\");\n grades[i] = scan.nextInt();\n scan.nextLine();\n\n if (i == (subjects.length - 1)) {\n System.out.println(\"Thank you!\");\n System.out.println();\n }\n }\n }\n\n private void displayGrades() {\n System.out.println(\"Subjects\" + \"\\tGrades\");\n System.out.println(\"---------------------\");\n\n for (int p = 0; p < subjects.length; p++) {\n\n System.out.println(subjects[p] + \"\\t\" + \"\\t\" + grades[p]);\n }\n }\n\n private void displayAverageGrade() {\n System.out.println(\"Total of grades: \" + getSum(grades));\n System.out.println(\"Count of grades: \" + grades.length);\n System.out.println(\"Average of grades: \" + getAverage(grades));\n System.out.println();\n }\n</code></pre>\n\n<p>Now you can see that <code>subjects</code> and <code>grades</code> need to have class scope, that is, to be declared outside of all methods. And we notice that declaring <code>sum</code> in <code>run()</code> is unnecessary because a local variable (one inside a method) will do.</p>\n\n<h1>Scanner weirdness</h1>\n\n<p>The <code>scanner</code> class has some oddities that I can't go into at length, but the long and the short is that you either put the line <code>scan.nextLine()</code> after each <code>scan.nextInt()</code>, or write a wrapper around <code>scanner</code> to hide the weirdness, or, like you did, have two <code>scanner</code> objects, one for strings and one for ints. The wrapper is best, but as you can imagine, it's the hardest. The nice thing though is if you write it correctly, you can reuse it anywhere.</p>\n\n<h1>Final thoughts</h1>\n\n<p>There is a lot more you can do, but I need to wrap this up. Here are some things to think about.</p>\n\n<ul>\n<li>You could put all your display into one class</li>\n<li>What happens when you enter a non-integer into the menu or grades prompts?</li>\n<li>There's a better way to store the subjects and grades. What about a class that holds one subject and grade? How does that change the program?</li>\n<li>You have repeated code in your <code>getAverage()</code> and <code>getSum()</code> methods. How can you get rid of that?</li>\n</ul>\n\n<p>Okay, here's the \"final\" code, but not really final as there's a lot still to do:</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class UserInteraction {\n private Scanner scan = new Scanner(System.in);\n private String[] subjects = new String[10];\n private int grades[] = new int[10];\n\n public static void main(String[] args) {\n new UserInteraction().run();\n }\n\n private void run() {\n int choice;\n\n do {\n showMenu();\n choice = scan.nextInt();\n scan.nextLine();\n\n switch (choice) {\n case 1:\n enterCourses();\n break;\n case 2:\n displayGrades();\n break;\n case 3:\n displayAverageGrade();\n }\n } while (choice != 4);\n }\n\n private void showMenu() {\n System.out.println(\"1. Enter a course name and a grade\");\n System.out.println(\"2. Display all grades\");\n System.out.println(\"3. Calculate the average grade\");\n System.out.println(\"4. Exit program\");\n }\n\n private void enterCourses() {\n System.out.println(\"Enter 10 subjects and their corresponding grades:\");\n System.out.println();\n\n for (int i = 0; i < subjects.length; i++) {\n System.out.println(\"Subject:\");\n subjects[i] = scan.nextLine();\n\n System.out.println(\"Grade:\");\n grades[i] = scan.nextInt();\n scan.nextLine();\n\n if (i == (subjects.length - 1)) {\n System.out.println(\"Thank you!\");\n System.out.println();\n }\n }\n }\n\n private void displayGrades() {\n System.out.println(\"Subjects\" + \"\\tGrades\");\n System.out.println(\"---------------------\");\n\n for (int p = 0; p < subjects.length; p++) {\n System.out.println(subjects[p] + \"\\t\" + \"\\t\" + grades[p]);\n }\n }\n\n private void displayAverageGrade() {\n System.out.println(\"Total of grades: \" + getSum(grades));\n System.out.println(\"Count of grades: \" + grades.length);\n System.out.println(\"Average of grades: \" + getAverage(grades));\n System.out.println();\n }\n\n private double getAverage(int[] array) {\n int sum = 0;\n for (int i : array) {\n sum += i;\n }\n return ((double) sum) / array.length;\n }\n\n private double getSum(int[] array) {\n int sum = 0;\n for (int i : array) {\n sum += i;\n }\n return sum;\n }\n\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T18:38:53.090",
"Id": "199768",
"ParentId": "18196",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T23:55:59.553",
"Id": "18196",
"Score": "2",
"Tags": [
"java"
],
"Title": "Displaying grades and calculating average grade"
}
|
18196
|
<p>I have a console application that I'm trying to make with minimal redundant code.</p>
<p>I have 4 functions, Create, Read, Update, and Delete.</p>
<ul>
<li>is it possible or practical to combine the four functions into one function that takes different parameters to create, read, update, or delete?</li>
<li>is it possible to also adjust that one combined function to use whichever of my two entity tables (Man or Location) I tell it to use?</li>
</ul>
<p>I also have a helper static class that provides some functions to make some tasks easier.</p>
<h2>4 CRUD FUNCTIONS</h2>
<pre><code>class Program
{
#region CRUD functions
static private void DoCreate()
{
int myID;
var dbEntities = new TestDatabaseEntities();
string sNewName = "";
myID = stcHelper.InsistOnValidInput<int>("Enter ID: ", "ID must be Valid: ", int.TryParse);
sNewName = stcHelper.GetInput<string>("Enter Name", x => x.Trim());
stcHelper.TryDataBase(dbEntities, () =>
{
dbEntities.Men.Add(new Man{ManID = myID, Name = sNewName});
Console.WriteLine("Insert Sucessful");
});
stcHelper.SaveDBChanges(dbEntities);
}
static private void DoRead()
{
var dbEntities = new TestDatabaseEntities();
string sDisplayDivider = "|||||||||||||||||||||||||||||||||||||||";
var query = from person in dbEntities.Men
where true
select person;
Console.WriteLine(sDisplayDivider);
stcHelper.TryDataBase(dbEntities, () =>
{
foreach (Man m in query)
{
Console.WriteLine(m.ManID + " " + m.Name);
}
});
Console.WriteLine(sDisplayDivider);
}
static private void DoUpdate()
{
int myID;
var dbEntities = new TestDatabaseEntities();
string sNewName = "";
// get The Target's ID for the user to update
myID = stcHelper.GetInput<int>("Enter ID to update: ", int.Parse);
// get the new name from user
sNewName = stcHelper.GetInput<string>("Enter new name: ", x => x.Trim());
// Query the database for the row to be updated.
var query =
from person in dbEntities.Men
where person.ManID == myID
select person;
// Execute the query, and change the column values
stcHelper.TryDataBase(dbEntities, () =>
{
foreach (Man M in query)
{
M.Name = sNewName;
Console.WriteLine("Update Sucessful!");
}
});
stcHelper.SaveDBChanges(dbEntities);
}
static private void DoDelete()
{
int myID;
//T myID;
var dbEntities = new TestDatabaseEntities();
myID = stcHelper.InsistOnValidInput<int>("Enter ID to delete: ", "ID Invalid, please re-enter", int.TryParse);
// Query the database for the rows to be deleted.
var Query =
from details in dbEntities.Men
where details.ManID == myID
select details;
stcHelper.TryDataBase(dbEntities, () =>
{
foreach (var detail in Query)
{
dbEntities.Men.Remove(detail);
Console.WriteLine("Removal successful.");
}
});
stcHelper.SaveDBChanges(dbEntities);
}
#endregion
}
</code></pre>
<h2>HELPER CLASS</h2>
<pre><code>public static class stcHelper
{
/// <summary>
/// Delegate that matches the signature of TryParse, method defined for all primitives.
/// </summary>
/// <typeparam name="T">Output type of This Delegate</typeparam>
/// <param name="input">input for this Delegate to translate to type T</param>
/// <param name="output">The translated variable to return via out parameter</param>
/// <returns>Whether the Parse was successful or not, and output as output</returns>
public delegate bool TryParse<T>(string input, out T output);
/// <summary>
/// Prompts user for input with given message, and converts input to type T
/// </summary>
/// <typeparam name="T">Value type to convert to, and return</typeparam>
/// <param name="message">Message to be printed to console</param>
/// <param name="transform">The type conversion function to use on user's input</param>
/// <returns>Type T</returns>
static public T GetInput<T>(string message, Converter<string, T> transform)
{
Console.Write(message);
return transform(Console.ReadLine());
}
/// <summary>
/// Repeatedly asks the user for valid input
/// </summary>
/// <typeparam name="T">The type of result to return</typeparam>
/// <param name="message">The initial message to prompt the user with</param>
/// <param name="errorMessage">The message to prompt user with if input is invalid</param>
/// <param name="validator">The TryParse function to use to test the input.</param>
/// <returns>Type T</returns>
public static T InsistOnValidInput<T>(string message, string errorMessage, TryParse<T> validator)
{
Console.Write(message);
T result;
while (!validator(Console.ReadLine(), out result))
{
Console.Write(errorMessage);
}
return result;
}
static public void SaveDBChanges(TestDatabaseEntities MyDBEntities)
{
// Submit the changes to the database.
TryDataBase(MyDBEntities,
() =>
{
MyDBEntities.SaveChanges();
Console.WriteLine("Save Changes Successful.");
});
}
static public void TryDataBase(TestDatabaseEntities MyDBEntities, Action MyAction)
{
try
{
MyAction();
}
catch (Exception e)
{
Console.WriteLine("Database interaction failed: " + e.ToString());
return;
}
}
}
</code></pre>
<h2>Man and Location. Auto-generated</h2>
<p>by the entity framework</p>
<pre><code>public partial class Man
{
public Man()
{
this.Locations = new HashSet<Location>();
}
public int ManID { get; set; }
public string Name { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
public partial class Location
{
public Location()
{
this.Men = new HashSet<Man>();
}
public int PlaceID { get; set; }
public string Place { get; set; }
public virtual ICollection<Man> Men { get; set; }
}
</code></pre>
<h2>Man and Location, NON-Auto Generated</h2>
<pre><code>public partial class Location : IAmAnEntity
{
public void PromptNewName()
{
Place = stcHelper.GetInput<string>("Give Location Name: ", (x) => x.Trim());
}
public void PromptNewID()
{
PlaceID = stcHelper.InsistOnValidInput<int>("Give New ID: ", "ID must be integer: ", int.TryParse);
}
public void CreateMe()
{
PromptNewID();
PromptNewName();
}
public void ReadMe()
{
throw new NotImplementedException();
}
public void UpdateMe()
{
throw new NotImplementedException();
}
public void DeleteMe()
{
throw new NotImplementedException();
}
}
public partial class Man : IAmAnEntity
{
public void PromptNewName()
{
Name = stcHelper.GetInput<string>("Enter Name for new person", i => i.Trim());
}
public void PromptNewID()
{
ManID = stcHelper.InsistOnValidInput<int>("Enter ID for new person:", "ID must be integer: ", int.TryParse);
}
public void CreateMe()
{
PromptNewID();
PromptNewName();
}
public void ReadMe()
{
throw new NotImplementedException();
}
public void UpdateMe()
{
throw new NotImplementedException();
}
public void DeleteMe()
{
throw new NotImplementedException();
}
}
</code></pre>
<h2>interface IAmAnEntity</h2>
<pre><code>public interface IAmAnEntity
{
void PromptNewName();
void PromptNewID();
void CreateMe();
void ReadMe();
void UpdateMe();
void DeleteMe();
}
</code></pre>
|
[] |
[
{
"body": "<p>First off, thank you for the formatting and white space.</p>\n\n<p>To answer your question, having the CRUD operations into one is not possible. Somewhere you have to have different logic to do the operations, which is the standard way of doing thing</p>\n\n<p>Looking through your code, I see a few issues. Having your data access, U.I. and entities in one class violates the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a> all over the place. Basically a class/method should do one thing, and do it well.</p>\n\n<p>Your entities, data access and U.I. should be separated out into their own classes, maybe even their own libraries. When I read any class with the word 'helper' in it, I cringe, especially when its static. There is usually a better to write that code, and still follow <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\">SOLID</a>.</p>\n\n<p>I would change it something more like this:</p>\n\n<pre><code>class DataAccess\n{\n public Man CreateMan(string name, ...)\n {\n // Logic required to create a man\n }\n\n public bool UpdateMan(Man man)\n {\n // Logic required to update\n }\n\n public bool DeleteMan(Man man)\n {\n // Logic required to delete\n }\n\n public Man GetMan(int id)\n {\n // Logic required to retrieve\n }\n}\n\npublic class UserInterface\n{\n public T GetInput<T>(string prompt)\n {\n\n }\n\n public T InsistOnValidInput<T>(string prompt, TryParse<T> validator)\n {\n }\n}\n\npublic static class Program\n{\n private DataAccess _dataAccess;\n private UserInterface _userInterface;\n\n public int Main()\n {\n _dataAccess = new DataAccess();\n _userInterface = new UserInterface();\n\n var input = string.Empty;\n while(input != \"quit\")\n {\n input = _userInterface.GetInput<string>(\"Enter operation:\");\n ProcessInput(input);\n }\n }\n\n public void ProcessInput(string input)\n {\n switch(input)\n {\n case \"new Person\":\n CreatePerson();\n break;\n case \"delete person\":\n DeletePerson()\n break;\n // other operations\n } \n }\n\n private CreatePerson()\n {\n var firstName = _userInterface .InsistOnValidInput<string>(\"Enter first name: \", i => i.Trim());\n var age = _userInterface .InsistOnValidInput<int>(\"Enter age: \", int.TryParse);\n\n var person = _dataAcess.CreatePerson(firstName, age, ...);\n }\n\n // More operations\n}\n</code></pre>\n\n<p>This code will decouple your logic, so in the future if you wish to change how the data is stored, you just change the DataAccess code. If you want to make it a windows app, you replace the UserInterface class. In fact, I would create a interfaces and inject concrete classes where they are required. But this is a discussion for another time.</p>\n\n<p>A couple more comments:</p>\n\n<ul>\n<li>Lose the regions. Regions just add unnecessary and confusing code. If you need to wrap code in a region, there is a good chance that code can be pulled out into its own class.</li>\n<li>Most of the comments add nothing to the code. // Execute the query, and change the column values is fairly obvious to anybody that can read that code. Comments should be used sparingly to justify why you did something, explain the reasoning behind what looks like complex code, or to clarify something. i.e. // Bug in X library so this has to be done first\n<ul>\n<li>Most of the places you've created static methods, static is being used incorrectly. You have basically create a procedural application, rather than an object oriented application.</li>\n</ul></li>\n</ul>\n\n<p>Just a quick note: this is done in notepad so the code might not be 100% accurate, but hopefully it portrays the general ideas.</p>\n\n<p>Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T16:16:11.130",
"Id": "29056",
"Score": "0",
"body": "As you suspected, this code won't compile because of a couple of typos (`i => i.Trim` is missing the `()` for instance) and misunderstandings (`InsistOnValidInput` expects a `delegate bool TryParse<T>(string input, out T output)`, so `int.Parse` will not match it, however `int.TryParse` will work). It is otherwise a very helpful review and I'll upvote it as soon as those issues are fixed ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T15:55:06.637",
"Id": "29104",
"Score": "0",
"body": "thank you this is helpful. if dataaccess and ui do user interface stuff, what should the main program maintain responsibility for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T16:31:03.347",
"Id": "29108",
"Score": "0",
"body": "Your main program can be the user interface. I'm just suggesting having the domain objects and data access in other libraries."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T15:41:04.113",
"Id": "18217",
"ParentId": "18197",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "18217",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-03T23:59:57.710",
"Id": "18197",
"Score": "5",
"Tags": [
"c#",
"optimization",
"design-patterns",
"entity-framework"
],
"Title": "combining 4 CRUD functions into 1?"
}
|
18197
|
<p>I'm writing some crypto code, and as part of it, we have to implement modular exponentiation.
I have it working, both with the right-to-left binary method and with the Montgomery formula. </p>
<p>While they both work, the Montgomery calculations take three times longer than the right-to-left binary method. This is extremely frustrating, as I worked out the right-to-left in an afternoon, but it's taken me three days solid work to figure out the Montgomery. I thought it would be faster, so I'm guessing it's my implementation - three different function calls are used to work it out. </p>
<p>Here is the code, if anyone can see anything that would speed it up I'd be delighted to hear it. </p>
<p>First I needed a function to get the values for Extended Euclid - </p>
<pre><code>private static BigInteger[] extendedEuclid(BigInteger p, BigInteger q) {
if(q.compareTo(BigInteger.ZERO) == 0)
return new BigInteger[] {p, BigInteger.ONE, BigInteger.ZERO};
BigInteger[] vals = extendedEuclid(q, p.mod(q));
BigInteger d = vals[0];
BigInteger a = vals[2];
BigInteger divBit = p.divide(q);
BigInteger mulBut = divBit.multiply(vals[2]);
BigInteger b = vals[1].subtract(mulBut);
return new BigInteger[] {d, a, b};
}
</code></pre>
<p>This works but calculates value I never need - all I use is values[1] but to get it I need to calculate the others, I think?</p>
<p>Next we have the helper function monPro :</p>
<pre><code>private static BigInteger monPro(BigInteger aBar, BigInteger bBar, BigInteger r, BigIntegernPrime, BigInteger n) {
BigInteger t = aBar.multiply(bBar);
BigInteger m = (t.multiply(nPrime)).mod(r);
BigInteger u = (m.multiply(n).add(t)).divide(r);
if(u.compareTo(n) >= 0)
return u.subtract(n);
else return u;
}
</code></pre>
<p>This is needed to use the final function, modExp - </p>
<pre><code>private static BigInteger modExp(BigInteger M, BigInteger e, final BigInteger n) {
BigInteger r = new BigInteger("2").pow(n.bitLength());
BigInteger[] values = extendedEuclid(r, n);
BigInteger rInverse = values[1].mod(n);
BigInteger mBar = M.multiply(r).mod(n);
BigInteger xBar = new BigInteger("1").multiply(r).mod(n);
BigInteger nPrime = n.negate().modInverse(r);
for(int i = e.bitLength() -1 ; i >= 0 ; i--) {
xBar = monPro(xBar, xBar, r, nPrime, n);
if (e.testBit(i) == true)
xBar = monPro(mBar, xBar, r, nPrime, n);
}
BigInteger returnValue = monPro(xBar, BigInteger.ONE, r, nPrime, n);
return returnValue;
}
}
</code></pre>
<p>I'm almost certain the running time is due to the amount of time the actual modExp functon calls monPro. Euclid is only called once so I can't see that being the huge deal, I could be wrong. Anyway, any tips or pointers much appreciated, this has turned out to be an extremely frustrating exercise (optimize for three days and slow it down by a factor of three....booooooo!)</p>
<p>PS - I'm not allowed use the BigInteger function modPow.</p>
|
[] |
[
{
"body": "<p>Not really an optimization note but I'd be much cleaner if you'd use a separate object to store the result value instead of the <code>BigInteger</code> array. Its keys are magic numbers currently. They could be named fields in the result object. It would also remove the risk of creating arrays with more or less values than required and the risk of accessing invalid indexes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T13:59:49.723",
"Id": "18212",
"ParentId": "18199",
"Score": "0"
}
},
{
"body": "<p>There are two points where you can improve the performance. This is more related to the algorithm itself, but I guess the answer fits better here than in crypto.SE...</p>\n\n<ol>\n<li>When computing <code>m</code> and <code>u</code>, you are using <code>mod(r)</code> and <code>divide(r)</code>. But since <code>r</code> is a power of 2, these are just a bitwise <code>and</code> (with <code>r - 1</code>) and a right shift (by <code>n.bitLength()</code>), which should be much faster. It also helps reducing <code>t</code> modulo <code>r</code> (also using <code>and</code>) before multiplying by <code>nPrime</code>.</li>\n<li>Montgomery works better at the word level. If <code>n</code> has <code>w</code> words, then your code takes <code>2 * (w^2)</code> word multiplications when computing <code>m</code> and <code>u</code>, but could take <code>w^2 + w</code> when using word-level Montgomery. So if you really need speed, you'll need to use an array of integers instead of <code>BigInteger</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T12:47:35.687",
"Id": "18539",
"ParentId": "18199",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T01:53:22.153",
"Id": "18199",
"Score": "3",
"Tags": [
"java",
"optimization",
"homework"
],
"Title": "Optimization of exponentiation"
}
|
18199
|
<p>Even though it's simple, I've spent quite a bit of time on it, learning as I go. Is there anyway I can make this code more efficient, more crossbrowser compatible or just generally better?</p>
<p><a href="http://jsfiddle.net/njDvn/113/" rel="nofollow noreferrer">jsFiddle</a></p>
<pre><code><!-- Geocode -->
$(document).ready(function () {
var GeoCoded = { done: false };
autosuggest();
$('#myform').on('submit', function (e) {
if (GeoCoded.done) return true;
e.preventDefault();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;
$('#myform input[type="submit"]').attr('disabled', true);
geocoder.geocode({
'address': address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
GeoCoded.done = true;
$('#myform').submit();
} else {
console.log("Geocode failed: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled', false);
}
});
});
});
function autosuggest() {
var input = document.getElementById('location');
var options = {
types: [],
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T14:55:30.203",
"Id": "29053",
"Score": "1",
"body": "To get some quick ideas for improvements, you can try putting your code through [jslint](http://jslint.com), or [jshint](http://jshint.com) - jshint is easier to use as it requires less set-up (for your code, you mostly just need to check the \"jQuery\" checkbox)."
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>When you wrote <br></p>\n\n<pre><code>var latLng = results[0].geometry.location;\n$('#lat').val(results[0].geometry.location.lat());\n$('#lng').val(results[0].geometry.location.lng());\n</code></pre>\n\n<p>you probably meant to write </p>\n\n<pre><code>var latLng = results[0].geometry.location;\n$('#lat').val(latLng .lat());\n$('#lng').val(latLng .lng());\n</code></pre></li>\n<li><p>I wonder why you capture <code>new google.maps.places.Autocomplete(input, options);</code> into <code>autocomplete</code> since you do nothing with <code>autocomplete</code>.</p></li>\n<li><p>1 <code>var</code> block with comma separated variables is considered the standard, preferably on top.</p></li>\n<li><p>You could capture <code>document.getElementById('location')</code> into a var to prevent repeated DOM lookups</p></li>\n<li><p>Don't do <code>console.log</code> in production code</p></li>\n<li><p>Creating <code>GeoCoded</code> as an object with 1 property is overkill, why not simply<br> \n<code>var geoCodingDone = false;</code></p></li>\n<li><p>lowerCamelCasting is not applied consistently : <code>autosuggest</code> -> <code>autoSuggest</code>, <code>autocomplete</code> -> <code>autoComplete</code></p></li>\n<li><p>There is an indentation problem after <code>return true;</code></p></li>\n</ul>\n\n<p>With all that, I would counter suggest something like</p>\n\n<pre><code>$(document).ready(function () {\n\n var geoCodingDone = false,\n locationInput = document.getElementById('location'); \n\n createAutoSuggest();\n\n $('#myform').on('submit', function (e) {\n if (geoCodingDone) \n return true;\n\n var geocoder = new google.maps.Geocoder(),\n address = locationInput.value; \n\n e.preventDefault();\n\n $('#myform input[type=\"submit\"]').attr('disabled', true);\n\n geocoder.geocode( {'address': address }, function (results, status){\n if (status == google.maps.GeocoderStatus.OK) {\n var latLng = results[0].geometry.location;\n $('#lat').val(latLng.lat());\n $('#lng').val(latLng.lng());\n geoCodingDone = true;\n $('#myform').submit();\n } else {\n $('#myform input[type=\"submit\"]').attr('disabled', false);\n }\n });\n });\n});\n\nfunction createAutoSuggest(){\n var options = { types: [] };\n new google.maps.places.Autocomplete(locationInput, options);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T16:09:35.113",
"Id": "40854",
"ParentId": "18200",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T02:04:24.070",
"Id": "18200",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"geospatial",
"google-maps"
],
"Title": "Geocoder form with Google Maps autosuggest"
}
|
18200
|
<h2>Summary</h2>
<p>I've created a function that blends tiles on a 2D hexagonal grid with their neighboring tiles based on an image that serves as a "blend mask". It runs, and isn't too intensive, but I feel it can be better / faster. Drawing pixel-by-pixel is very intensive even for the 108x122 (Relatively small) images I'm using. With so many iterations per loop (13,176 in this case) per tile, even a small optimization could make a significant improvement.</p>
<p>I'll outline my process below, and I welcome all feedback and suggestions for optimization. If there's a way to achieve this without pixel-by-pixel updates I'd be intrigued to hear about it. I've noticed that <code>context.drawImage()</code> seems to draw much faster than pixel-by-pixel updates and I'm not sure how that's achieved. Maybe I could utilize a similar process?</p>
<h2>The Blend Mask</h2>
<p><img src="https://i.stack.imgur.com/NZsFZ.png" alt="Blend Mask"></p>
<p>This is the (actual size) blend mask I've devised to control the most basic blending technique. There are six color ranges, each representing which tile to pull blend a texture from, and at which opacity:</p>
<ul>
<li>0<Red<127: Top Right</li>
<li>0<Green<127: Mid Right</li>
<li>0<Blue<127: Bot Right</li>
<li>128<Red<255: Bot Left</li>
<li>128<Green<255: Mid Left</li>
<li>128<Blue<255: Top Left</li>
</ul>
<p>Opacity is determined by the modulo of 127 into the corresponding R, G or B value. For example, a pixel defined as RGB(200, 0, 100) would mix the bottom left neighbor's texture at 200%127 = 73 opacity and the bottom right neighbor's texture at 100%127 = 100 opacity. You'd find such a pixel close to the bottom of this particular blend map.</p>
<p>I would like to continue using my blend mask method regardless of optimization capabilities due to the fact that I can alter this blend mask at any time, not only modifying the current shape but also adding more natural / chaotic looking blends to enhance aesthetics.</p>
<h2>Example Blend</h2>
<p><img src="https://i.stack.imgur.com/1zDmE.png" alt="Grass Tile">
<img src="https://i.stack.imgur.com/od6lf.png" alt="Sand Tile">
<img src="https://i.stack.imgur.com/0GkWj.png" alt="Dirt Tile"></p>
<p><img src="https://i.stack.imgur.com/y5bpV.png" alt="Example Blend"></p>
<h2>Relevant Code</h2>
<p>My blend function. This is where over 90% of the actual processing takes place (Specifically in the pixel loop <code>for(var i = 0; i < mask.width*mask.height*4; i+=4)</code>), so this is where I need to make the optimizations. All other code is provided solely to help understand the function's process.</p>
<pre class="lang-js prettyprint-override"><code>function blend(mask, row, col) {
blender.drawImage(mask, 0, 0, mask.width, mask.height);
var imageData = blender.getImageData(0, 0, mask.width, mask.height);
var data = imageData.data;
var tileType = [
/*Top Right:*/ (row%2 == 0) ? getTile(row-1, col+1) : getTile(row-1, col+0),
/*Mid Right:*/ getTile(row+0, col+1),
/*Bot Right:*/ (row%2 == 0) ? getTile(row+1, col+1) : getTile(row+1, col+0),
/*Bot Left: */ (row%2 == 0) ? getTile(row+1, col+0) : getTile(row+1, col-1),
/*Mid Left: */ getTile(row+0, col-1),
/*Top Left: */ (row%2 == 0) ? getTile(row-1, col+0) : getTile(row-1, col-1),
];
// This is where over 90% of the processing occurs
for(var i = 0; i < mask.width*mask.height*4; i+=4) {
var colors = new Array();
var alphaSum = 0;
for(var side = 0; side < tileType.length; side++) {
var semi = 127 * Math.floor(side/3);
var index = i+side%3;
if(data[index] > semi && data[index] <= semi+128) {
if(tileType[side] != null) {
alphaSum += data[index] - semi;
colors.push({
r: images[tileType[side]].data[i+0],
g: images[tileType[side]].data[i+1],
b: images[tileType[side]].data[i+2],
a: data[index] - semi
});
}
}
}
if(colors.length > 1) {
var colorSum = { r:0, g:0, b:0 };
for(var index = 0; index < colors.length; index++) {
var alphaRatio = colors[index].a / alphaSum;
colorSum.r += colors[index].r * alphaRatio;
colorSum.g += colors[index].g * alphaRatio;
colorSum.b += colors[index].b * alphaRatio;
}
data[i+0] = colorSum.r;
data[i+1] = colorSum.g;
data[i+2] = colorSum.b;
data[i+3] = 255 - 255/((alphaSum+127)/127);
} else if (colors.length > 0) {
data[i+0] = colors[0].r;
data[i+1] = colors[0].g;
data[i+2] = colors[0].b;
data[i+3] = 255 - 255/((colors[0].a+127)/127);
} else {
data[i+3] = 0;
}
}
blender.putImageData(imageData, 0, 0);
}
</code></pre>
<p>My draw function, which calls my blend function once per tile:</p>
<pre class="lang-js prettyprint-override"><code>function draw() {
var start = Date.now();
for(var row = 0; row < tiles.length; row++) {
for(var col = 0; col < tiles[row].length; col++) {
var tileType = tiles[row][col];
var indent = (row%2) ? 0.0 : 0.5 ;
var y = (images[tileType].height+4) * row * 0.75;
var x = images[tileType].width * (col+indent);
buffer.drawImage(images[tileType], 0, 0);
blend(blendMask, row, col);
ctx.drawImage(bCanvas, x, y, images[tileType].width, images[tileType].height);
ctx.drawImage(blCanvas, x, y, images[tileType].width, images[tileType].height);
}
}
console.log("Draw executed in " + (Date.now() - start) + "ms");
}
</code></pre>
<h2>Additional Code</h2>
<p>Declaring canvases and contexts:</p>
<pre class="lang-js prettyprint-override"><code>canvas = $("#blendCanvas")[0];
ctx = canvas.getContext("2d");
bCanvas = $("#buffer")[0];
buffer = bCanvas.getContext("2d");
blCanvas = $("#blender")[0];
blender = blCanvas.getContext("2d");
</code></pre>
<p>My tile images array (Pseudo-code):</p>
<pre class="lang-js prettyprint-override"><code>var images = new Array();
var imageURLs = [
"images/gameboard/grasshex.png",
"images/gameboard/sandhex.png",
"images/gameboard/dirthex.png"
];
for(var i = 0; i < imageURLs.length; i++) {
images.push(new Image());
images[i].src = imageURLs[i];
$(images[i]).load(function () {
// Draw image to a buffer canvas
this.data = buffer.getImageData().data;
}
</code></pre>
<p>Defining example tile grid (As seen above):</p>
<pre class="lang-js prettyprint-override"><code>var tiles = [
[0, 1],
[2, 1, 2],
[1, 0]
];
</code></pre>
<h2>Working Example</h2>
<p>And of course, a working example:
<a href="https://dl.dropbox.com/u/7377788/Other/Blend2/avblend.html" rel="nofollow noreferrer">https://dl.dropbox.com/u/7377788/Other/Blend2/avblend.html</a></p>
<h2>Thanks!</h2>
<p>I hope this isn't too long-winded, and I'm looking forward to seeing if anybody has any suggestions for optimization. Thanks for reading!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T22:04:10.597",
"Id": "29066",
"Score": "2",
"body": "Excellent, well-formatted, and interesting question. +1! I hope you'll get some helpful answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-17T07:56:03.770",
"Id": "353326",
"Score": "0",
"body": "The dropbox link is not working for me."
}
] |
[
{
"body": "<p>First of all, very nice and interesting question!</p>\n\n<p>Second, <code>drawImage</code> is fast because it's native, compiled code - there's no interpreted JavaScript going on. And since it's native, it can utilize the computer in ways browser-based JavaScript simply can't. For instance, <code>drawImage</code> might be multi-threaded, and/or use the GPU to do the drawing. It's basically written \"closer to the metal\" than you can hope to achieve in JavaScript.</p>\n\n<p>But! There are some things you <em>can</em> do with the javascript you have.</p>\n\n<p>I messed around with it a little, and got a big improvement by doing some very, <em>very</em> simple things. In fact, I didn't change any of your logic at all.</p>\n\n<p>In order to test, I changed the checkbox's click-handler to run the <code>draw</code> method 100 times in a row, and log the cumulative time for those 100 runs rather than log for each run. This was basically to \"smooth\" the stats by having more samples.</p>\n\n<p>Now, the first thing I noticed about your code is that you declare variables inside the loops, meaning things get redeclared again and again. I can't say how much this affects performance, because different JS runtimes have different optimizations for such things. But in any case, it's just good practice to declare all local variables at the top of a functions.</p>\n\n<p>The other thing I did, which I think had the largest impact, was simply caching certain values that were otherwise being calculated and re-calculated on each loop. I.e. I went from this:</p>\n\n<pre><code>for(var i = 0; i < mask.width*mask.height*4; i+=4) {\n ...\n for(var side = 0; side < tileType.length; side++) {\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>var i,\n l = mask.width * mask.height * 4, // calculate this once!\n side,\n types = tileType.length; // .length can be cached too (see: http://jsperf.com/caching-array-length)\n\nfor(i = 0 ; i < l ; i += 4) {\n ...\n for(side = 0 ; side < types ; side++) {\n</code></pre>\n\n<p>Of course, I moved every other <code>var</code> declaration to the top of the <code>blend</code> function as well. I also put <code>colors.length</code> in a variable, and used it for both the loop and the <code>if-else if</code> branching</p>\n\n<p>Overall, by doing these basic things (and <em>only</em> in <code>blend()</code> - didn't touch anything else), I got the following results:</p>\n\n<p>Original blend (x100): <strong>~2300ms</strong><br>\nRevised blend (x100): <strong>~1200ms</strong></p>\n\n<p>(this was in Chrome/Mac)</p>\n\n<p>So I basically shaved ~10ms per iteration (or 1 second for 100 iterations) off by just doing some basic code-cleanup.</p>\n\n<p>Now, I'm sure there's more stuff to find in this vein. And there may well be even more to find, by doing actual refactoring - again, I didn't actually refactor anything at all. And I didn't even do basic clean-up on the rest of the code.</p>\n\n<p>Here's what I ended up with:</p>\n\n<pre><code>function blend(mask, row, col) {\n \"use strict\";\n var imageData,\n data,\n oddRow = row % 2,\n tileType = [\n oddRow ? getTile(row-1, col+1) : getTile(row-1, col), /*Top Right:*/\n getTile(row, col+1), /*Mid Right:*/\n oddRow ? getTile(row+1, col+1) : getTile(row+1, col), /*Bot Right:*/\n oddRow ? getTile(row+1, col) : getTile(row+1, col-1), /*Bot Left: */\n getTile(row, col-1), /*Mid Left: */\n oddRow ? getTile(row-1, col) : getTile(row-1, col-1), /*Top Left: */\n ],\n i,\n l = mask.width*mask.height*4,\n side,\n types = tileType.length,\n colors,\n alphaSum,\n alphaRatio,\n colorSum,\n semi,\n index,\n colorsLength;\n\n\n blender.drawImage(mask, 0, 0, mask.width, mask.height);\n imageData = blender.getImageData(0, 0, mask.width, mask.height);\n data = imageData.data;\n\n for(i = 0 ; i < l ; i += 4) {\n colors = [];\n alphaSum = 0;\n\n for(side = 0; side < types; side++) {\n semi = 127 * Math.floor(side/3);\n index = i+side%3;\n\n if(data[index] > semi && data[index] <= semi+128) {\n if(tileType[side] != null) {\n alphaSum += data[index] - semi;\n\n colors.push({\n r: images[tileType[side]].data[i+0],\n g: images[tileType[side]].data[i+1],\n b: images[tileType[side]].data[i+2],\n a: data[index] - semi\n });\n }\n }\n }\n\n colorsLength = colors.length;\n\n if(colorsLength > 1) {\n colorSum = { r:0, g:0, b:0 };\n\n for(index = 0; index < colorsLength; index++) {\n alphaRatio = colors[index].a / alphaSum;\n\n colorSum.r += colors[index].r * alphaRatio;\n colorSum.g += colors[index].g * alphaRatio;\n colorSum.b += colors[index].b * alphaRatio;\n }\n\n data[i+0] = colorSum.r;\n data[i+1] = colorSum.g;\n data[i+2] = colorSum.b;\n data[i+3] = 255 - 255/((alphaSum+127)/127);\n\n counts[0]++;\n } else if (colorsLength > 0) {\n data[i+0] = colors[0].r;\n data[i+1] = colors[0].g;\n data[i+2] = colors[0].b;\n data[i+3] = 255 - 255/((colors[0].a+127)/127);\n\n counts[1]++;\n } else {\n data[i+3] = 0;\n\n counts[2]++;\n }\n } \n\n blender.putImageData(imageData, 0, 0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T02:51:27.167",
"Id": "29075",
"Score": "0",
"body": "You know what: I tried moving the variable declarations out of the loop but it seemed to make a neglible difference so I left them in favor of readability. However, I can't believe I didn't consider moving the calculation out of the `for` loop. I guess it's been so long since I've done anything this CPU intensive that I completely forgot this condition was recalculated on every iteration and took it for granted that it would only calculate it once. Thank you! Your answer was very detailed and well-written."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T03:49:30.193",
"Id": "29076",
"Score": "0",
"body": "@rrowland You're welcome. And yeah, the readability suffers. Under different circumstances, I'd advocate splitting things into several functions, which would of course make it easier on the eyes, but it'd make expression caching harder and (I suspect) introduce some heavy calling-overhead. I'm afraid you'll have to accept some long-winded functions and reduced readability in the interest of performance. However you can cache some things (like `mask.width*mask.height*4`) even earlier than at the top of the function, which would help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T01:57:44.597",
"Id": "18228",
"ParentId": "18205",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "18228",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T07:05:00.790",
"Id": "18205",
"Score": "5",
"Tags": [
"javascript",
"performance",
"jquery",
"canvas"
],
"Title": "Optimize iterative pixel blending function"
}
|
18205
|
<p>I want to give users help in which format they have to enter a date. The <code>label</code> content is: </p>
<blockquote>
<p>Date (YYYY-MM-DD)</p>
</blockquote>
<p>I used the following markup:</p>
<pre><code><label>Date (<kbd><abbr title="four-digit year">YYYY</abbr>-<abbr title="two-digit month">MM</abbr>-<abbr title="two-digit day">DD</abbr></kbd>)</label>
</code></pre>
<p>Note: the new HTML5 <code>input</code>-<code>type</code> values (like <code>date</code>) might be used, but this label is a fallback for users with older browsers. Most of them use screenreaders and I try to give the most nitty-gritty markup.</p>
<p>I wonder:</p>
<ul>
<li>Should I use the <a href="http://www.w3.org/TR/html5/the-code-element.html#the-code-element" rel="nofollow"><code>code</code> element</a>?</li>
<li>Is my use of the <a href="http://www.w3.org/TR/html5/the-kbd-element.html#the-kbd-element" rel="nofollow"><code>kbd</code> element</a> correct in this context? The "YYYY-MM-DD" <em>represents</em> something that users should enter, but it isn't something they should enter <em>exactly</em> as given, of course. It's more some kind of variable, I guess.</li>
<li>So maybe the <a href="http://www.w3.org/TR/html5/the-var-element.html#the-var-element" rel="nofollow"><code>var</code> element</a> might be appropiate?</li>
<li>Is my use of the <a href="http://www.w3.org/TR/html5/the-abbr-element.html#the-abbr-element" rel="nofollow"><code>abbr</code> element</a> correct?</li>
<li>Should I use the <a href="http://www.w3.org/TR/html5/the-dfn-element.html#the-dfn-element" rel="nofollow"><code>dfn</code> element</a> around each <code>abbr</code> element? So "YYYY" would be <em>defined</em> as year, because strictly spoken it is not an abbreviation for "four-digit year" but for "Year Year Year Year".</li>
</ul>
|
[] |
[
{
"body": "<p>There is little point in using <code>code</code> markup here. Technically, it might not be completely wrong “semantically”, since the YYYY-MM-DD notation is really meant for computers rather than human beings, but what would it achieve? Monospace font by default?</p>\n\n<p>Using <code>kbd</code> is equally, if not more, pointless.</p>\n\n<p>Using <code>var</code> might be “semantically” appropriate, since you are using placeholders of a kind. But, here, too, the question is: Why? Do you want some browsers to render the text in italics? What else would you achieve in practice?</p>\n\n<p>Using <code>abbr</code> is “semantically” wrong, since e.g. YYYY is not an abbreviation. It is a conventional notation. In practice, <code>abbr</code> creates by default a dotted bottom border on some borders. Why use some markup when the only real implication is that you get some default rendering that you don’t want?</p>\n\n<p>Using <code>dfn</code> would be equally wrong. You are not giving any definition for e.g. YYYY. Instead, you are implying a definition, i.e. assuming that the user knows what YYYY means.</p>\n\n<p>The <code>title</code> element is poor usability, but if you wish to use it, you can use it for a <code>span</code> element, which has no defined semantics (so it cannot be semantically wrong) and has no impact on default rendering.</p>\n\n<p>If you don’t think that the explanation ”(YYYY-MM-DD)” is not sufficient, the best approach is to explain it in normal content. E.g.,</p>\n\n<p>Date (YYYY-MM-DD, i.e. 4-digit year, hyphen, 2-digit month, hyphen, 2-digit day):</p>\n\n<p>Note that a <code>label</code> element that has neither a <code>for</code> attribute nor a form field as content is pointless. The <code>label</code> markup is useful only when used to associate a form field with its label text.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T20:10:40.960",
"Id": "18225",
"ParentId": "18222",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T19:01:18.460",
"Id": "18222",
"Score": "2",
"Tags": [
"html",
"html5"
],
"Title": "Markup \"YYYY-MM-DD\" as input hint"
}
|
18222
|
<p>In ruby, is there a more concise way of expressing multiple AND conditions in an if statement?</p>
<p>For example this is the code I have:</p>
<pre><code> if first_name.blank? and last_name.blank? and email.blank? and phone.blank?
#do something
end
</code></pre>
<p>Is there a better way to express this in Ruby? 1.9.2 or 1.9.3</p>
|
[] |
[
{
"body": "<pre><code>if [first_name, last_name, email, phone].all?(&:blank?)\n #do something\nend\n</code></pre>\n\n<p>Caveat: While <code>and</code>/<code>&&</code> short-circuit the expression (that's it, only the needed operands are evaluated), an array evaluates all its items in advance. In your case it does not seem something to worry about (they seem cheap attributes to get), but if you ever need lazy evaluation and still want to use this approach, it's possible using procs, just slightly more verbose:</p>\n\n<pre><code>p = proc\nif [p{first_name}, p{last_name}, p{email}, p{phone}].all? { |p| p.call.blank? }\n #do something\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T07:50:30.627",
"Id": "29084",
"Score": "0",
"body": "I received an undefined method 'all' on the code example above. See http://repl.it/D7X"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T08:02:40.870",
"Id": "29085",
"Score": "0",
"body": "@koa: `all?`. The enumerable methods are a must read (really, read and understand them one by one). http://ruby-doc.org/core-1.9.3/Enumerable.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T05:08:53.603",
"Id": "29315",
"Score": "0",
"body": "Sometimes the logic setting up a condition is the worst part of programming, and, after getting done, still won't look right. It's like staring at a word and it just doesn't look like it's spelled right, though you know it is. I generally try to go with whatever combination results in the most concise, yet readable, code for the long-term. After I get done writing it, it could be passed to several other programmers so I don't want them coming back later asking what-the-heck that code does. I've used `all?` against an array, and chains of `&&` and `||`, depending on what felt right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T11:32:09.213",
"Id": "29337",
"Score": "0",
"body": "@the Tin Man. Thanks for commenting. I think we had our differences in the past about how to write logic, didn't we? :-) I agree that it's hard to get it right, logic is so important (is there anything more important in an app?) that it deserves to invest time on it. For me the best logic is that which resembles mathematical logic, that uses no early \"return\"s, in-line conditionals, nor any other imperative stuff. Just the good old logic expressions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T14:03:25.757",
"Id": "29349",
"Score": "0",
"body": "When I was writing assembly language, Perl and C, I wrote my conditionals a lot more tersely and concisely. Languages like Ruby encourage a more expressive coding style, that tries to sit between a conversation with the computer, and cold-logic. I prefer conciseness over verbosity personally, but not everyone can deal with Perl-like code, so I try to adjust. In your answer above, your point about short-circuiting is important, especially as the list of conditions grows. Blindly looping over every element can become costly so `&&` and `||` become important."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T19:49:03.777",
"Id": "18224",
"ParentId": "18223",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18224",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T19:37:43.610",
"Id": "18223",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "Expressing multiple AND conditions in ruby"
}
|
18223
|
<p>I had this interview question like a year ago and was asked to code, on a piece of paper, how to reverse each word of a string. Since I am used to Java, I proposed the obvious answer of using split + reverse, which are native commands in Java. I was then told I couldn't use those, so I floundered and ended up with a really terrible solution (even though it technically would've worked). </p>
<p>Anyway, it was bugging me lately, so I gave it a shot in straight C, which I am not very good at, so it took me a good while to actually get it working.</p>
<p>I was wondering:</p>
<ol>
<li>Is this a good solution?</li>
<li>Have I forgotten anything obvious?</li>
<li>Have I done anything non-kosher in the C world?</li>
</ol>
<p>Again, I'm not very good at C, so even small points will probably help me out.</p>
<pre><code>#include <stdio.h>
void reverseString(char* start, char* end){
while (start < end){
char temp = *start;
*start = *end;
*end = temp;
++start;
--end;
}
}
char* word_start_index(char* p)
{
while((*p != '\0') && (*p == ' ')){
++p;
}
if(*p == '\0')
return NULL;
else
return p;
}
char* word_end_index(char* p)
{
while((*p != '\0') && (*p != ' ')){
++p;
}
return p-1;
}
void main(){
char arr[] = "kevin is a good programmer";
char* test = arr;
while (test != '\0'){
char* curWordStart = word_start_index(test);
if (curWordStart == NULL)
break;
char* curWordEnd = word_end_index(curWordStart);
reverseString(curWordStart, curWordEnd);
test = curWordEnd + 1;
}
printf("%s \n", arr);
}
</code></pre>
<p>Also, would taking a different approach, like in higher level languages of breaking the string into an array of strings (so I guess a 2D array of chars), then stepping through and reversing each one, be a good approach as well? I thought about this first and was unable to hash it out. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T12:19:32.663",
"Id": "29107",
"Score": "1",
"body": "Another thing that you need to consider is that words are not always terminated by a space. Punctuation also counts!.:,;?\nAnd, being awkward, what about numbers?"
}
] |
[
{
"body": "<p>I like it; nice and logical and easy to follow.</p>\n\n<p>The only change I would make is the test for space.</p>\n\n<pre><code>*p == ' '\n</code></pre>\n\n<p>I would replace this with</p>\n\n<pre><code>isspace(*p)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T04:31:21.573",
"Id": "18230",
"ParentId": "18229",
"Score": "4"
}
},
{
"body": "<p>I also met this question during a interview several years before, the string was null-terminated and separated by spaces.\nmy idea was same as yours, just save some lines of code, comments in line.</p>\n\n<pre><code>// Reverse the characters between pointer p and q\nvoid ReverseWord(char* p, char* q)\n{\n while(p < q)\n {\n char t = *p ;\n *p++ = *q ;\n *q-- = t ;\n }\n}\n\n\n// Reverse all words in a sentence.\nvoid ReverseSentence(char *s)\n{\n char *p = s ; // point to the start position of a word\n char *q = s ; // point to the end position of a word(white space or '\\0')\n\n while(*q != '\\0') // While string not ends\n {\n if (*q == ' ') // Get a word?\n {\n ReverseWord(p, q - 1) ;\n q++ ; // move to next word\n p = q ;\n }\n else\n q++ ;\n }\n\n ReverseWord(p, q - 1) ; // Reverse the last word\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T14:00:43.357",
"Id": "18248",
"ParentId": "18229",
"Score": "2"
}
},
{
"body": "<p>I have a few issues with in your code:</p>\n\n<ul>\n<li><p>Consistency in naming - use either camelCase or not_camel_case but don't\nmix</p></li>\n<li><p>consistency in braces. The opening brace for a function goes in the first\ncolumn.</p></li>\n<li><p><code>word_start_index</code> and <code>word_end_index</code> should take a <code>const</code> parameter</p></li>\n<li><p><code>word_start_index</code> is the same as <code>strspn(string, \" \");</code> or if you are also\nlooking for punctuation, <code>strspn(string, \" \\t\\n.,;:\");</code> </p></li>\n<li><p><code>word_end_index</code> - as for <code>word_start_index</code> but use <code>strcspn</code> (note the\n'c')</p></li>\n<li><p><code>word_end_index</code> as a function (ie not in your context) fails for an empty\nstring or a string starting with a space (it returns the char before the\nstring starts).</p></li>\n<li><p>variable <code>test</code> in <code>main()</code> is misnamed. I would prefer something that shows it\nis a string.</p></li>\n<li><p>the test <code>while (test != '\\0')</code> in <code>main()</code> is wrong - should be <code>*test !=\n'\\0'</code>.\nYour loop always exits from the <code>break</code></p></li>\n<li><p>no return or parameters in main()</p></li>\n</ul>\n\n<p>Also, arguably the position of the stars in your pointers is wrong. I prefer <code>char* p</code> to be written <code>char *p</code>, which makes it clear that it is p that takes the star. Consider code such as <code>char* a, b;</code>. This is bad because it gives the impression that b is a pointer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T15:11:39.767",
"Id": "29100",
"Score": "0",
"body": "Thanks for the comments! Do you think taking a different approach like in higher level languages of breaking the string into an array of string (so I guess a 2-d array of chars), then stepping through and reversing each one would be good approach as well? I thought about this first and was unable to hash it out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T15:16:44.863",
"Id": "29102",
"Score": "0",
"body": "No, your approach is fine"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T15:18:37.733",
"Id": "29103",
"Score": "0",
"body": "OK, thanks for the details, I was definitely unclear about how some of the pointers need to be declared and compared and had some trial and error there. The camel case issues were just a result of copy pasting a bit off the web, but again thanks for the help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-31T21:07:36.223",
"Id": "214545",
"Score": "0",
"body": "@WilliamMorris, hello, what is the benefit of changing the parameters to const? Thank you."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T15:02:53.543",
"Id": "18249",
"ParentId": "18229",
"Score": "5"
}
},
{
"body": "<p>Mine is also very similiar:</p>\n\n<pre><code>#include <stdio.h>\n#include <ctype.h>\n\nvoid reverse(char *p, char *q)\n{\n while (p<q)\n {\n char t = *p;\n *p++ = *q;\n *q-- = t;\n }\n}\n\nchar *reverse_each_word(char* str)\n{\n char *p, *q = str;\n while(*q)\n {\n p = q; while(*p && !isalnum(*p)) p++; // Skip non-word chars\n q = p; while(*q && isalnum(*q)) q++; // Skip word chars\n if(*p) reverse(p, q-1);\n } \n return str;\n}\n\nint main()\n{\n char str[] = \"An answer on http://codereview.stackexchange.com/questions/18229\";\n printf(\"%s\\n\", str);\n printf(\"%s\\n\", reverse_each_word(str)); \n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T15:31:53.790",
"Id": "18403",
"ParentId": "18229",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18249",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T02:14:19.597",
"Id": "18229",
"Score": "11",
"Tags": [
"c",
"beginner",
"strings",
"interview-questions"
],
"Title": "Reverse each word of a string in C"
}
|
18229
|
<p>Basically this code is for an upvote/downvote system and I'm basically</p>
<ul>
<li>Incrementing the count by 1 when voting up</li>
<li>Decrementing the count by 1 when voting down</li>
<li>If the number of downvotes > upvotes, we'll assume it's a negative score, so the count stays 0</li>
<li>Reverting the count back to what it originally was when clicking upvote twice or downvote twice</li>
<li>Never go below 0 (by showing negative numbers);</li>
</ul>
<p>Basically it's the same scoring scheme reddit uses, and I tried to get some ideas from the source which was minified and kind of hard to grok:</p>
<pre><code> a.fn.vote = function(b, c, e, j) {
if (reddit.logged && a(this).hasClass("arrow")) {
var k = a(this).hasClass("up") ? 1 : a(this).hasClass("down") ? -1 : 0, v = a(this).all_things_by_id(), p = v.children().not(".child").find(".arrow"), q = k == 1 ? "up" : "upmod";
p.filter("." + q).removeClass(q).addClass(k == 1 ? "upmod" : "up");
q = k == -1 ? "down" : "downmod";
p.filter("." + q).removeClass(q).addClass(k == -1 ? "downmod" : "down");
reddit.logged && (v.each(function() {
var b = a(this).find(".entry:first, .midcol:first");
k > 0 ? b.addClass("likes").removeClass("dislikes unvoted") : k < 0 ? b.addClass("dislikes").removeClass("likes unvoted") : b.addClass("unvoted").removeClass("likes dislikes")
}), a.defined(j) || (j = v.filter(":first").thing_id(), b += e ? "" : "-" + j, a.request("vote", {id: j,dir: k,vh: b})));
c && c(v, k)
}
};
</code></pre>
<p>I'm trying to look for a pattern, but there are a bunch of edge cases that I've been adding in, and it's still a little off.</p>
<p>My code (and <a href="http://jsfiddle.net/bHfFj/" rel="nofollow">fiddle</a>):</p>
<pre><code>$(function() {
var down = $('.vote-down');
var up = $('.vote-up');
var direction = up.add(down);
var largeCount = $('#js-large-count');
var totalUp = $('#js-total-up');
var totalDown = $('#js-total-down');
var totalUpCount = parseInt(totalUp.text(), 10);
var totalDownCount = parseInt(totalDown.text(), 10);
var castVote = function(submissionId, voteType) {
/*
var postURL = '/vote';
$.post(postURL, {
submissionId : submissionId,
voteType : voteType
} , function (data){
if (data.response === 'success') {
totalDown.text(data.downvotes);
totalUp.text(data.upvotes);
}
}, 'json');
*/
alert('voted!');
};
$(direction).on('click', direction, function () {
// The submission ID
var $that = $(this),
submissionId = $that.attr('id'),
voteType = $that.attr('dir'), // what direction was voted? [up or down]
isDown = $that.hasClass('down'),
isUp = $that.hasClass('up'),
curVotes = parseInt($that.parent().find('div.count').text(), 10); // current vote
castVote(submissionId, voteType);
// Voted up on submission
if (voteType === 'up') {
var alreadyVotedUp = $that.hasClass('likes'),
upCount = $that.next('div.count'),
dislikes = $that.nextAll('a').first(); // next anchor attr
if (alreadyVotedUp) {
// Clicked the up arrow and previously voted up
$that.toggleClass('likes up');
if (totalUpCount > totalDownCount) {
upCount.text(curVotes - 1);
largeCount.text(curVotes - 1);
} else {
upCount.text(0);
largeCount.text(0);
}
upCount.css('color', '#555').hide().fadeIn();
largeCount.hide().fadeIn();
} else if (dislikes.hasClass('dislikes')) {
// Voted down now are voting up
if (totalDownCount > totalUpCount) {
upCount.text(0);
largeCount.text(0);
} else if (totalUpCount > totalDownCount) {
console.log(totalDownCount);
console.log(totalUpCount);
if (totalDownCount === 0) {
upCount.text(curVotes + 1);
largeCount.text(curVotes + 1);
} else {
upCount.text(curVotes + 2);
largeCount.text(curVotes + 2);
}
} else {
upCount.text(curVotes + 1);
largeCount.text(curVotes + 1);
}
dislikes.toggleClass('down dislikes');
upCount.css('color', '#296394').hide().fadeIn(200);
largeCount.hide().fadeIn();
} else {
if (totalDownCount > totalUpCount) {
upCount.text(0);
largeCount.text(0);
} else {
// They clicked the up arrow and haven't voted up yet
upCount.text(curVotes + 1);
largeCount.text(curVotes + 1).hide().fadeIn(200);
upCount.css('color', '#296394').hide().fadeIn(200);
}
}
// Change arrow to dark blue
if (isUp) {
$that.toggleClass('up likes');
}
}
// Voted down on submission
if (voteType === 'down') {
var alreadyVotedDown = $that.hasClass('dislikes'),
downCount = $that.prev('div.count');
// Get previous anchor attribute
var likes = $that.prevAll('a').first();
if (alreadyVotedDown) {
if (curVotes === 0) {
if (totalDownCount > totalUp) {
downCount.text(curVotes);
largeCount.text(curVotes);
} else {
if (totalUpCount < totalDownCount || totalUpCount == totalDownCount) {
downCount.text(0);
largeCount.text(0);
} else {
downCount.text((totalUpCount - totalUpCount) + 1);
largeCount.text((totalUpCount - totalUpCount) + 1);
}
}
} else {
downCount.text(curVotes + 1);
largeCount.text(curVotes + 1);
}
$that.toggleClass('down dislikes');
downCount.css('color', '#555').hide().fadeIn(200);
largeCount.hide().fadeIn();
} else if (likes.hasClass('likes')) {
// They voted up from 0, and now are voting down
if (curVotes <= 1) {
downCount.text(0);
largeCount.text(0);
} else {
// They voted up, now they are voting down (from a number > 0)
downCount.text(curVotes - 2);
largeCount.text(curVotes - 2);
}
likes.toggleClass('up likes');
downCount.css('color', '#ba2a2a').hide().fadeIn(200);
largeCount.hide().fadeIn(200);
} else {
if (curVotes > 0) {
downCount.text(curVotes - 1);
largeCount.text(curVotes - 1);
} else {
downCount.text(curVotes);
largeCount.text(curVotes);
}
downCount.css('color', '#ba2a2a').hide().fadeIn(200);
largeCount.hide().fadeIn(200);
}
// Change the arrow to red
if (isDown) {
$that.toggleClass('down dislikes');
}
}
return false;
});
});
</code></pre>
<p>Pretty convoluted, right? Is there a way to do something similar but in about 1/3 of the code I've written? After attempting to re-write it, I find myself doing the same thing so I just gave up halfway through and decided to ask for some help (<a href="http://jsfiddle.net/U5Lbh/5/" rel="nofollow">fiddle of most recent</a>).</p>
|
[] |
[
{
"body": "<p>Don't use an A element for the up/down buttons, use a button or styled span element.</p>\n\n<p>The logic seems way more convoluted than necessary, consider something much simpler. The function below gets the original value, calculates the new value, then works out what to do with it. If it's within the range +/-1, it uses that value, otherwise it resets to the original value.</p>\n\n<p>Use classes instead of IDs so that the function can be generic. I don't use jQuery, you can convert the logic if you want. This is dependent on the client having getElementsByClassName, it's pretty easy to add if it's missing. There are a few support functions at the start, they're simple and you should have your own small library of such functions already.</p>\n\n<pre><code>// Support functions\nfunction hasClass(el, cName) {\n var re = new RegExp('(^|\\\\s)' + cName + '(\\\\s|$)');\n return re.test(el.className);\n}\n\nfunction getText(el) {\n if (typeof el.textContent == 'string') {\n return el.textContent;\n } else if (typeof el.innerText == 'string') {\n return el.innerText;\n }\n}\n\nfunction setText(el, text) {\n if (typeof el.textContent == 'string') {\n el.textContent = text;\n } else if (typeof el.innerText == 'string') {\n el.innerText = text;\n }\n} \n\n// Add listeners onload \nwindow.onload = function() {\n var voteEls = document.getElementsByClassName('thingToBeVotedOn');\n\n for (var i=0, iLen=voteEls.length; i<iLen; i++) {\n voteEls[i].onclick = handleClick;\n }\n\n function handleClick(evt) {\n evt = evt || window.event;\n var node, scoreNode, originalScore, currentScore, newScore, diff;\n var el = evt.target || evt.srcElement;\n var increment = hasClass(el, 'up')? 1 : \n hasClass(el, 'down')? -1 :\n 0; // default\n\n // Thing to be voted on is the button's parentNode\n // Only do something if there is an increment\n if (increment) {\n node = el.parentNode;\n scoreNode = node.getElementsByClassName('count')[0];\n originalScore = Number(node.getAttribute('data-originalValue'));\n currentScore = Number(getText(scoreNode)) || 0;\n newScore = currentScore + increment;\n diff = Math.abs(originalScore - newScore);\n\n // Can't go more than + or - 1\n if (diff > 1) {\n newScore = originalScore;\n }\n\n // Set new displayed value\n setText(scoreNode, newScore);\n } \n }\n}\n</script>\n\n<div class=\"thingToBeVotedOn\" data-originalValue=\"6\">\n <div class=\"count\">6</div>\n <button class=\"up\">Up</button>\n <button class=\"down\">Down</button>\n</div>\n</code></pre>\n\n<p>There are many ways to do this, the above is just an example that you can apply as you wish. You can add and remove classes to change the appearance of nodes based on what happens in side the <code>if (increment)</code> block.</p>\n\n<p>I would think that clicking on \"up\" or \"down\" a second time should just be ignored, if a user wants to remove their up vote, they just click down and vice versa. Anyway, this works as you've asked.</p>\n\n<p>The code can be more concise, but I prefer clarity over brevity. The original is awful from a code maintenace perspective.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T17:27:34.417",
"Id": "29111",
"Score": "0",
"body": "Thanks for such a quick response. This looks 100x better than what I was currently doing. My primary goal is maintenance so I like how you abstracted this into one handle method. +1 on Math.abs() as well for keeping the integers positive. Seems to work pretty nicely. Offtopic but I think I found my new favorite stackexchange site. Much appreciated :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T06:36:09.603",
"Id": "18234",
"ParentId": "18231",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18234",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T05:03:21.510",
"Id": "18231",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Tips on how to refactor this unwieldy upvote/downvote code"
}
|
18231
|
<p>Here is a class that executes the <code>CreateAPerson</code> use case. It takes a request object (which is a simple data structure), validates the request, creates a new person, and then returns a response object (another simple data structure).</p>
<p>For testability, I've created a setter that allows me to inject a mocked entity manager (I'm using Doctrine for persistence).</p>
<p>I realize this is rather simple, but do you see any red flags on the testability of this code?</p>
<pre><code><?php
namespace Stratus\UseCase\CreateAPerson;
class Interactor
{
protected $entityManager;
function __construct()
{
$doctrine = new \Stratus\Repository\Doctrine();
$this->entityManager = $doctrine->getManager();
}
public function execute(Request $request)
{
if (!$request->isValid())
throw new \Stratus\Exception\InvalidRequestException('Request did not pass validation.');
$person = new \Stratus\Entity\Person();
$person->setFirstName($request->firstName);
$this->entityManager->persist($person);
$response = new Response();
$response->id = $person->getID();
return $response;
}
public function setEntityManager($entityManager)
{
$this->entityManager = $entityManager;
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Constructor injection</h2>\n\n<p>Use constructor injection becouse this is the best way to write well readable and testable code. If you don't need a Doctrine instance in your class then don't use it.</p>\n\n<pre><code>public function __construct($entityManager)\n {\n $this->setEntityManager($entityManager);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T05:56:09.303",
"Id": "18233",
"ParentId": "18232",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T05:42:15.353",
"Id": "18232",
"Score": "2",
"Tags": [
"php",
"design-patterns",
"unit-testing",
"doctrine"
],
"Title": "Use case interactor"
}
|
18232
|
<p>I'm trying to see if there is a loop I can use in order to pull off this code a little more elegantly. I was previously using a <code>foreach($row as $cell)</code> with <code>$row = mysqli_fetch_row($result)</code> but because of that I couldn't access the data from the 'user' column in order to check it against the session variables in the if statment. Here's the code:</p>
<pre><code>$sql = "SELECT * FROM tbl_name ORDER BY subject, description LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME RESULTS:</h1>";
echo "<table border='0'>";
while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>".$row['subject']."</td>";
echo"<td>".$row['description']."</td>";
echo"<td>".$row['user']."</td>";
if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
echo"<td>You can delete this</td>";
}
else{
echo"<td>Code didn't work</td>";
}
echo "</tr>\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no results!';
}
?>
</code></pre>
<p>Is there a loop I can run that can also allow me to access data from each row so I don't have to print out a new line of code for each column but keep the if statement in tact? Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T07:44:26.177",
"Id": "29083",
"Score": "0",
"body": "You have not mentioned the structure of $result. You must be able to iterate the result set using foreach as you already tried before. Inside loop make sure you are pointing to data using correct index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T14:25:13.377",
"Id": "29096",
"Score": "0",
"body": "Ah sorry, I've added more code. $result is a query from a specific MySQL table."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T14:27:14.747",
"Id": "29098",
"Score": "0",
"body": "What you've mentioned is exactly what I'm trying to do but I suppose I'm confusing on the syntax of that. That's the idea I have in my head but am not exactly sure how it is pulled off."
}
] |
[
{
"body": "<h2>Mysqli_* functions or PDO</h2>\n\n<p>I would recommend you start using <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow\">PDO</a>, here is a good <a href=\"http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/\" rel=\"nofollow\">tutorial</a> for it. If you insist on using <code>mysqli_*</code> the correct way is using <code>foreach($row as $cell)</code> as you already tried. Dunno why it didn't work for you then.</p>\n\n<h2>Sample PDO code</h2>\n\n<pre><code>$host = 'localhost';\n$dbname = 'database1';\n$user = 'user1';\n$pass = 'password1';\n\ntry {\n # MySQL with PDO_MYSQL\n $dbh = new PDO(\"mysql:host=$host;dbname=$dbname\", $user, $pass);\ncatch(PDOException $e) {\n echo $e->getMessage();\n}\n\n$sth = $dbh->query('SELECT * FROM tbl_name ORDER BY subject, description LIMIT :startpoint, :limit');\n$sth->bindParam(':startpoint', $startpoint);\n$sth->bindParam(':limit', $limit);\n\n$sth->setFetchMode(PDO::FETCH_ASSOC);\nwhile($row = $sth->fetch()) {\n echo $row['subject'] . \"<br />\";\n echo $row['description'] . \"<br />\";\n echo $row['user'] . \"<br />\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T18:59:38.993",
"Id": "18624",
"ParentId": "18236",
"Score": "0"
}
},
{
"body": "<p>I would compare $user_id instead of the user's full name. What if you have two John Smiths?</p>\n\n<p>If you use this to fetch your array:</p>\n\n<pre><code>$row = mysqli_fetch_array($result, MYSQLI_ASSOC); // Get row as associative array\n</code></pre>\n\n<p>then for each row, you can do this:</p>\n\n<pre><code>echo '<tr>';\nforeach ($row as $cell_key => $cell_value) \n{\n echo '<td>'; // Single quotes because you don't need to eval the string\n\n if ($cell_key == 'user') \n {\n if ($cell_value == $_SESSION['firstname'] . ' ' . $_SESSION['lastname'])\n {\n echo 'You can delete this';\n }\n else\n {\n echo 'Code didn\\'t work';\n }\n } \n else \n {\n echo $cell_value;\n }\n\n echo '</td>'; // Single quotes because you don't need to eval the string\n\n}\n\necho '<tr/>'; // Again single quoted, etc.\n\n// And if you want to refer to a *specific* row here, you can just $row['name'] for example, yeah? That var is still available.\n</code></pre>\n\n<p>If the order of the columns isn't to your taste, don't <code>SELECT *</code>, select specific column names in the order you want them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-15T08:37:38.783",
"Id": "20535",
"ParentId": "18236",
"Score": "0"
}
},
{
"body": "<p>Saving lines of code in search of elegance is not always (in fact hardly ever in my experience) a worthwhile exercise if it comes at the expense of clarity and maintainability. Your current code is better than any solution that iterates over table columns because it is clear and easy to change. For example, combining the data of two columns into one or changing column order are both trivial.</p>\n\n<p>You might consider moving this display logic to a template. Here is an example of a <a href=\"http://twig.sensiolabs.org/documentation\" rel=\"nofollow\">twig</a> template:</p>\n\n<pre><code>{% if results %}\n<h1>HERE ARE SOME RESULTS</h1>\n<table>\n {% for row in results %}\n <tr>\n <td>{{ row.subject }}</td>\n <td>{{ row.description }}</td>\n {% if row.user == user %}\n <td>You can delete this</td>\n {% else %}\n <td>Code didn't work</td>\n {% endif %}\n </tr>\n {% endfor %}\n</table>\n{% else %}\n<p>No results</p>\n{% endif %}\n</code></pre>\n\n<p>The PHP becomes very simple:</p>\n\n<pre><code>$bindings = array(\n 'results' => $mysqli->query('SELECT...'),\n 'user' => $_SESSION['firstname'] . ' ' . $_SESSION['lastname']\n);\n$twig->render('template.html', $bindings);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T14:45:59.837",
"Id": "34871",
"Score": "0",
"body": "No please, don't use a template engine. PHP **is** a template engine."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-15T12:21:04.093",
"Id": "20540",
"ParentId": "18236",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20540",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T07:14:29.533",
"Id": "18236",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "Trying to Find a Loop to use for a specific MySQL query"
}
|
18236
|
<p>I think my code has too many functions... can it be written better?</p>
<p>Please help reviewing my jQuery functions.</p>
<h1>HTML</h1>
<pre><code><div class="event_owner">
<p>
<label for="xxx">xxx</label>
<input type="radio" name="event_owner" id="xxx">
</p>
<p>
<label for="yyy">yyy</label>
<input type="radio" name="event_owner" id="yyy">
</p>
<input type="text" name="_event_owner[name]" autocomplete="off" value="">
</div>
</code></pre>
<h1>jQuery</h1>
<pre><code>$(".event_owner").click(function(){
$(".event_owner input[type='text']").val($('.event_owner :radio:checked').attr("id"));
$('.event_owner p').css({"opacity":"1"});
$('.event_owner input').not(":checked").parent("p").css({"opacity":"0.3"});
});
// when page loaded and input(radio) saved
if($(".event_owner input[type='text']").length) {
$("input[id="+$(".event_owner input[type='text']").val()+"]").attr("checked","checked");
$('.event_owner input').not(":checked").parent("p").css({"opacity":"0.3"});
}
</code></pre>
<h1>Playground</h1>
<p><a href="http://jsfiddle.net/Zf4UE/" rel="nofollow">http://jsfiddle.net/Zf4UE/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T03:13:03.407",
"Id": "29137",
"Score": "3",
"body": "I'm wondering what you're trying to accomplish. You set the value of the text field with the radio buttons, but what if someone just writes something else in the field? Now the field no longer matches the selected radio button, and may be entirely invalid. So I'm not sure how it's supposed to work."
}
] |
[
{
"body": "<p>There are a few points worth mentioning:</p>\n\n<ol>\n<li><p>Your code does not actually function the way you want it to.<br>\n<code>$(\".event_owner input[type='text']\").length</code> checks for the existence of that element, not whether its value is set.</p></li>\n<li><p>Your radio buttons don't have a <code>value</code> attribute on them. They really should.</p></li>\n<li><p>You should cache your selectors. You're querying for <code>.event_owner</code> a total of 7 times in your code, and an additional 4 times on every click.</p></li>\n<li><p>Instead of listening for every click inside <code>.event_owner</code>, you should instead only listen for the <code>change</code> event of the radio buttons.</p></li>\n<li><p>On page load, if there's a value in the input text field, all we have to do is check the correct radio button. The <code>change</code> event listener will take care of the rest.</p></li>\n</ol>\n\n<p>With the above in mind, here's some sample code you might consider:</p>\n\n<pre><code>var $wrapper = $('.event_owner'),\n $textInput = $wrapper.find('input[type=\"text\"]'),\n $radios = $wrapper.find('input[type=\"radio\"]'),\n owner = $textInput.val();\n\n$radios.on( 'change', function () {\n $textInput.val( $radios.filter(':checked').val() );\n $radios.each(function () {\n $(this).closest('p').css( 'opacity', this.checked ? 1 : .3 );\n });\n});\n\nif ( owner ) $radios.filter('#' + owner).prop('checked', true);\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/Zf4UE/8/\" rel=\"nofollow\">http://jsfiddle.net/Zf4UE/8/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T02:09:08.953",
"Id": "18274",
"ParentId": "18239",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "18274",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T08:37:48.073",
"Id": "18239",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Playing with radio input"
}
|
18239
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.