body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Is there a way to make this more pythonic?</p>
<pre><code>def money():
current_salary = float(input("What is your current salary? "))
years = int(input("How many years would you like to look ahead? "))
amount_of_raise = float(input("What is the average percentage raise you think you will get? ")) * 0.01
for years in range(1, years + 1):
current_salary += current_salary * amount_of_raise
print('Looks like you will be making', current_salary,' in ', years,'years.')
money()
</code></pre>
|
[] |
[
{
"body": "<p>Maybe you could write: </p>\n\n<p>Instead of <code>print('Looks like you will be making', current_salary,' in ', years,'years.')</code> you could write <code>print('Looks like you will be making %d in %d years.') % (current_salary, years)</code></p>\n\n<p>Also, and this one is kind of important, you should check the input before converting it to an <code>int</code> or <code>float</code> (maybe the user goes crazy and throws a string just for the fun of it). You could maybe do that with a <code>try: ... except:</code> block.</p>\n\n<p>And just to be nitpicky, what's your position on quotes? Do you use single or you use double?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-06T23:09:44.183",
"Id": "44061",
"Score": "0",
"body": "Your first point seems to have missed that he's using the variable years in the output. So your suggestions don't seem to make sense there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-06T23:18:32.793",
"Id": "44062",
"Score": "0",
"body": "You're right, sorry about that. Edited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T02:57:00.980",
"Id": "44072",
"Score": "0",
"body": "Hi Paul, I actually do plan to add in a type check as I'm a fan of error checking I just haven't done that yet. I just like to write efficient code and make checks along the way. So regarding the quotes, I don't really have a position. Even though I say that, if I'm right, to quote within there I would have to use double and single quotes so I am probably more likely to use double and then use single as necessary. I'm REALLY new to all of this so I appreciate your input."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-06T22:59:09.947",
"Id": "28209",
"ParentId": "28208",
"Score": "2"
}
},
{
"body": "<p>Not sure if that it would make things more pythonic but here are 2 comments to make things less awkward.</p>\n\n<p>You might want to rename your variable name in <code>for years in range(1, years + 1):</code> for something like <code>for year in range(1, years + 1):</code>.</p>\n\n<p>It might make sense to use an additional variable to make things slighly clearer in your calculations:</p>\n\n<pre><code>def money():\n # TODO : Add error handling on next 3 lines\n current_salary = float(input(\"What is your current salary? \"))\n years = int(input(\"How many years would you like to look ahead? \"))\n amount_of_raise = float(input(\"What is the average percentage raise you think you will get? \"))\n coeff = 1 + amount_of_raise * 0.01\n\n for year in range(1, years + 1):\n current_salary *= coeff\n print('Looks like you will be making', current_salary,' in ', year,'years.')\nmoney()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T00:56:43.977",
"Id": "28211",
"ParentId": "28208",
"Score": "2"
}
},
{
"body": "<ul>\n<li>As others have noted, you'll probably want to do some error-checking on your inputs, which means writing a helper function to handle your prompts.</li>\n<li>You're writing a program that handles money and using binary floats, which are designed for scientific calculations. You are likely to run into a variety of small calculation errors! Python has a decimal module for calculations involving money. This will also make your input-handling easier.</li>\n<li>Don't reuse \"years\" as the iterator in the for loop when you already have a variable with that name. It works here, but only by luck.</li>\n<li>Prefer the format() method to straight concatenation. In this case it allows you to easily print your numbers with comma separators.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>from decimal import * \n\ndef get_decimal(prompt):\n while True:\n try:\n answer = Decimal(input(prompt + \" \"))\n return answer\n except InvalidOperation:\n print(\"Please input a number!\")\n\ndef money():\n current_salary = get_decimal(\"What is your current salary?\")\n years = int(get_decimal(\"How many years would you like to look ahead?\"))\n percent_raise = get_decimal(\"What is the average percentage raise you think you will get?\") * Decimal(\"0.01\")\n for year in range(1, years+1):\n current_salary += percent_raise * current_salary\n line = \"Looks like you will be making ${0:,.2f} in {1} years.\".format(current_salary, year)\n print(line)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T16:41:12.663",
"Id": "44184",
"Score": "0",
"body": "`from <module> import *` is discouraged because it can cause namespace collisions and gives static analyzers a hard time determining where a name originates from. `from decimal import Decimal` is better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T04:35:25.867",
"Id": "28220",
"ParentId": "28208",
"Score": "4"
}
},
{
"body": "<p>I would use a docstring and split the method to even smaller ones</p>\n\n<pre><code>def money():\n \"\"\"Print Expectations on Salary\"\"\"\n salary, delta, perc_raise = get_user_input()\n expectations = calculate_expectations(salary, delta, perc_raise)\n print_expectations(expectations)\n\nmoney()\n</code></pre>\n\n<p>And I would store the expectations in a List</p>\n\n<pre><code>def calculate_expectations(salary, delta_max, perc_raise):\n \"\"\"Calculate Expectations on Salary\"\"\"\n [salary*(1+perc_raise/100)**delta for delta in range(1, delta_max + 1)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T10:09:46.903",
"Id": "44227",
"Score": "0",
"body": "@codesparcle Thank you for the hint. I've edited my answer and renamed the variable to perc_raise."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T16:18:03.637",
"Id": "28230",
"ParentId": "28208",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-06T22:09:19.470",
"Id": "28208",
"Score": "2",
"Tags": [
"python"
],
"Title": "Calculate cumulative salary including raises"
}
|
28208
|
<p>I wrote this program for an exercise in Bjarne Stroustrup's text Programming -- <em>Principles and Practice Using C++</em>. He recommended using a <code>vector</code> for pseudo randomness, however I opted for <code>srand()</code> and <code>rand()</code> from <code>cstdlib</code>.</p>
<p>Any recommendations regarding efficiency or simplification would be greatly appreciated. I apologize in advance for the nested switch statements. After much thought, I could not come up with a better solution. The exercise is as follows:</p>
<blockquote>
<p>Write a program that plays the game "Rock, Paper, Scissors." If you are
not familiar with the game do some research (e.g., on the web using
Google). Research is a common task for programmers. Use a switch statement
to solve this exercise. Also, the machine should give random
answers (i.e., select the next rock, paper, or scissors randomly). Real randomness
is too hard to provide just now, so just build a vector with a sequence
of values to be used as "the next value." If you build the vector
into the program, it will always play the same game, so maybe you
should let the user enter some values. Try variations to make it less easy
for the user to guess which move the machine will make next.</p>
</blockquote>
<pre><code>#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
void show_winner(char user_move, char comp_move)
{
using namespace std;
switch (user_move) {
case 'r':
switch (comp_move) {
case 'r':
cout << "User: Rock" << endl;
cout << "Computer: Rock" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Tie!" << endl;
break;
case 'p':
cout << "User: Rock" << endl;
cout << "Computer: Paper" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Computer Wins! Paper Beats Rock!" << endl;;
break;
case 's':
cout << "User: Rock" << endl;
cout << "Computer: Scissor" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "User Wins! Rock Beats Scissor!";
break;
}
break;
case 'p':
switch (comp_move) {
case 'r':
cout << "User: Paper" << endl;
cout << "Computer: Rock" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "User Wins! Paper Beats Rock!" << endl;
break;
case 'p':
cout << "User: Paper" << endl;
cout << "Computer: Paper" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Tie!" << endl;
break;
case 's':
cout << "User: Paper" << endl;
cout << "Computer: Scissor" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Computer Wins! Scissor Beats Paper!" << endl;
break;
}
break;
case 's':
switch (comp_move) {
case 'r':
cout << "User: Scissor" << endl;
cout << "Computer: Rock" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Computer Wins! Rock Beats Scissor";
break;
case 'p':
cout << "User: Scissor" << endl;
cout << "Computer: Paper" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "User Wins! Scissor Beats Paper!" << endl;
break;
case 's':
cout << "User: Scissor" << endl;
cout << "Computer: Scissor" << endl;
cout << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Tie!" << endl;
break;
}
break;
}
}
void countdown()
{
using namespace std;
// Print countdown, and wait one second after
// each statement prints.
cout << "Rock..." << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Paper..." << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << "Scissor..." << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
cout << endl;
cout << "SHOOT!" << endl;
for (time_t t = time(0) + 1; time(0) < t;) {}
}
char get_comp()
{
// Seed the RNG
srand(time(NULL));
// Divide the random int by 3 and assign its
// remainder to a variable.
int c_num = rand() % 3;
// Assign a move to the computer's random number.
char c_move;
switch (c_num) {
case 0:
c_move = 'r';
break;
case 1:
c_move = 'p';
break;
case 2:
c_move = 's';
break;
}
// Return the Computer's Move
return c_move;
}
char get_user()
{
using namespace std;
// Get the user's move
char move;
cout << "Enter your move (Rock = r , Paper = p , Scissor = s):" << endl;
cin >> move;
cout << endl;
// Return the chosen move to the main function
return move;
}
int main()
{
using namespace std;
while (true) {
// Get the user's move
char user_move = get_user();
// Get the computer's move
char comp_move = get_comp();
// Print the countdown dialogue
countdown();
cout << endl;
// Declare a winner
show_winner(user_move, comp_move);
for (time_t t = time(0) + 1; time(0) < t;) {}
/* Prompt the user to play another round.
* Any input besides "yes","Yes","y", or "Y"
* will break out of the main loop. */
string again;
cout << endl;
cout << "Enter Y to Play Again" << endl;
cin >> again;
if (again == "Y") {}
else break;
cout << endl;
}
// Main Function Return
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>. Using it in local scope (such as a function) is better than having it in global scope, but it's still quite repetitive to have it in multiple ones.</p></li>\n<li><p>Only call <code>std::srand()</code> <em>once</em> in <code>main()</code>, preferably at the very top, otherwise your random values will always be the same.</p></li>\n<li><p>You can greatly simplify <code>get_comp()</code> by having an <code>enum</code> for the moves and returning one based on an acquired random number:</p>\n\n<pre><code>enum Move { ROCK, PAPER, SCISSORS };\n\n// ...\n\nMove get_comp()\n{\n return std::rand() % 2;\n}\n</code></pre></li>\n<li><p>Your loop in <code>main()</code> makes little sense. Here's an alternative:</p>\n\n<pre><code>do\n{\n // play the game...\n\n std::cout << \"Enter 'Y' to play again: \";\n char again;\n std::cin >> again;\n} while (toupper(again) == 'Y');\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T01:38:11.173",
"Id": "28218",
"ParentId": "28212",
"Score": "2"
}
},
{
"body": "<p>As a general comments, your comments are not really helpful as they explain the how instead of the why. If you were to split your code into smaller functions and to use relevant types, most of them would not be required. You could also use the <code>const</code> keywords to tell the reviewer and/or the compiler that variables are not supposed to be updated.</p>\n\n<p>As suggested by Jamal, an enum could make things clearer : let's define : <code>enum Moves {ROCK, PAPER, SCISSORS};</code></p>\n\n<p>Then you could reuse this type everywhere :</p>\n\n<pre><code>Move get_random_move()\n{\n return rand() % 3;\n}\n\nMove get_user_move()\n{\n for (;;)\n {\n cout << \"Enter your move (Rock = r , Paper = p , Scissor = s):\" << endl;\n char move;\n cin >> move;\n cout << endl;\n switch (move)\n {\n case 's': return SCISSORS;\n case 'p': return PAPER;\n case 'r': return ROCK;\n default : cout << \"Invalid input, please try again.\" << endl;\n }\n}\n</code></pre>\n\n<p>It would probably be worth extracting <code>for (time_t t = time(0) + 1; time(0) < t;) {}</code> into a function.</p>\n\n<p>You should add a <code>cout << endl;</code> at the end of the <code>countdown()</code> function in order not to have to do it after you've called it.</p>\n\n<p>Your <code>show_winner</code> functions does way too much : you should have a function handling the printing and one handling the computation of the winning player.</p>\n\n<pre><code>void get_winner(Move m1, Move m2)\n{\n # Implementation to update if we update the order in the enum\n # Here we get the winner by computing the \"distance\" between the moves if we were to cycle on the enum in a given order.\n return (3+m1-m2)%3; # 0 is tie, 1 is move 1, 2 is move 2\n}\n\nostream& operator<<(ostream& out, const Move &m)\n{\n switch (m)\n {\n case SCISSORS: out << \"Scissors\"; break;\n case ROCK: out << \"Rock\"; break;\n case PAPER: out << \"Paper\"; break;\n default: out << \"Invalid move\";\n }\n\n return out;\n}\n</code></pre>\n\n<p>Then your main would be like :</p>\n\n<pre><code>int main()\n{\n srand(time(NULL));\n while (true) {\n const Move user = get_user_move();\n const Move comp = get_random_move();\n\n countdown(); \n\n cout << \"User: \" << user << endl;\n cout << \"Computer: \" << comp << endl << endl;\n\n sleep(1);\n switch(get_winner(user,comp))\n {\n case 0: cout << \"Tie!\" << endl; break;\n case 1: cout << \"User wins, \" << user << \" beats \" << comp << endl; break;\n case 2: cout << \"Computer wins, \" << comp << \" beats \" << user << endl; break;\n }\n\n sleep(1); \n\n /* Prompt the user to play another round.\n * Any input besides \"yes\",\"Yes\",\"y\", or \"Y\"\n * will break out of the main loop. */ \n // Note from Josay : the comment just above is probably wrong\n string again;\n cout << endl << \"Enter Y to Play Again\" << endl;\n cin >> again; \n if (again == \"Y\") {}\n else break;\n\n cout << endl;\n } \n return 0; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T05:39:08.493",
"Id": "44078",
"Score": "1",
"body": "Surely the `srand` call in the `get_random_move` function is wrong. You should call `srand` once, at the beginning of `main`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T05:46:01.270",
"Id": "44079",
"Score": "1",
"body": "Your output operator. The parameter `m` is not used. There is no `return` statement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T02:12:30.017",
"Id": "28219",
"ParentId": "28212",
"Score": "3"
}
},
{
"body": "<p>Rather than have big switch statements. You use a matrix of valid results:</p>\n\n<pre><code> User Move -> Rock Paper Scissor\n Comp Move \\/\n\n Rock Tie User-Win Comp-Win\n Paper Comp-Win Tie User-Win\n Scissor User-Win Comp-Win Tie\n</code></pre>\n\n<p>This implies we should use <code>enum</code> </p>\n\n<pre><code> enum Weapon {Rock, Paper, Scissor};\n enum Result {Tie, Comp_Win, User_Win};\n</code></pre>\n\n<p>To make printing it easier add the appropriate output operators:</p>\n\n<pre><code> std::ostream& operator<<(std::ostream& s, Weapon w)\n {\n return s << ((w == Rock) ? \"Rock\" : (w == Paper) ? \"Paper\" : \"Scissor\");\n }\n std::ostream& operator<<(std::ostream& s, Result r)\n {\n return s << ((r == Tie) ? \"Tie\" : (r == Comp_Win) ? \"Comp_Win\" : \"User_Win\");\n }\n</code></pre>\n\n<p>Now we can define the result matrix like this:</p>\n\n<pre><code> Result actionMatric[3][3] = [[Tie, User_Win, Comp_Win],\n [Comp_Win, Tie, User_win],\n [User_Win, Comp_Win, Tie]];\n\n void show_winner(Weapon user, Weapon comp)\n {\n // Notice don't use std::endl unless you want to flush the output.\n // If you use std::endl all the time you waste the buffer that is being used\n // to make the stream effecient.\n std::cout << \"User: \" << user << \"\\n\"\n << \"Computer: \" << comp << \"\\n\"\n << std::endl;\n for (time_t t = time(0) + 1; time(0) < t;) {} \n std::cout << actionMatric[user][comp] << std::endl;\n }\n</code></pre>\n\n<p>Don't use a busy wait() to sleep.</p>\n\n<pre><code>for (time_t t = time(0) + 1; time(0) < t;) {}\n\n// Prefer: one of these.\n// Usually for multi-platform code you macro out these\nsleep(1); // Unix\nSleep(1000); // Win \n</code></pre>\n\n<p>Only seed the random number generator once in a game:</p>\n\n<pre><code>srand(time(NULL));\n</code></pre>\n\n<p>Easiest to right after main() is entered.</p>\n\n<p>You don't need a switch to convert a random number to a value. You can calculate it (or with enum cast it).</p>\n\n<pre><code>Weapon compWeapon = static_cast<Weapon>(rand() % 3);\n</code></pre>\n\n<p>Don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:04:54.743",
"Id": "44105",
"Score": "2",
"body": "I don't know until now that paper is weapon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T22:05:26.557",
"Id": "44133",
"Score": "4",
"body": "@AlvinWong: Never heard of a paper cut?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T05:41:40.940",
"Id": "28221",
"ParentId": "28212",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "28221",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T01:12:48.937",
"Id": "28212",
"Score": "5",
"Tags": [
"c++",
"beginner",
"game",
"rock-paper-scissors"
],
"Title": "Simplification and efficiency suggestions for \"Rock, Paper, Scissors\" game"
}
|
28212
|
<p>Yes, I know there are plenty of libraries to get this done (Q, step, async), but only for learning I'm wondering if the following code is ok and usable or have major drawbacks and it is only usable at a small programs.</p>
<p>Usage:</p>
<pre><code>var g = new Manager();
g.then (
function() {
console.log("hello");
setTimeout( function () { g.done("hello done") }, 2000 );
}
);
g.start();
g.then (
function() {
console.log("two");
g.done ("two done");
}
);
g.then (
function(resp) {
console.log("I got: " + resp);
setTimeout( function () { g.done("happy ending") }, 2000 );
}
);
g.then (
function(resp) {
console.log("last msg: " + resp);
g.done();
}
);
</code></pre>
<p>Class:</p>
<pre><code>//...............................
// class Manager
//...............................
function Manager () {
this.functionList = [];
this.allDone = false;
} // ()
//...............................
//...............................
Manager.prototype.then = function (fun) {
this.functionList.push (fun);
if (this.allDone) {
this.allDone = false;
this.done(this.previousResult);
console.log ( "then(): continuing");
}
} // ()
//...............................
//...............................
Manager.prototype.done = function (prevRes) {
this.previousResult = prevRes;
if ( this.where <= this.functionList.length-2 ) {
this.where++;
this.functionList [this.where](this.previousResult);
} else {
this.allDone = true;
console.log ( "done(): stopping because allDone: where=" + this.where + " and length = " + this.functionList.length);
}
} // ()
//...............................
//...............................
Manager.prototype.start = function () {
this.allDone = false;
this.where=-1;
this.done();
} // ()
</code></pre>
|
[] |
[
{
"body": "<p>Some points:</p>\n\n<ul>\n<li><code>g.then(function() { … g.done (\"two done\");})</code> I (personally) don't like that signature, I'm more used to callbacks that get passed as parameters (<code>g.then(function(done) { … done (\"two done\");})</code>). They tend make the chained functions better reusable - in your case it might not matter since you're using dedicated function expressions anyway which are bound to <code>g</code>. And your signature simplifies argument handling in the <code>Manager</code> :-)</li>\n<li><code>this.allDone = false;</code> seems to be a misnomer for me. The way you're using it, it should rather be called <code>startedAndNotRunning</code>. Technically if you're initialising the empty list they are all done already :-)</li>\n<li><p>This is highly confusing:</p>\n\n<pre><code>if ( this.where <= this.functionList.length-2 ) { \n this.where++;\n …\n</code></pre>\n\n<p>What happens to the last two functions? Nothing special. It better is written</p>\n\n<pre><code>this.where++;\nif (this.where < this.functionList.length) {\n …\n</code></pre>\n\n<p>Then the iterator variable (<code>where</code>) will become the <code>length</code> of the array after the \"loop\", which is the common behaviour. Yet, you cannot use <code>done</code> any more to [re]start the chain - you'd need to decrement <code>where</code> before. Therefore I'd recommend to restructure the methods to</p>\n\n<pre><code>function Manager () {\n …\n this.where = 0;\n}\nManager.prototype.start = function () {\n // you might reset allDone and where\n this.next();\n};\nManager.prototype.done = function (prevRes) { \n this.previousResult = prevRes;\n this.where++;\n this.next();\n};\nManager.prototype.next = function() {\n if (this.where < this.functionList.length)\n this.functionList[this.where](this.previousResult);\n else { \n this.allDone = true;\n console.log ( \"done(): stopping at where=\" + this.where + \" with length = \" + this.functionList.length);\n }\n};\nManager.prototype.then = function (fun) { \n this.functionList.push (fun);\n if (this.allDone) {\n this.allDone = false;\n this.start();\n console.log ( \"then(): continuing\");\n } \n};\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T15:13:36.007",
"Id": "44178",
"Score": "0",
"body": "I appreciate your comments. The internal implementation Manager may be not the best, but I was more interested in the usability of the interface (client code) and with regard to the implementation (here, consider your version) if you think that it can be used as a library for general development, or it must be restricted to cases with few \".then\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T15:57:48.073",
"Id": "44179",
"Score": "0",
"body": "What do you mean by \"cases with few `then`\"? It has no performance problems if you mean that. On the usability of the interface, only my first bullet point is interesting. It often is subjective, so ask your actual client :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T16:33:37.050",
"Id": "44183",
"Score": "0",
"body": "Yes, its on performance. And here I suppose there is no need to think in \"thread safe\" implementations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T17:30:21.403",
"Id": "44186",
"Score": "1",
"body": "Yes. And since the `Manager` is dedicated for asynchronous function queues, you don't need to worry about the call stack as well."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T09:39:52.253",
"Id": "28214",
"ParentId": "28213",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28214",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T08:41:42.573",
"Id": "28213",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"asynchronous"
],
"Title": "Synchronizing async tasks"
}
|
28213
|
<p>I am doing some tests with html5 Canvas object. At the same time I am trying to make my javascript code more modular. In the following code, where/how should I declare canvas and context, so that it can be shared with other objects? Please provide general comments/improvements?</p>
<p>Output:</p>
<p><img src="https://i.stack.imgur.com/DDJeG.jpg" alt="enter image description here"></p>
<p>Code:</p>
<pre><code>$( document ).ready(function() {
var axis = {
LEFT_INDENT : 100,
START_WORK_HOUR : 8,
END_WORK_HOUR : 17,
HOURS_IN_WORKDAY : 0,
CANVAS_WIDTH : 0,
CANVAS_HEIGHT : 0,
AXIS_SIDE_MARGIN : 20,
AXIS_TOP_MARGIN : 40,
AXIS_ORIGIN : new Array(),
AXIS_RIGHT : 0,
TICK_INCREMENT : 0,
setup: function(){
// assumes that I have <canvas id="myCanvas" width="800" height="300"></canvas> in the HTML
this.canvas = document.getElementById('myCanvas');
this.context = this.canvas.getContext('2d');
this.HOURS_IN_WORKDAY = this.END_WORK_HOUR - this.START_WORK_HOUR;
this.CANVAS_WIDTH = this.canvas.width;
this.CANVAS_HEIGHT = this.canvas.height;
this.AXIS_ORIGIN = { x: this.AXIS_SIDE_MARGIN,
y: this.AXIS_TOP_MARGIN };
this.AXIS_RIGHT = this.canvas.width-this.AXIS_SIDE_MARGIN;
this.TICK_INCREMENT = (this.CANVAS_WIDTH-this.LEFT_INDENT-(2*this.AXIS_SIDE_MARGIN))/this.HOURS_IN_WORKDAY;
this.AXIS_RIGHT = this.canvas.width-this.AXIS_SIDE_MARGIN;
},
draw_lines: function(){
this.context.beginPath();
this.context.moveTo(this.LEFT_INDENT, this.AXIS_ORIGIN.y);
this.context.lineTo(this.AXIS_RIGHT, this.AXIS_ORIGIN.y)
this.context.stroke();
this.counter = this.START_WORK_HOUR;
for(x=this.AXIS_SIDE_MARGIN+this.LEFT_INDENT ; x < this.AXIS_RIGHT ; x = x + this.TICK_INCREMENT){
// grid lines
this.context.beginPath();
this.context.moveTo(x,30);
this.context.lineTo(x,50)
this.context.stroke();
// background line - top to bottom
this.context.save();
this.context.fillStyle = "#F0F8FF";
this.context.beginPath();
this.context.lineWidth = .1;
this.context.moveTo(x,30);
this.context.lineTo(x,this.CANVAS_HEIGHT-20)
this.context.stroke();
this.context.restore();
// text
this.context.font = "14px Arial";
this.context.fillStyle = "#011f5b";
this.counter++;
this.context.fillText(this.counter+":00",x-7,20);
}
}
}
axis.setup();
axis.draw_lines();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T06:33:14.593",
"Id": "44069",
"Score": "0",
"body": "I'm not sure this will be helpful, but I created a github project called [brushes.js](https://github.com/jimschubert/brushes.js) which somewhat tries to encapsulate *brushes* to draw on a canvas. There are unit tests and examples."
}
] |
[
{
"body": "<p>You can wrap the functionality in an object. You instantiate it with a canvas element and some configuration options.</p>\n\n<pre><code>(function($) {\n\n// config defaults \nvar defaults = {\n LEFT_INDENT: 100,\n START_WORK_HOUR: 8,\n END_WORK_HOUR: 17,\n AXIS_SIDE_MARGIN: 20,\n AXIS_TOP_MARGIN: 40\n};\n\n// constructor\naxis = function(canvas, config)\n{\n this.config = $.extend({}, defaults, config);\n this.canvas = canvas;\n\n this.setup();\n}\n\n// define prototype functions\naxis.prototype.setup = function() {\n this.context = this.canvas.getContext('2d');\n\n this.HOURS_IN_WORKDAY = this.config.END_WORK_HOUR - this.config.START_WORK_HOUR;\n this.CANVAS_WIDTH = this.canvas.width;\n this.CANVAS_HEIGHT = this.canvas.height;\n\n this.AXIS_ORIGIN = {\n x: this.config.AXIS_SIDE_MARGIN,\n y: this.config.AXIS_TOP_MARGIN\n };\n\n this.AXIS_RIGHT = this.canvas.width - this.config.AXIS_SIDE_MARGIN;\n\n this.TICK_INCREMENT = (this.CANVAS_WIDTH - this.config.LEFT_INDENT - 2*this.config.AXIS_SIDE_MARGIN)) / this.HOURS_IN_WORKDAY;\n}\n\naxis.prototype.draw_lines = function() {\n this.context.beginPath();\n this.context.moveTo(this.LEFT_INDENT, this.AXIS_ORIGIN.y);\n this.context.lineTo(this.AXIS_RIGHT, this.AXIS_ORIGIN.y)\n this.context.stroke();\n this.counter = this.config.START_WORK_HOUR;\n\n for(x = this.config.AXIS_SIDE_MARGIN + this.config.LEFT_INDENT ; x < this.AXIS_RIGHT ; x = x + this.TICK_INCREMENT) {\n // grid lines\n this.context.beginPath();\n this.context.moveTo(x,30);\n this.context.lineTo(x,50)\n this.context.stroke();\n\n // background line - top to bottom\n this.context.save(); \n this.context.fillStyle = \"#F0F8FF\";\n this.context.beginPath();\n this.context.lineWidth = .1;\n this.context.moveTo(x,30);\n this.context.lineTo(x, this.CANVAS_HEIGHT - 20)\n this.context.stroke();\n this.context.restore(); \n\n // text \n this.context.font = \"14px Arial\";\n this.context.fillStyle = \"#011f5b\"; \n this.counter++;\n this.context.fillText(this.counter+\":00\",x-7,20); \n } \n}\n\n}(jQuery));\n</code></pre>\n\n<p>To use it:</p>\n\n<pre><code>var a = new axis(document.getElementById('myCanvas'), {\n // whatever you want to override\n});\na.draw_lines();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T03:30:55.743",
"Id": "44070",
"Score": "0",
"body": "my god, there are so many ways of doing things in javascript! If I understand you group variables in its own array. The \"axis\" methods and properties do not have to be wrapped and grouped together.\nYou are instantiating the axis object with the \"new\" verb then run the constructor within the object.\n\nCode is a bit neater, and setup is done within the class.\nWhat other advantages does this way offer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T06:29:38.577",
"Id": "44071",
"Score": "0",
"body": "@Abe With the encapsulation, it also allows to have multiple axis objects which are tied to canvas objects."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T03:13:06.960",
"Id": "28216",
"ParentId": "28215",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T02:57:10.467",
"Id": "28215",
"Score": "4",
"Tags": [
"javascript",
"html",
"object-oriented",
"canvas"
],
"Title": "javascript canvas -javascript design"
}
|
28215
|
<p>This program will show or alter the timestamp header on gzip archives. It was created for people who have issues using hash functions to compare gzip archives as the timestamps would be different. I want my code to really speak its intention without having to use comments outside of initialization (unless it is better). What can I do to improve this little guy?</p>
<p><a href="https://github.com/whackashoe/gziptimetravel/" rel="nofollow noreferrer">gziptimetravel GitHub repository</a></p>
<p>Here is the bulk of the program. The only other file is a cmake generated file for versioning (the header). </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <gziptimetravel.h>
void displayHelp(void);
void displayVersion(void);
time_t getTime(const unsigned char vals[4]);
void printTime(const time_t t);
int main(int argc, char ** argv)
{
int printtimeflag = 0; /*do we pretty print?*/
int settimeflag = 0; /*do we alter time on file*/
int grabfrominflag = 0; /*are we getting input from stdin?*/
int fileflag = 0; /*is a file set*/
const char * filesrc = NULL; /*path to input file passed*/
char newtime[11]; /*passed in time (since epoch)*/
char * tnewtime; /*temporary newtime for checking if newtime->ntime conversion succeeded*/
size_t newtimelength; /*length of newtime buffer*/
unsigned long ntime; /*the value of newtime*/
FILE *fp; /*input file*/
unsigned char gheaderbuffer[8]; /*buffer to hold header of gzip input file*/
size_t gheaderbytes; /*how many bytes read into gheaderbuffer*/
const unsigned char ID1 = 0x1f; /*IDentifier 1 (for gzip detection of file)*/
const unsigned char ID2 = 0x8b; /*IDentifier 2*/
int i; /*for loop iterator*/
int c; /*option iteration*/
while((c = getopt (argc, argv, "ps:S-:")) != -1) {
switch(c) {
case 'p':
printtimeflag = 1;
break;
case 's':
settimeflag = 1;
strncpy(newtime, optarg, sizeof(newtime)-1);
newtime[sizeof(newtime)-1] = '\0';
break;
case 'S':
settimeflag = 1;
grabfrominflag = 1;
break;
case '-':
if(strcmp(optarg, "help") == 0) {
displayHelp();
exit(0);
}
if(strcmp(optarg, "version") == 0) {
displayVersion();
exit(0);
}
break;
case '?':
if(optopt == 's')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if(isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
fprintf(stderr, "Try gziptimetravel --help\n");
exit(1);
default:
exit(1);
}
}
for (i = optind; i < argc; i++) {
if(!fileflag) {
fileflag = 1;
filesrc = argv[i];
}
}
if(!fileflag) {
fprintf(stderr, "Missing file operand (\"gziptimetravel --help\" for help)\n");
exit(1);
}
fp = fopen(filesrc, (settimeflag) ? "r+b" : "r");
if(fp == NULL) {
fprintf(stderr, "%s%s\n", filesrc, ": No such file");
exit(1);
}
gheaderbytes = fread(gheaderbuffer, sizeof(unsigned char), sizeof(gheaderbuffer), fp);
if(gheaderbytes < sizeof(gheaderbuffer)) {
fprintf(stderr, "%s%lu%s\n", "Only read ", gheaderbytes, " bytes");
exit(1);
}
/* gzip's 8 byte header format:
* bytes name desc
* 1: ID1 -- (IDentification 1)
* 1: ID2 -- (IDentification 2)
* 1: CM -- (Compression Method)
* 1: FLG -- (FLaGs)
* 4: MTIME -- (Modification TIME)
*/
if(gheaderbuffer[0] != ID1 || gheaderbuffer[1] != ID2) {
fprintf(stderr, "%s%s%s\n", "File:", filesrc, " is not a gzip archive\n");
exit(1);
}
if(!printtimeflag && !settimeflag) {
time_t mtime = getTime(gheaderbuffer+4);
printf("%lu\n", mtime);
}
if(printtimeflag) {
time_t mtime = getTime(gheaderbuffer+4);
printTime(mtime);
}
if(settimeflag) {
if(grabfrominflag) {
fflush(stdout);
if(!fgets(newtime, sizeof(newtime), stdin)) {
fprintf(stderr, "Error reading from stdin");
exit(1);
}
newtimelength = strlen(newtime);
if(newtime[newtimelength-1] == '\n') newtime[--newtimelength] = '\0';
}
tnewtime = newtime;
errno = 0;
ntime = strtoul(newtime, &tnewtime, 0);
if(errno != 0) {
fprintf(stderr, "Conversion of time failed, EINVAL, ERANGE\n");
exit(1);
}
if(*tnewtime != 0) {
fprintf(stderr, "Conversion of time failed, pass an unsigned integer\n");
exit(1);
}
fseek(fp, 4, SEEK_SET);
fputc((ntime & 0xFF), fp);
fputc((ntime >> 8 & 0xFF), fp);
fputc((ntime >> 16 & 0xFF), fp);
fputc((ntime >> 24 & 0xFF), fp);
}
fclose(fp);
return 0;
}
time_t getTime(const unsigned char vals[4])
{
time_t mtime = (vals[0]) +
(vals[1] << 8) +
(vals[2] << 16) +
(vals[3] << 24);
return mtime;
}
void printTime(const time_t t)
{
char gheaderbuffer[100];
strftime(gheaderbuffer, 100, "%Y-%m-%d %H:%M:%S", localtime(&t));
printf("%s\n", gheaderbuffer);
}
void displayHelp(void)
{
printf("Usage: gziptimetravel [OPTIONS...] SOURCE\n"
"Set or view timestamp of gzip archives\n"
"\n"
" -p print formatted timestamp to stdout\n"
" -s [seconds from epoch] set timestamp of file\n"
" -S set timestamp of file from stdin\n"
"\n"
"If no flags other than file are given gziptimetravel will output inputs timestamp as seconds since epoch\n"
"\n");
printf("EXAMPLES:\n"
" gziptimetravel input.tar.gz\n"
" Print input.tar.gz's timestamp\n"
"\n"
" gziptimetravel -s0 input.tar.gz\n"
" Set input.tar.gz's timestamp to January 1st 1970\n"
"\n"
" echo \"123456789\" | gziptimetravel -S input.tar.gz\n"
" Set input.tar.gz's timestamp to 1973-11-29 November 29th 1973\n"
"\n"
"\n");
printf("Report gziptimetravel bugs to whackashoe@gmail.com\n"
"gziptimetravel homepage: <https://github.com/whackashoe/gziptimetravel/>\n");
}
void displayVersion(void)
{
printf("%s%d%c%d\n", "gziptimetravel ", GZIPTIMETRAVEL_VERSION_MAJOR, '.', GZIPTIMETRAVEL_VERSION_MINOR);
}
</code></pre>
|
[] |
[
{
"body": "<p>An interesting program. A few comments</p>\n\n<ul>\n<li><p>there is too much in <code>main</code>. You could usefully split it into several\nseparate functions, one of which would handle argument processing.\nAdmittedly, your use of <code>getopt</code> from <code>main</code> means that you can set local\nvariables in main to control the program - if option handling is separated\nout, you must either pass the option variables in, define and pass an\n<code>options</code> structure holding those variables, or use globals (preferably not). Despite\nthis inconvenience, I would still separate option handling.</p></li>\n<li><p>The default of printing the time in seconds seems less useful than a default\nof printing the formatted time, with the value in seconds being available\nthrough an option.</p></li>\n<li><p>I wasn't aware that one could use long options through <code>getopt</code> (as opposed\nto <code>getopt_long</code>) in that way. Clearly it works :-)</p></li>\n<li><p>You print an extra message when a wrong option or missing argument is input\nbut <code>getopt</code> already prints a message. You should supress this default\nmessage - see the <code>getopt</code> man-page - or not print your own.</p></li>\n<li><p>You use your preferred name for the application in messages rather than\nusing <code>argv[0]</code>, which is perhaps more normal.</p></li>\n<li><p>It would be better after processing options to adjust the argument variables\nand then process each remaining argument as an input file, rather than\nrestricting input to just one file.</p>\n\n<pre><code>argc -= optind;\nargv += optind;\n\nfor (int i=0; i < argc; ++i) {\n gziptimetravel(argv[i], &options);\n}\n</code></pre>\n\n<p>This means that everything from the <code>fopen</code> call downwards is extracted\nfrom <code>main</code> to a function, such as <code>gziptimetravel</code> and other functions.<br>\nI would have\nfunction for each activity (is-header check, printing time seconds,\nprinting formatted time, setting time, getting time from user) called from\n<code>gziptimetravel</code></p></li>\n<li><p>Using <code>perror</code> on failure of a system call (or indeed of <code>strtoul</code>) instead\nof rolling your own error messages would be more normal:</p>\n\n<pre><code>if ((fp = fopen(filesrc, (settimeflag) ? \"r+b\" : \"r\")) == NULL) {\n perror(filesrc);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>Also your own messages are unusual, for exammle,</p>\n\n<pre><code>fprintf(stderr, \"%s%lu%s\\n\", \"Only read \", gheaderbytes, \" bytes\");\n</code></pre>\n\n<p>is usually written</p>\n\n<pre><code>fprintf(stderr, \"Only read %lu bytes\\n\", gheaderbytes);\n</code></pre></li>\n<li><p>some of your variable names are too long for me (<code>gheaderbuffer</code> ==\n<code>header</code>, <code>gheaderbytes</code> == <code>nbytes</code>). This is brought about by having\neverything in one big function and defining all variables at the start.\nSplitting into several functions means you can reduce variable name sizes\nwithout becoming uninteligible. Defining all variables at the top of <code>main</code>\nis too early for many. It is generally preferable to define variables only\nwhen/where you need them. For-loop variables can be defined within the\nloop.</p></li>\n<li><p>Trivial point: <code>sizeof(unsigned char)</code> is 1 by definition.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T05:28:16.463",
"Id": "44137",
"Score": "0",
"body": "Thanks a lot, this really helped. I've updated my repository with all changes and a bit more, minus one which I have a question on: why do you think that parsing the options should be in a separate function? I tried it, then realized I was just calling `checkArgs` and exiting, felt as though it was unnecessary indirection? I'd like to hear your thoughts on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T12:21:12.873",
"Id": "44150",
"Score": "1",
"body": "Your updated code (in github) looks better. I think it would be worth re-submitting it as a new question (they are free :-) to get extra comments as there are many style issues that I would comment upon. On separating option handling into a function, there is no right and wrong. Much programming is about personal taste and readability. To my taste, `main` is rather long - separating option handling would make it clearer. Others may disagree."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T19:36:32.813",
"Id": "28233",
"ParentId": "28217",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28233",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T01:27:00.880",
"Id": "28217",
"Score": "5",
"Tags": [
"c",
"datetime"
],
"Title": "Showing or altering the timestamp header on gzip archives"
}
|
28217
|
<p><strong>Information about my code:</strong></p>
<p>I am following this <a href="http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/" rel="nofollow">MIT OCW algorithms course</a>. The first lecture described insertion sort and merge sort. I implemented merge sort in C. </p>
<p>The algorithm is structured as a function called from the <code>main</code> function. The array to be sorted is allocated dynamically in the <code>main</code> function but can also be statically allocated.</p>
<p><strong>What I am looking for:</strong></p>
<p>I am looking whether the 2 functions can be optimized without changing the algorithm(merge sort), whether it follows the best-practices of programming in C and does it have proper readability factor?</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#define SORTING_ALGO_CALL merge_sort
void merge_parts(int arr[], int length)
{
/*
Sorts into increasing order
For decreasing order change the comparison in for-loop
*/
int ans[length];
//This for and next if-else puts the merged array into temporary array ans
//in a sorted manner
int i, k;
int temp, j = temp = length/2;
for (i = k = 0; (i < temp && j < length); k++){
ans[k] = (arr[i] < arr[j]) ? arr[i++] : arr[j++];
}
if(i >= temp){
while(j < length){
ans[k++] = arr[j++];
}
}
else{
while(i < temp){
ans[k++] = arr[i++];
}
}
//This for-loop puts array ans into original array arr
for(i = 0; i < length; i++){
arr[i] = ans[i];
}
}
void merge_sort(int arr[], int length)
{
if(length > 1)
{
merge_sort(&arr[0], (length/2));
merge_sort(&arr[length/2], (length - length/2));
merge_parts(arr, length);
}
}
int main()
{
int length;
scanf("%d", &length);
while (length < 1)
{
printf("\nYou entered length = %d\n", length);
printf("\nEnter a positive length: ");
scanf("%d", &length);
}
int *arr;
if ((arr = malloc(sizeof(int) * length)) == NULL)
{
perror("The following error occurred");
exit(-1);
}
for (int i = 0; i < length; i++){
scanf("%d", &arr[i]);
}
SORTING_ALGO_CALL(arr, length);
for (int i = 0; i < length; i++){
printf("%d ", arr[i]);
}
free(arr);
return 0;
}
</code></pre>
<p>The book I am reading is <em>Introduction to Algorithms 3rd Edition</em> by Cormen. It mentions a sentinel value be placed at the end of two subarrays. That, if implemented, it can result in better efficiency. But I am not sure what to use as a sentinel value.</p>
|
[] |
[
{
"body": "<p>I've slightly reorganised your code to make it easier to follow.</p>\n\n<pre><code>void merge_parts(int arr[], int length)\n{\n /*\n Sorts into increasing order\n For decreasing order change the comparison in for-loop\n */\n int ans[length];\n //This for and next if-else puts the merged array into temporary array ans\n //in a sorted manner\n int mid = length/2;\n int i = 0, k = 0, j = mid;\n while (i < mid && j < length){\n ans[k++] = (arr[i] < arr[j]) ? arr[i++] : arr[j++];\n }\n\n // Only one of the two loops will apply\n while(j < length){\n ans[k++] = arr[j++];\n }\n while(i < mid){\n ans[k++] = arr[i++];\n }\n\n //This for-loop puts array ans into original array arr\n for(int i = 0; i < length; i++){\n arr[i] = ans[i];\n }\n}\n\nvoid merge_sort(int arr[], int length)\n{\n if(length > 1)\n {\n int mid = length/2;\n merge_sort(arr, mid);\n merge_sort(arr+mid, length - mid);\n merge_parts(arr, length);\n }\n}\n\nint main()\n{\n int length;\n for (;;)\n {\n printf(\"\\nEnter a positive length: \");\n scanf(\"%d\", &length);\n printf(\"\\nYou entered length = %d\\n\", length);\n if (length>=1) break;\n }\n\n int *arr = malloc(sizeof(int) * length);\n if (!arr)\n {\n perror(\"The following error occurred\");\n exit(-1);\n }\n\n for (int i = 0; i < length; i++){\n scanf(\"%d\", &arr[i]);\n }\n\n merge_sort(arr, length);\n\n for (int i = 0; i < length; i++){\n printf(\"%d \", arr[i]);\n }\n\n free(arr);\n return 0;\n}\n</code></pre>\n\n<p>Then for the only optimisation I can think of, you could avoid some copying : when <code>j < length</code> after the main loop, it corresponds to a situation where the end of <code>arr</code> is already sorted in the right place. Thus, you don't need to copy it from <code>arr</code> to <code>ans</code> and then from <code>ans</code> to <code>arr</code>.</p>\n\n<pre><code>int mid = length/2;\nint i = 0, k = 0, j = mid;\nwhile (i < mid && j < length){\n ans[k++] = (arr[i] < arr[j]) ? arr[i++] : arr[j++];\n}\n\nwhile(i < mid){\n ans[k++] = arr[i++];\n}\n\n//This for-loop puts array ans into original array arr\nfor(i = 0; i < j; i++){\n arr[i] = ans[i];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T19:51:05.220",
"Id": "28234",
"ParentId": "28224",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28234",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T14:25:43.900",
"Id": "28224",
"Score": "6",
"Tags": [
"optimization",
"c",
"recursion",
"mergesort"
],
"Title": "Recursive implementation of merge sort"
}
|
28224
|
<p>I am currently going through Codecademy's Python course (I don't come from a coding background but I'm thoroughly enjoying it) and I got to the end of one of the sections and thought, "Well it worked, but that seemed wildly inefficient." I tried shortening unnecessary parts and came up with this:</p>
<pre><code>lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
classlist = [lloyd, alice, tyler]
# Add your function below!
def get_average(student):
average_homework = sum(student["homework"]) / len(student["homework"])
average_quizzes = sum(student["quizzes"]) / len(student["quizzes"])
average_tests = sum(student["tests"]) / len(student["tests"])
average_total = average_homework * 0.1 + average_quizzes * 0.3 + average_tests * 0.6
return average_total
def get_letter_grade(score):
if score >= 90:
return "A"
if score < 90 and score >= 80:
return "B"
if score < 80 and score >= 70:
return "C"
if score < 70 and score >= 60:
return "D"
else:
return "F"
def get_class_average(classlist):
a = []
for student in classlist:
a.append(get_average(student))
return sum(a) / len(a)
get_class_average(classlist)
</code></pre>
<p>Now this bit works, but I was wondering if there are more places I could trim the code down without losing the functionality (I'm guessing there is in the get_average function but the things I tried came back as errors because of the "name" field in the dictionary). Codecademy seems good for learning the fundamentals, but I wanted to get some insight into the "best" way to do things. Should I not worry about reworking functional code to be more efficient at first and just learn the fundamentals, or should I keep trying to make the "best" code as I learn?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T14:50:32.037",
"Id": "44104",
"Score": "1",
"body": "Can you add information about the problem you are trying to solve ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:06:50.560",
"Id": "44106",
"Score": "0",
"body": "@Josay Actually he isn't trying to solve any problem. This is the part of the python track on codecademy.com. One introducing to dictionary in Python."
}
] |
[
{
"body": "<ul>\n<li>In the function <code>get_letter_grade</code> you were checking more conditions then necessary. Try to follow the logical difference between your function and my code. It is simple math which I used to optimize it. Also structuring it as an if-elif-...-else is better for readability.</li>\n<li>In <code>get_average</code> and <code>get_class_average</code> I use a thing called list comprehension. A simple google search will tell you what it is and why it is better. Google it in python tutorials if you have problem.</li>\n</ul>\n\n<p><strong>Edited Functions</strong></p>\n\n<pre><code>def average(values):\n return sum(values) / len(values)\n\ndef get_average(student):\n keys = ['homework', 'quizzes', 'tests']\n factors = [0.1, 0.3, 0.6]\n return sum([ average(student[key]) * factor for key, factor in zip(keys, factors)])\n\ndef get_letter_grade(score):\n if score >= 90:\n return \"A\"\n elif score >= 80:\n return \"B\"\n elif score >= 70:\n return \"C\"\n elif score >= 60:\n return \"D\"\n else:\n return \"F\"\n\ndef get_class_average(classlist):\n return average([get_average(student) for student in classlist])\n\nget_class_average(classlist)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:21:45.747",
"Id": "44109",
"Score": "0",
"body": "I would vote you up, but I don't have 15 reputation. This is exactly what I was meaning. It works to Codeacademy standards, but could easily be refined. Thanks for the list comprehension pointer as well!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:34:22.833",
"Id": "44110",
"Score": "0",
"body": "@Raynman37 Edited the answer a bit more. Try to figure out how the return statement of `get_average` works. Yeah you cannot vote up but you can [accept an answer](http://codereview.stackexchange.com/help/accepted-answer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:34:48.043",
"Id": "44111",
"Score": "3",
"body": "Actually you don't need a list-comprehension. A generator expression works too, and avoids the creation of the intermediate `list`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:39:42.170",
"Id": "44112",
"Score": "0",
"body": "@Bakuriu Yeah that would have been better. There are two reasons I didn't do that. FIrstly, the OP is a beginner and I don't think introducing generators to a beginner would be a good idea. Secondly, I am not much experienced in Python either so my explanation might not have been the best. If he is interested here is a [link to a question on stackoverflow](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:42:08.100",
"Id": "44113",
"Score": "0",
"body": "@AseemBansal I'm not sure I understand the xrange part. Is that just so it loops 3 times? The rest I get after following it through all the steps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:43:48.013",
"Id": "44114",
"Score": "0",
"body": "@Bakuriu thanks as well! I'll look into that too. This is really what I wanted, to get extra things that I can go read about to expand my understanding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:45:28.740",
"Id": "44115",
"Score": "0",
"body": "Yeah. The value of i goes from 0 upto 3 i.e. 0,1,2. Try to figure out what is keys[0], keys[1] and key[2]. Similarly for factors. The best way to understand is to take pen and paper and write these values. It might be helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:48:47.130",
"Id": "44116",
"Score": "0",
"body": "@Raynman37 If you want to know extra things then I would suggest you to go [here](http://docs.python.org/2/index.html). It has the entire Python. In this the tutorial part is especially useful for beginners. It might be more useful than reading advanced material in the beginning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:50:47.273",
"Id": "44117",
"Score": "0",
"body": "@AseemBansal I will definitely take a look at that. Thanks! I kind of figured the only way to refine it past what you do on code academy would be to start using more advanced things. I'll keep this bit of code for later and come back to it after I learn more techniques."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T03:19:03.903",
"Id": "44136",
"Score": "1",
"body": "I would have used ``zip`` in ``get_average()``: ``return sum([average(student[key]) * factor for key, factor in zip(keys, factors)])``."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T14:57:48.720",
"Id": "28227",
"ParentId": "28226",
"Score": "1"
}
},
{
"body": "<p>Defining an <code>average</code> function (based on <a href=\"https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list\">this</a>), you could have things slightly clearer :</p>\n\n<pre><code>def average_list(l)\n return sum(l) / float(len(l))\n\ndef average_student(student):\n average_homework = average_list(student[\"homework\"])\n average_quizzes = average_list(student[\"quizzes\"])\n average_tests = average_list(student[\"tests\"])\n average_total = average_homework * 0.1 + average_quizzes * 0.3 + average_tests * 0.6\n return average_total\n\ndef class_average(students):\n return average_list([average_student(s) for s in students])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:07:57.283",
"Id": "44107",
"Score": "0",
"body": "You are not using the description in the link that you provided. You just added a function call which can be used in the other function as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:52:27.583",
"Id": "44118",
"Score": "0",
"body": "Actually I was talking about using `reduce` and `lambda`. Anyways you don't need to use `float` in the `average_list` function either. All the values are `float` already so sum would also be. Implicit conversion so explicit isn't needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T17:49:21.100",
"Id": "44124",
"Score": "1",
"body": "@Josay Are we supposed to use `class` in the class_average section because it's already a built in Python term (I don't know what you'd call it officially)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T18:54:44.100",
"Id": "44126",
"Score": "0",
"body": "Raynman37 : As per http://docs.python.org/release/2.5.2/ref/keywords.html this is a valid comment. It completely went out of my mind but I'm going to change this."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T14:58:00.580",
"Id": "28228",
"ParentId": "28226",
"Score": "0"
}
},
{
"body": "<p>In average_student, you're manually iterating over the keys in a dictionary, and you've hardcoded the weights of the various parts. What if you want to add a \"presentation\" component to the grade? You've got a lot of places to touch.</p>\n\n<p>Consider exporting the hardcoded information into its own dictionary, and iterating over the keys in that dictionary:</p>\n\n<pre><code>weights = {\n \"homework\": 0.1,\n \"quizzes\": 0.3,\n \"tests\": 0.6\n}\n\ndef get_average(student):\n return sum(average(student[section]) * weights[section] for section in weights)\n\ndef average(x):\n return sum(x)/len(x)\n</code></pre>\n\n<p>In terms of learning Python, I'd definitely agree with your instinct -- you should keep trying to make your code as clean as possible even while completing exercises. When you're learning fundamentals, it's that much more important to understand good structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T16:10:53.630",
"Id": "44120",
"Score": "0",
"body": "Is this the `get_average` function? I tried but couldn't run it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T17:40:04.553",
"Id": "44122",
"Score": "0",
"body": "Oops! I had a syntax brainfart. Fixed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T17:45:11.850",
"Id": "44123",
"Score": "0",
"body": "@llb Thanks for this input too! `get_average` was the section I didn't like when I got done with it either. Exactly like you said that whole section was basically hardcoded in there. I'll definitely be playing with this today as well!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T15:45:34.337",
"Id": "28229",
"ParentId": "28226",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-06T22:32:45.643",
"Id": "28226",
"Score": "0",
"Tags": [
"python"
],
"Title": "Calculating student and class averages"
}
|
28226
|
<p>I have the following code to open and close some popup divs. I'd like to know whether there is a shorter solution to close the currently opened divs, as soon as another div is opened, so that there is only one open div.</p>
<p>The current solution works as you can see in <a href="http://jsfiddle.net/Gq6eK/2/y" rel="nofollow noreferrer">this jsFiddle</a>, but I guess it is a bit inconvenient.</p>
<p><strong>jQuery:</strong></p>
<pre><code>$('.details').hide();
$('#item-a').click(function () {
$('#detail-1').fadeToggle(600);
$('#detail-2,#detail-3').fadeOut("slow");
});
$('#item-b').click(function () {
$('#detail-2').fadeToggle(600);
$('#detail-1,#detail-3').fadeOut("slow");
});
$('#item-c').click(function () {
$('#detail-3').fadeToggle(600);
$('#detail-1,#detail-2').fadeOut("slow");
});
$('.btn-close').click(function () {
$(this).parent().parent().fadeOut("slow");
});
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><div id="content">
<ul class="list-1">
<li class="topic-a" id="item-a">
<p class="shortinfo"> item a </p>
</li>
<li class="topic-b" id="item-b">
<p class="shortinfo"> item b </p>
</li>
<li class="topic-b" id="item-c">
<p class="shortinfo"> item c </p>
</li>
</ul>
</div>
<div class="block">
<div class="details" id="detail-1">
<p><a class="btn-close">close</a>
</p>
<p> Some detailed text 1.. </p>
</div>
<div class="details" id="detail-2">
<p><a class="btn-close">close</a>
</p>
<p> Some detailed text 2.. </p>
</div>
<div class="details" id="detail-3">
<p><a class="btn-close">close</a>
</p>
<p> Some detailed text 3.. </p>
</div>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>You can use the <code>not</code> function to get all the details elements except one:</p>\n\n<pre><code>function show(sel) {\n var el = $(sel);\n el.fadeToggle(600);\n $('.details').not(el).fadeOut(\"slow\");\n}\n\n$('.details').hide();\n\n$('#item-a').click(function () {\n show('#detail-1');\n});\n\n$('#item-b').click(function () {\n show('#detail-2');\n});\n\n$('#item-c').click(function () {\n show('#detail-3');\n});\n\n$('.btn-close').click(function () {\n $(this).parent().parent().fadeOut(\"slow\");\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T21:30:55.897",
"Id": "28238",
"ParentId": "28235",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28238",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-07T20:17:24.210",
"Id": "28235",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "jQuery fadeToggle/fadeout function"
}
|
28235
|
<p>Say I have <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code> and I want to spread it across - at most - 4 columns. The end result would be: <code>[[1, 2, 3], [4, 5], [6, 7], [8, 9]]</code>. So I made this:</p>
<pre><code>item_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
item_count = len(item_list)
column_count = item_count if item_count <= 4 else 4
items_per_column = int(item_count / 4)
extra_items = item_count % 4
item_columns = []
for group in range(column_count):
count = items_per_column
if group < extra_items:
count += 1
item_columns.append(item_list[:count])
item_list = item_list[count:]
</code></pre>
<p>Is there a nicer way of accomplishing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T09:32:37.943",
"Id": "44142",
"Score": "0",
"body": "What are the constraints ? I assume that : 1) a column cannot be be bigger than a column on its left 2) the maximum size difference between two columns must be 0 or 1 3) the element should stay in the same order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T09:34:49.140",
"Id": "44143",
"Score": "0",
"body": "Also, I guess the list in your question should be [1, 2, 3, 4, 5, 6, 7, 8, 9] and not [1, 2, 3, 4, 5, 7, 8, 9]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T10:18:32.023",
"Id": "44145",
"Score": "0",
"body": "@Josay Correct on all accounts. It should attempt to spread everything evenly, left -> right, maintaining order and I've fixed my list, thanks."
}
] |
[
{
"body": "<p>How about using generators? </p>\n\n<ul>\n<li>It puts the whole thing in a function which in <a href=\"https://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function\">itself is a performance boost</a>. </li>\n<li>List comprehension are better compared to list creation and appending. See the part Loops and avoiding dots.. in <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow noreferrer\">here</a></li>\n<li>An extra variable isn't needed for the length of the list as <a href=\"http://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">it is <code>O(1)</code> operation</a>.</li>\n<li>You don't need to use the <code>int</code> function. It will be an <code>int</code> in this case.</li>\n</ul>\n\n<p><strong>My Suggested Code</strong></p>\n\n<pre><code>def get_part(item_list):\n items_per_column = len(item_list) / 4\n extra_items = len(item_list) % 4\n\n if len(item_list) <= 4:\n column_count = len(item_list)\n else:\n column_count = 4\n\n for i in xrange(column_count):\n if i < extra_items:\n yield item_list[i * (items_per_column + 1) : (i + 1) * (items_per_column + 1)]\n else:\n yield item_list[i * items_per_column : (i + 1) * items_per_column]\n\nitem_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nitem_columns = [i for i in get_part(item_list)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T18:16:08.537",
"Id": "28258",
"ParentId": "28244",
"Score": "0"
}
},
{
"body": "<p>You could do something like this (elegant, but not the fastest approach)</p>\n\n<pre><code>item_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nmin_height = len(item_list) // 4\nmod = len(item_list) % 4\n\nheights = [min_height + 1] * mod + [min_height] * (4 - mod)\nindices = [sum(heights[:i]) for i in range(4)]\ncolumns = [item_list[i:i+h] for i, h in zip(indices, heights)]\n</code></pre>\n\n<p>Or a compressed version:</p>\n\n<pre><code>columns = [item_list[\n min_height * i + (i >= mod) * mod :\n min_height * (i+1) + (i+1 >= mod) * mod]\n for i in range(4)]\n</code></pre>\n\n<p>I guess the fastest way would be similar to what you already have:</p>\n\n<pre><code>index = 0\ncolumns = []\nfor i in xrange(4):\n height = min_height + (i < mod)\n columns.append(item_list[index:index+height])\n index += height\n</code></pre>\n\n<p>(With both of these, if there are less than 4 items you get empty columns at the end.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T04:35:45.980",
"Id": "44341",
"Score": "0",
"body": "o.O I didn't know `(1 + True) == 2`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:04:53.113",
"Id": "44381",
"Score": "0",
"body": "it's hacky but True and False become 1 or 0 when mixed with numbers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:51:04.863",
"Id": "28304",
"ParentId": "28244",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T08:27:11.953",
"Id": "28244",
"Score": "1",
"Tags": [
"python"
],
"Title": "Taking a list and using it to build columns"
}
|
28244
|
<p><strong>Edit:</strong> Even adding a comment of "looks good to me" and up-voting that comment would be appreciated :) I just want the feedback! Thanks!</p>
<p>For the fun of it as well as professional development, I wrote a small "library" (single 24 line JavaScript function) that will allow a developer to double check that all external libraries loaded and to reload them with a local copy as a fallback if the CDN is blocked or down.</p>
<h1>Double Take Script Loader</h1>
<p><img src="https://lh6.googleusercontent.com/-oVncGY891Sc/Udl8V3DHb1I/AAAAAAAABYg/KX4pJgv0fEc/w350-h166-no/Double+Take.png" alt="Double Take Script Loader" title="Double Take Script Loader"></p>
<p>This is a simple way to load a local copy of a library as a fallback to an external CDN.</p>
<p>I'm looking for feedback on my methods. <a href="https://gist.github.com/kentcdodds/5941149" rel="nofollow">Here's the actual gist on GitHub</a>. Is there any (obvious) way I could improve this function? I realize that everyone has their own style and such. I'm not asking about that. I'm asking about better performance/ease of use. See the specific questions on the lines of code.</p>
<p><strong>dt-script-loader.js</strong></p>
<pre><code>var DoubleTakeScriptLoader = function(scripts) { //I have to use the global namespace if I want to let devs call it on their own right?
if (scripts) { //Allows devs to call it with specific scripts
if (Object.prototype.toString.call(scripts) !== '[object Array]' ) { //Is there a better way to check whether it's an array without using another library?
scripts = [scripts]; //Allows devs to call with just an object and I'll change it to an array
}
} else {
scripts = document.getElementsByTagName('script'); //If function is called without argument, we'll get the scripts from the document. I think this will only load the scripts that have been parsed thus far correct?
}
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
var propName = script.propName || script.getAttribute('data-prop-name'); //For use without calling with an argument, I get a data attribut. Is getAttribute the best way to get attributes or should I use dot notation in the context? I have seen differing opinions.
var localSource = script.localSource || script.getAttribute('data-local-src');
if (propName != null && localSource != null) {
if (!window[propName]) { //If the library was not loaded. Is there any way to be aware that the request to get the library failed so this can be responsive to failures rather than called regardless?
document.write('<script src="' + localSource + '" type="text/javascript"><' + '/script>'); //I tried creating a DOM element and adding it to the DOM, but the script wouldn't load. Did I do something wrong, or is this the best way to add a script to the DOM as it is parsing?
if (script.originalId) {
script = document.getElementById(script.originalId);
}
!script.parentNode || script.parentNode.removeChild(script); //Remove the old script. Good/bad?
}
}
}
};
DoubleTakeScriptLoader(); //Invoke the script so devs using it don't have to do so. Should I allow them to have a data- attribute on the script itself which says "don't invoke?" I don't see it being any performance issue or anything....
</code></pre>
<p>Thanks for any and all input. I realize that a single function is not much of a library, but I'm learning and I want to build something useful for others.</p>
<h2>Example</h2>
<p>For an example of how to use this function, see <a href="https://gist.github.com/kentcdodds/5941149#file-example-html" rel="nofollow" title="example.html"><code>example.html</code></a>. You will of course need local copies of <a href="http://jquery.com/download/" rel="nofollow" title="jQuery Download">jQuery</a> and <a href="http://underscorejs.org/" rel="nofollow" title="UnderscoreJS.org">Underscore</a> because for the purpose of the example the CDNs do not actually exist. You can also look at <a href="http://kent.doddsfamily.us/dt-script-loader" rel="nofollow" title="DT Demo">the demo</a>.</p>
<p><strong>example.html</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>DT Script Loader</title>
</head>
<body>
<h1>Double Take Script Loader Example</h1>
<div id="message-jQuery">
Waiting to load jQuery...
</div>
<div id="message-underscore">
Waiting to load Underscore...
</div>
<!-- Method 1: Use data- attributes. This does NOT require calling DoubleTakeScriptLoader, just including it. -->
<script src="http://cdn.example.com/underscore/1.4.4/underscore-min.js" data-prop-name="_" data-local-src="underscore-min.js"></script>
<!-- Method 2: Call DoubleTakeScriptLoader directly -->
<script src="http://cdn.example.com/jquery/1.10.1/jquery.min.js" id="jQueryScript"></script>
<script src="dt-script-loader.js"></script>
<script>
DoubleTakeScriptLoader({
propName: '$',
localSource: 'jquery-1.10.2.min.js',
originalId: 'jQueryScript'
});
</script>
<!-- Use libraries. This must be done AFTER calling DoubleTakeScriptLoader() -->
<script>
(function() {
var checkStuff = function(prop, elementId) {
var el = document.getElementById(elementId);
if (window[prop]) {
el.innerText = 'Loading ' + prop + ' worked great!';
el.style.backgroundColor = "green";
} else {
el.innerText = 'Loading ' + prop + ' did NOT work!';
el.style.backgroundColor = "red";
}
};
checkStuff('$', 'message-jQuery');
checkStuff('_', 'message-underscore');
})();
</script>
</body>
</html>
</code></pre>
<hr>
<p>I, the student, thank you for your time and feedback and look forward to your constructive input.</p>
|
[] |
[
{
"body": "<p>I like the look of this in general. Its short, simple and I'd love to know how well its worked in the field.</p>\n\n<p>I'm not a big fan of <code>document.write</code> but I don't think the alternative is much better. If you look in the jQuery source code you'll see they eval the script.</p>\n\n<p>It comes from <a href=\"http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context\" rel=\"nofollow\">http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context</a> </p>\n\n<p>In place of the <code>document.write</code> I might put something like: </p>\n\n<pre><code>var xmlHttpReq = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(\"Microsoft.XMLHTTP\");\nxmlHttpReq.open('GET', localSource);\nxmlHttpReq.setRequestHeader('Content-Type', 'application/javascript');\nxmlHttpReq.onreadystatechange = function _readyStateChange() {\n if (xmlHttpReq.readyState == 4) {\n (window.execScript || window.eval).call(window, xmlHttpReq.responseText);\n }\n}\nxmlHttpReq.send(null);\n</code></pre>\n\n<p>This uses an ajax request to get the JavaScript instead of blocking your page load. Its all a matter of taste I believe. (Also any other scripts might fail if they are expecting your framework to have loaded.)</p>\n\n<hr>\n\n<p>After some Google Searching I've found a few places that do the almost same as your framework in less code.</p>\n\n<pre><code><script src=\"/path/to/cdn/framwork.js\"></script>\n<script> window.framework || document.write(\"<script src=\\\"/local/path/framework.js\\\"></script>\");</script>\n</code></pre>\n\n<p>It is shorter but requires one per script file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T01:02:21.747",
"Id": "36171",
"ParentId": "28246",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T11:41:29.893",
"Id": "28246",
"Score": "6",
"Tags": [
"javascript",
"library",
"library-design"
],
"Title": "CDN Fallback \"library\""
}
|
28246
|
<p>I came across this interview question and it has been asked to print combinations of the characters in a string. For example: "abc" --> a, b, c, ab, ac, bc, abc. Also it has been mentioned that 'ab' and 'ba' are same. </p>
<p>I want to know if there is any improvement I can make in terms of memory usage/performance.</p>
<pre><code>public string[] Combination(string str)
{
if (string.IsNullOrEmpty(str))
throw new ArgumentException("Invalid input");
if (str.Length == 1)
return new string[] { str };
// read the last character
char c = str[str.Length - 1];
// apart from the last character send remaining string for further processing
string[] returnArray = Combination(str.Substring(0, str.Length - 1));
// List to keep final string combinations
List<string> finalArray = new List<string>();
// add whatever is coming from the previous routine
foreach (string s in returnArray)
finalArray.Add(s);
// take the last character
finalArray.Add(c.ToString());
// take the combination between the last char and the returning strings from the previous routine
foreach (string s in returnArray)
finalArray.Add(s + c);
return finalArray.ToArray();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T07:07:31.133",
"Id": "44152",
"Score": "0",
"body": "For big strings you can fall through stackoverflow exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T07:15:10.327",
"Id": "44153",
"Score": "0",
"body": "@HamletHakobyan: thanks for your reply. is there any way to avoid it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T07:16:34.177",
"Id": "44154",
"Score": "0",
"body": "@p.s.w.g: From next time I will surely post such question in the codereview site. thanks for the information."
}
] |
[
{
"body": "<p>I can suggest following project for combinations and permutations which is very efficient and easy to use:</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G\">http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G</a></p>\n\n<p>Then it's simple as:</p>\n\n<pre><code>IList<Char> chars = \"abc\".ToList();\nList<string> allCombinations = new List<String>();\nfor (int i = 1; i <= chars.Count; i++)\n{ \n var combis = new Facet.Combinatorics.Combinations<Char>(\n chars, i, Facet.Combinatorics.GenerateOption.WithRepetition);\n allCombinations.AddRange(combis.Select(c => string.Join(\"\", c)));\n}\n\nforeach (var combi in allCombinations)\n Console.WriteLine(combi);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>a\nb\nc\naa\nab\nac\nbb\nbc\ncc\naaa\naab\naac\nabb\nabc\nacc\nbbb\nbbc\nbcc\nccc\n</code></pre>\n\n<p>If you don't want repetion you just have to change <code>GenerateOption.WithRepetition</code> to <code>GenerateOption.WithoutRepetition</code> and the result is:</p>\n\n<pre><code>a\nb\nc\nab\nac\nbc\nabc\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T14:14:12.030",
"Id": "44171",
"Score": "8",
"body": "I wonder if that would be accepted at an interview."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T07:26:27.843",
"Id": "28249",
"ParentId": "28248",
"Score": "6"
}
},
{
"body": "<p>Mostly for fun, this version will work for strings up to 30 characters long:</p>\n\n<pre><code>var str = \"abc\";\nvar results = \n from e in Enumerable.Range(0, 1 << str.Length)\n let p = \n from b in Enumerable.Range(0, str.Length)\n select(e & (1 << b)) == 0 ? (char?)null : str[b]\n select string.Join(string.Empty, p);\n</code></pre>\n\n<p>Or in fluent syntax:</p>\n\n<pre><code>var results = Enumerable.Range(0, 1 << str.Length)\n .Select(e => string.Join(string.Empty, Enumerable.Range(0, str.Length).Select(b => (e & (1 << b)) == 0 ? (char?)null : str[b])));\n</code></pre>\n\n<p>The output will be:</p>\n\n<pre><code>{empty string}\na\nb\nab\nc\nac\nbc\nabc\n</code></pre>\n\n<p>You can use <code>Enumerable.Range(1, (1 << str.Length) - 1)</code> or <code>.Skip(1)</code> to exclude the empty string in the results. </p>\n\n<p>If you write your own <code>Range</code> function using <code>BigInteger</code>'s, like this:</p>\n\n<pre><code>public IEnumerable<BigInteger> Range(BigInteger start, BigInteger count)\n{\n while(count-- > 0)\n {\n yield return start++;\n }\n}\n</code></pre>\n\n<p>You can extend this technique to support strings of any length:</p>\n\n<pre><code>var results = \n from e in Range(0, BigInteger.Pow(2, str.Length))\n let p = \n from b in Enumerable.Range(1, str.Length)\n select(e & BigInteger.Pow(2, b - 1)) == 0 ? (char?)null : str[b - 1]\n select string.Join(string.Empty, p);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T09:07:19.497",
"Id": "44155",
"Score": "0",
"body": "what about using UInt64 instead of int (as the data type of 'e' above) to work for strings of length up to 63 characters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T10:04:23.237",
"Id": "44156",
"Score": "0",
"body": "@bytefire Absolutely. You could do that, but you'd have to write your own version `Enumerable.Range` for that, which kind of ruins the nice 'one-liner' aspect of this solution, and ultimately it just pushes the hard limit back a few steps. If you use `BigInteger`'s it will work for arbitrary-length strings (see my updated answer), though not as efficiently since `BigInteger` math is much slower than `int` or `long` math."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T10:25:39.207",
"Id": "44157",
"Score": "0",
"body": "My up vote was, in part, for the one-liner niceness."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T09:31:21.353",
"Id": "423704",
"Score": "0",
"body": "I'm working on similar function and this gives a good head start, do you have any idea what I should change if I only wanted to find \"connected\" permutations in \"original sequence\"? For example, for the case of abc, the result should be only a/b/c/ab/bc/abc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T15:06:57.057",
"Id": "423751",
"Score": "0",
"body": "@ChorWaiChun I think I'd take a different approach. In that case, each result would be a non-empty substring of `str`, i.e. `from i in Range(0, str.length - 1) from j in Range(1, str.length - i) select str.Substring(i, j);`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T07:48:06.203",
"Id": "28250",
"ParentId": "28248",
"Score": "4"
}
},
{
"body": "<p>You can improve the implementation by building the strings only when needed:</p>\n\n<pre><code>public static string[] Combination2(string str)\n{\n List<string> output = new List<string>();\n // Working buffer to build new sub-strings\n char[] buffer = new char[str.Length];\n\n Combination2Recurse(str.ToCharArray(), 0, buffer, 0, output);\n\n return output.ToArray();\n}\n\npublic static void Combination2Recurse(char[] input, int inputPos, char[] buffer, int bufferPos, List<string> output)\n{\n if (inputPos >= input.Length)\n {\n // Add only non-empty strings\n if (bufferPos > 0)\n output.Add(new string(buffer, 0, bufferPos));\n\n return;\n }\n\n // Recurse 2 times - one time without adding current input char, one time with.\n Combination2Recurse(input, inputPos + 1, buffer, bufferPos, output);\n\n buffer[bufferPos] = input[inputPos];\n Combination2Recurse(input, inputPos + 1, buffer, bufferPos + 1, output);\n}\n</code></pre>\n\n<p>When run 100,000 times with the string 'abcdefghi' on my laptop the results are:</p>\n\n<ul>\n<li> Question's implementation: 5.21s </li>\n<li> This implementation: 2.48s </li>\n<li> Tim Schmelter's implementation: 93s </li>\n<li> p.s.w.g's implementation: 142s </li>\n</ul>\n\n<p>You can further improve performance/memory by pre-allocating the needed output array string[] and writing the strings directly to the array (the size is 2^n, minus 1 the empty string).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T05:52:48.877",
"Id": "423676",
"Score": "0",
"body": "Just wondering, is the Tim you referring now Rango?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T19:51:47.737",
"Id": "423933",
"Score": "0",
"body": "@ChorWaiChun Yes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T06:46:43.160",
"Id": "29051",
"ParentId": "28248",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T07:01:43.737",
"Id": "28248",
"Score": "8",
"Tags": [
"c#",
"algorithm"
],
"Title": "Implement a function that prints all possible combinations of the characters in a string"
}
|
28248
|
<p>After finding myself sometimes needing a map of maps, and as I couldn't find one in existing libs (like Guava), I wrote my own implementation. Do you think this version is okay? Specifically: Is it acceptable that I don't permit empty "inner" maps as content for my "outer" map, hence probably breaking the contract of <code>Map</code>? Do I miss useful methods, are some methods superfluous? Should my class implement the <code>Map</code> interface at all, as some methods work counter-intuitive when using this abstraction? Are the names of the additional methods too subtle?</p>
<pre><code>import java.util.*;
public class MapMap<K1,K2,V> implements Map<K1,Map<K2,V>> {
private Map<K1, Map<K2,V>> underlyingMap = new HashMap<K1, Map<K2, V>>();
public MapMap() {
}
public MapMap(Map<K1, Map<K2,V>> underlyingMap) {
putAll(underlyingMap);
}
@Override
public int size() {
return underlyingMap.size();
}
@Override
public boolean isEmpty() {
return underlyingMap.isEmpty();
}
@Override
public boolean containsKey(Object o) {
return underlyingMap.containsKey(o);
}
@Override
public boolean containsValue(Object o) {
return underlyingMap.containsValue(o);
}
@Override
public Map<K2, V> get(Object o) {
return underlyingMap.get(o);
}
@Override
public Map<K2, V> put(K1 k1, Map<K2, V> k2VMap) {
return (k2VMap == null || k2VMap.isEmpty()) ? null : underlyingMap.put(k1, k2VMap);
}
@Override
public Map<K2, V> remove(Object o) {
return underlyingMap.remove(o);
}
/**
* Puts the contents in a map of maps.
* Note that existing content stored under an outer key will be overwritten by the provided content.
* Note that no empty or null inner maps are stored.
* @param map the content to be added
*/
@Override
public void putAll(Map<? extends K1, ? extends Map<K2, V>> map) {
for(Entry<? extends K1, ? extends Map<K2, V>> entry : map.entrySet()) {
if (entry.getValue() != null && ! entry.getValue().isEmpty()) {
underlyingMap.put(entry.getKey(), entry.getValue());
}
}
}
@Override
public void clear() {
underlyingMap.clear();
}
@Override
public Set<K1> keySet() {
return underlyingMap.keySet();
}
@Override
public Collection<Map<K2, V>> values() {
return underlyingMap.values();
}
@Override
public Set<Entry<K1, Map<K2, V>>> entrySet() {
return underlyingMap.entrySet();
}
/**
* Retrieves a value from a map of maps
* @param key1 the key for the outer map
* @param key2 the key for the inner map
* @return the inner value, or null if none exists
*/
public V get(K1 key1, K2 key2) {
Map<K2,V> map = underlyingMap.get(key1);
return map == null ? null : map.get(key2);
}
/**
* Puts a value in a map of maps.
* Note that inner maps are created if necessary
* @param key1 the key for the outer map
* @param key2 the key for the inner map
* @param value the value for the inner map
* @return the former value, or null if none exists
*/
public V put(K1 key1, K2 key2, V value) {
Map<K2,V> map = underlyingMap.get(key1);
if (map == null) {
map = new HashMap<K2, V>();
underlyingMap.put(key1, map);
}
return map.put(key2, value);
}
/**
* Removes a value from a map of maps.
* Note that if an inner map gets empty by this operation, it will be removed.
* @param key1 the key for the outer map
* @param key2 the key for the inner map
* @return the former value, or null if none exists
*/
public V remove(K1 key1, K2 key2) {
Map<K2,V> map = underlyingMap.get(key1);
if (map == null) {
return null;
} else {
V result = map.remove(key2);
if (map.isEmpty()) {
remove(key1);
}
return result;
}
}
/**
* Returns a list of all values of inner maps to a given inner key
* @param key2 the inner key
* @return the list of values
*/
public List<V> deepGet(K2 key2) {
List<V> result = new ArrayList<V>();
for(Map<K2, V> map : underlyingMap.values()) {
V value = map.get(key2);
if (value != null) {
result.add(value);
}
}
return result;
}
/**
* Puts a value in all existing inner maps
* @param key2 the inner key
* @param value the inner value
* @return the list of former values
*/
public List<V> deepPut(K2 key2, V value) {
List<V> result = new ArrayList<V>();
for(Map<K2, V> map : underlyingMap.values()) {
V v = map.put(key2, value);
if (v != null) {
result.add(v);
}
}
return result;
}
/**
* Puts the contents in a map of maps.
* Note that existing content won't be overwritten.
* Note that no empty or null inner maps are stored.
* @param map the content to be added
*/
public void deepPutAll(Map<? extends K1, ? extends Map<K2, V>> map) {
for(Entry<? extends K1, ? extends Map<K2, V>> entry : map.entrySet()) {
if (entry.getValue() != null && !entry.getValue().isEmpty()) {
Map<K2, V> innerMap = underlyingMap.get(entry.getKey());
if (innerMap == null) {
underlyingMap.put(entry.getKey(), entry.getValue());
} else {
innerMap.putAll(entry.getValue());
}
}
}
}
/**
* Removes content for a given key from inner maps.
* Note that if an inner map gets empty by this operation, it will be removed.
* @param key2 the inner key
* @return the List of removed values
*/
public List<V> deepRemove(K2 key2) {
List<V> result = new ArrayList<V>();
for(Entry<K1, Map<K2, V>> entry : underlyingMap.entrySet()) {
Map<K2,V> map = entry.getValue();
V value = map.remove(key2);
if (value != null) {
result.add(value);
}
if (map.isEmpty()) {
remove(entry.getKey());
}
}
return result;
}
/**
* Calculates the total size of all inner maps
* @return total size
*/
public int deepSize() {
int result = 0;
for(Map<K2,V> map : values()) {
result += map.size();
}
return result;
}
/**
* Returns a set of all inner keys
* @return set of inner keys
*/
public Set<K2> deepKeys() {
Set<K2> result = new HashSet<K2>();
for(Map<K2,V> map : values()) {
result.addAll(map.keySet());
}
return result;
}
/**
* Returns a list of all inner values
* @return list of inner values
*/
public List<V> deepValues() {
List<V> result = new ArrayList<V>();
for(Map<K2,V> map : values()) {
result.addAll(map.values());
}
return result;
}
/**
* Returns a list of all inner entries
* @return list of inner entries
*/
public List<Entry<K2,V>> deepEntries() {
List<Entry<K2,V>> result = new ArrayList<Entry<K2,V>>();
for(Map<K2,V> map : values()) {
result.addAll(map.entrySet());
}
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T18:26:20.220",
"Id": "44195",
"Score": "0",
"body": "Hi, could you elaborate on what exactly you are trying to accomplish with your map of maps? By doing so, it would help us comment on your questions towards the end of your description regarding the api."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T03:39:07.527",
"Id": "44209",
"Score": "0",
"body": "How is this different from Guava's [Table](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T06:27:49.390",
"Id": "44211",
"Score": "0",
"body": "@jramoyo You are right, I overlooked that one..."
}
] |
[
{
"body": "<p>Rather than making a map of maps (<code>Map<K1,Map<K2,V>></code>), I find it often easier to make a map that uses a composite key : <code>Map<Key<K1, K2>, V></code>.</p>\n\n<p>You could make a generic <code>Key</code> class for this, or make a dedicated class on a per case basis since sometimes this key makes sense business-wise : e.g. Buyer - Seller -> Contract.</p>\n\n<p>Nevertheless, if you use a generic <code>Key</code> class (make sure <code>equals()</code> and <code>hashCode()</code> are implemented properly), you could still have use for a variant of your <code>MapMap</code>, that takes individual <code>K1</code> and <code>K2</code> objects and combines them into a key behind the scenes. But I think you'll find that a <code>Key</code> class with a static factory method is easy enough to use :</p>\n\n<p>getting :</p>\n\n<pre><code>V value = map.get(key(k1, k2));\n</code></pre>\n\n<p>or putting :</p>\n\n<pre><code>map.put(key(k1, k2), value);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T18:04:14.283",
"Id": "44189",
"Score": "1",
"body": "I have often the \"asymmetric\" situation that I always know `K1`, but not necessarily `K2`, so I would need to scan through the whole map if I would use a compound key. I agree that your version is clearly better if both keys are always known."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T20:09:53.790",
"Id": "44198",
"Score": "0",
"body": "A `Comparator` on `Key` and using a `SortedMap` will allow you to easily find all keys that have a certain `K1` value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T21:50:01.580",
"Id": "44205",
"Score": "0",
"body": "That sounds good, I'll try it out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T15:50:46.577",
"Id": "28255",
"ParentId": "28252",
"Score": "6"
}
},
{
"body": "<p>Guava's <code>Table<K1,K2,V></code> interface looks like exactly what you need for this.</p>\n\n<blockquote>\n <p>Typically, when you are trying to index on more than one key at a time, you will wind up with something like <code>Map<FirstName, Map<LastName, Person>></code>, which is ugly and awkward to use. Guava provides a new collection type, <code>Table</code>, which supports this use case for any \"row\" type and \"column\" type</p>\n</blockquote>\n\n<p>There are 4 provided implementations of this interface for different use cases, detailed <a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table\" rel=\"nofollow\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-23T09:35:15.323",
"Id": "63654",
"ParentId": "28252",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "63654",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T13:55:52.490",
"Id": "28252",
"Score": "4",
"Tags": [
"java",
"collections"
],
"Title": "Class for Map of Maps"
}
|
28252
|
<p>I got bored recently and wrote a tool to re-order out of order classes in Python files. This can occur with some auto-generation code tools for databases and the like; these files can sometimes be thousands of classes big.</p>
<p>I've posted it here to gauge its general utility and get feedback on the code (logic flow, readability, etc).</p>
<p>mr_agreeable is the tool and classes_test is the out of order test script.</p>
<p><strong>mr_agreeable.py:</strong></p>
<pre><code>import os
import sys
from codecs import encode
from random import randint
import getopt
import inspect
import types
__doc__ = \
'''
A python script that re-orders out of sequence class defintions
'''
class rebase_meta(type):
'''
Rebase metaclass
Automatically rebases classes created with this metaclass upon
modification of classes base classes
'''
org_base_classes = {}
org_base_classes_subs = {}
base_classes = {}
base_classes_subs = {}
mod_loaded = False
mod_name = ""
mod_name_space = {}
def __init__(cls, cls_name, cls_bases, cls_dct):
#print "Making class: %s" % cls_name
super(rebase_meta, cls).__init__(cls_name, cls_bases, cls_dct)
# Remove the old base sub class listings
bases = rebase_meta.base_classes_subs.items()
for (base_cls_name, sub_dict) in bases:
sub_dict.pop(cls_name, None)
# Add class to bases' sub class listings
for cls_base in cls_bases:
if(not rebase_meta.base_classes_subs.has_key(cls_base.__name__)):
rebase_meta.base_classes_subs[cls_base.__name__] = {}
rebase_meta.base_classes[cls_base.__name__] = cls_base
rebase_meta.base_classes_subs[cls_base.__name__][cls_name] = cls
# Rebase the sub classes to the new base
if(rebase_meta.base_classes.has_key(cls_name)): # Is class a base class
subs = rebase_meta.base_classes_subs[cls_name]
rebase_meta.base_classes[cls_name] = cls # Update base class dictionary to new class
for (sub_cls_name, sub_cls) in subs.items():
if(cls_name == sub_cls_name):
continue
sub_bases_names = [x.__name__ for x in sub_cls.__bases__]
sub_bases = tuple([rebase_meta.base_classes[x] for x in sub_bases_names])
try:
# Attempt to rebase sub class
sub_cls.__bases__ = sub_bases
#print "Rebased class: %s" % sub_cls_name
except TypeError:
# The old sub class is incompatible with the new base class, so remake the sub
if(rebase_meta.mod_loaded):
new_sub_cls = rebase_meta(sub_cls_name, sub_bases, dict(sub_cls.__dict__.items() + [("__module__", rebase_meta.mod_name)]))
rebase_meta.mod_name_space[sub_cls_name] = new_sub_cls
else:
new_sub_cls = rebase_meta(sub_cls_name, sub_bases, dict(sub_cls.__dict__.items()))
subs[sub_cls_name] = new_sub_cls
@classmethod
def register_mod(self, imod_name, imod_name_space):
if(not self.mod_loaded):
self.org_base_classes = self.base_classes.copy()
self.org_base_classes_subs = self.base_classes_subs.copy()
self.mod_loaded = True
else:
self.base_classes = self.org_base_classes
self.base_classes_subs = self.org_base_classes_subs
self.mod_name = imod_name
self.mod_name_space = imod_name_space
# Can't subclass these classes
forbidden_subs = \
[
"bool",
"buffer",
"memoryview",
"slice",
"type",
"xrange",
]
# Builtin, sub-classable classes
org_class_types = filter(lambda x: isinstance(x, type) and (not x.__name__ in forbidden_subs) and x.__module__ == "__builtin__", types.__builtins__.values())
# Builtin classes recreated with Rebasing metaclass
class_types = [(cls.__name__, rebase_meta(cls.__name__, (cls,), {})) for cls in org_class_types]
# Overwrite builtin classes
globals().update(class_types)
class mr_quiet(dict):
'''
A namespace class that creates placeholder classes upon
a non existant lookup. mr_quiet does not say much.
'''
def __getitem__(self, key):
if(not key in self.keys()):
if(hasattr(__builtins__, key)):
return getattr(__builtins__, key)
else:
if(not key in self.keys()):
self.sanity_check()
return self.setdefault(key, rebase_meta(key, (object,), {}))
else:
return dict.__getitem__(self, key)
def sanity_check(self):
pass
class mr_agreeable(mr_quiet):
'''
A talkative cousin of mr_quiet.
'''
sin_counter = 0
nutty_factor = 0
rdict = {0 : (0, 9), 200 : (10, 14), 500 : (15, 16), 550 : (17, 22)}
def sanity_check(self):
self.prognogsis()
print self.insanity()
def prognogsis(self):
self.sin_counter += 1
self.nutty_factor = max(filter(lambda x: x < self.sin_counter, self.rdict.keys()))
def insanity(self):
insane_strs = \
[
"Nofbyhgryl", "Fher, jul abg?", "Sbe fher", "Fbhaqf terng", "Qrsvangryl", "Pbhyqa'g nterr zber",
"Jung pbhyq tb jebat?", "Bxl Qbnxl", "Lrc", "V srry gur fnzr jnl", "Zneel zl qnhtugre",
"Znlor lbh fubhyq svk gung", "1 AnzrReebe vf bar gbb znal naq n 1000'f abg rabhtu", "V'ir qbar qvegvre guvatf",
"Gur ebbz vf fgnegvat gb fcva", "Cebonoyl abg", "Npghnyyl, ab ..... nyevtug gura", "ZNXR VG FGBC",
"BU TBQ AB", "CYRNFR AB", "LBH'ER OERNXVAT CLGUBA", "GUVF VF ABG PBAFRAGHNY", "V'Z GRYYVAT THVQB!!"
]
return encode("ze_nterrnoyr: " + insane_strs[randint(*self.rdict[self.nutty_factor])], "rot13")
def coll_up(ilist, base = 0, count = 0):
'''
Recursively collapse nested lists at depth base and above
'''
tlist = []
if(isinstance(ilist, __builtins__.list) or isinstance(ilist, __builtins__.tuple)):
for q in ilist:
tlist += coll_up(q, base, count + 1)
else:
if(base > count):
tlist = ilist
else:
tlist = [ilist]
return [tlist] if((count != 0) and (base > count)) else tlist
def build_base_dict(ilist):
'''
Creates a dictionary of class : class bases pairs
'''
base_dict = {}
def build_base_dict_helper(iclass, idict):
idict[iclass] = list(iclass.__bases__)
for x in iclass.__bases__:
build_base_dict_helper(x, idict)
for cur_class in ilist:
build_base_dict_helper(cur_class, base_dict)
return base_dict
def transform_base_to_sub(idict):
'''
Transforms a base dict into dictionary of class : sub classes pairs
'''
sub_dict = {}
classes = idict.keys()
for cur_class in idict:
sub_dict[cur_class] = filter(lambda cls: cur_class in idict[cls], classes)
return sub_dict
recur_class_helper = lambda idict, ilist = []: [[key, recur_class_helper(idict, idict[key])] for key in ilist]
recur_class = lambda idict: recur_class_helper(idict, idict.keys())
class proc_func(list):
'''
Cmdline processing class
'''
def __init__(self, name = "", *args, **kwargs):
self.name = name
super(list, self).__init__(*args, **kwargs)
def get_args(self, *args):
self.extend(filter(lambda x: x, args))
def __call__(self, *args):
print self.name
print self
class proc_inputs(proc_func):
def get_args(self, *args):
self.extend(filter(os.path.isfile, args))
class proc_outputs(proc_func):
pass
class proc_helper(proc_func):
'''
Help function
Print help information
'''
def get_args(self, *args):
self()
def __call__(self, *args):
print __file__
print __doc__
print "Help:\n\t%s -h -i inputfile -o ouputfile" % sys.argv[0]
print "\t\t-h or --help\tPrint this help message"
print "\t\t-i or --input\tSpecifies the input script"
print "\t\t-o or --output\tSpecifies the output script"
sys.exit()
if __name__ == "__main__":
proc_input = proc_inputs("input")
proc_output = proc_outputs("output")
proc_help = proc_helper("help")
cmd_line_map = \
{
"-i" : proc_input,
"--input" : proc_input,
"-o" : proc_output,
"--ouput" : proc_output,
"-h" : proc_help,
"--help" : proc_help
}
try:
optlist, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help", "input=", "output="])
for (key, value) in optlist:
cmd_line_map[key].get_args(value)
except getopt.GetoptError:
proc_help()
if(len(proc_input) != len(proc_output)):
print "Input files must have a matching output file"
proc_help()
elif(not proc_input):
proc_help()
else:
in_out_pairs = zip(proc_input, proc_output)
for (in_file, out_file) in in_out_pairs:
dodgy_module_name = os.path.splitext(in_file)[0]
sys.modules[dodgy_module_name] = types.ModuleType(dodgy_module_name)
sys.modules[dodgy_module_name].__file__ = in_file
# Make a fake space post haste
name_space = mr_agreeable\
(
[
("__name__", dodgy_module_name), # Needed for the created classes to identify with the 'module'
("__module__", dodgy_module_name), # Needed to fool the inspect module
] + \
class_types
)
# Exclude these from returning
exclusions = name_space.keys()
# Associate the fake name space to the rebasing metaclass
rebase_meta.register_mod(dodgy_module_name, name_space)
# Run dodgy code
execfile(in_file, name_space)
# Bring back dodgy classes
import_classes = [cls if(isinstance(cls, type) and not cls_name in exclusions) else None for (cls_name, cls) in name_space.items()]
dodgy_import_classes = filter(lambda x: x, import_classes)
# Create base and sub class dictionaries
base_dict = build_base_dict(dodgy_import_classes)
sub_dict = transform_base_to_sub(base_dict)
# Create sets of base and sub classes
base_set = reduce(lambda x, y: x | y, map(set, base_dict.values()), set([]))
sub_set = reduce(lambda x, y: x | y, map(set, sub_dict.values()), set([]))
kings = list(base_set - sub_set) # A list of bases which are not subs
kingdoms = recur_class_helper(sub_dict, kings) # A subclass tree of lists
lineages = coll_up(kingdoms, 2) # Flatten the tree branches at and below 2nd level
# Filter only for the clases created in the dodgy module
inbred_lines = [filter(lambda x: x.__module__ == dodgy_module_name, lineage) for lineage in lineages]
# Load Source
for lineage in inbred_lines:
for cls in lineage:
setattr(cls, "_source", inspect.getsource(cls))
# Write Source
with open(out_file, "w") as file_h:
for lineage in inbred_lines:
for cls in lineage:
file_h.write(cls._source + "\n")
</code></pre>
<p><strong>classes_test.py:</strong></p>
<pre><code>class ChildC(ChildB):
name = "childc"
childc_unique = "childc"
pass
class ChildB(ChildA):
name = "childb"
childb_unique = "childb"
pass
class ChildA(ParentModel):
name = "childa"
childa_unique = "childa"
pass
class ParentModel(object):
name = "parentmodel"
parentmodel_unique = "parentmodel"
pass
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-04T20:54:56.387",
"Id": "98776",
"Score": "0",
"body": "Can you describe the problem in more detail? What auto-generation code? What databases? What goes wrong? Why does it go wrong? Why is your solution better than fixing the auto-generation code? etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-05T02:12:54.823",
"Id": "98831",
"Score": "0",
"body": "@GarethRees, I'm not suggesting that it is a permanent solution; it's a bandaid for broken code, which could quite probably be unmaintained/proprietary. The exact software doesn't matter, if it produces python source files containing thousands of classes, which are unordered, then this can resolve the code."
}
] |
[
{
"body": "<p>Some tidbits:</p>\n\n<p>Might be anal, but I would have sorted my imports differently. For me it just makes it easier to find what I am looking for, but I can see why you might separate the way you did:</p>\n\n<pre><code>import getopt\nimport inspect\nimport os\nimport sys\nimport types\n\nfrom codecs import encode\nfrom random import randint\n</code></pre>\n\n<p>Classes should be camelcase (pep8 compliance)</p>\n\n<pre><code>RebaseMeta\n</code></pre>\n\n<p>For lines:</p>\n\n<pre><code>if(not rebase_meta.base_classes_subs.has_key(cls_base.__name__)):\nif(not self.mod_loaded):\nif(cls_name == sub_cls_name):\n</code></pre>\n\n<p>I might write as (remove extraneous parens):</p>\n\n<pre><code>if not rebase_meta.base_classes_subs.has_key(cls_base.__name__):\nif not self.mod_loaded:\nif cls_name == sub_cls_name:\n</code></pre>\n\n<p>These lines are already readable, not sure if the extra parens is buying anything other than preference. I prefer to save the 1 or 2 keystrokes. =)</p>\n\n<p>For line:</p>\n\n<pre><code>org_class_types = filter(lambda x: isinstance(x, type) and (not x.__name__ in\n</code></pre>\n\n<p>Consider making this multiline to be pep8 compliant. (79 chars max)</p>\n\n<p>Ditto here:</p>\n\n<pre><code>class_types = [(cls.__name__, rebase_meta(cls.__name__, (cls,), {})) for cls in org_class_types]\n</code></pre>\n\n<p>Line:</p>\n\n<pre><code>class mr_quiet\n</code></pre>\n\n<p>CamelCase preferred per pep8. MisterQuiet</p>\n\n<p>More ditch the parens:</p>\n\n<pre><code>for (key, value) in optlist:\n</code></pre>\n\n<p>Consider creating a def main(), and changing your if <strong>name</strong> statment to:</p>\n\n<pre><code>if__name__ == __main__:\n sys.exit(main())\n</code></pre>\n\n<p> \n </p>\n\n<p>Hopefully some of these idioms are helpful. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-10T05:41:10.820",
"Id": "56626",
"ParentId": "28254",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T14:11:49.530",
"Id": "28254",
"Score": "7",
"Tags": [
"python",
"sorting",
"python-2.x",
"inheritance"
],
"Title": "Out of order class resequencer"
}
|
28254
|
<p>Building on my previous questions. I've managed to make a GUI that queries a SQL database and displays the result in a table. Christ, it's a lot of work for such a simple activity. </p>
<p>The code below works. Does it adhere to MVC conventions? If I understand correctly, <code>MainFrame</code> and <code>CustomTable</code> are the "View" classes. They format and present data in the GUI. <code>Student</code> and its subclasses are the "Model" classes. They hold the data retrieved from the database. Misc is the "Controller" class. It queries the database, instantiates Model class objects to hold the data, then passes the Model data to the View classes. Do I have that right?</p>
<p>Apologies in advance for the null layout and bad error handling. They're two area I haven't studied sufficiently.</p>
<p>There are 4 classes I'm not posting. <code>Student</code> and its three subclasses <code>Undergraduate</code>, <code>Graduate</code>, and <code>PartTime</code>. Each class has properties that correspond to columns in a database table. And each instantiated object should correspond to a row in the table.</p>
<p><strong>MainFrame class:</strong></p>
<pre><code>package kft1task4;
import javax.swing.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.JScrollPane;
public class MainFrame extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JButton butt = new JButton("Push Me To Update The Table");
CustomTable ct = new CustomTable();
JTable tab = new JTable(ct);
MainFrame() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(1000,200,1500,1000);
pane.setLayout(null);
add(pane);
butt.setBounds(20,550,200,100);
butt.addActionListener(this);
pane.add(butt);
JScrollPane jsp = new JScrollPane(tab);
jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jsp.setBounds(20,50,1460,500);
pane.add(jsp);
}
@Override
public void actionPerformed(ActionEvent e) {
try{
ct.reQuery();
}
catch (ClassNotFoundException f){System.out.println("Exception");}
catch (InstantiationException f){System.out.println("Exception");}
catch (IllegalAccessException f){System.out.println("Exception");}
catch (SQLException f){System.out.println("Exception");}
}
}
</code></pre>
<p><strong>CustomTable class:</strong></p>
<pre><code>package kft1task4;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.sql.SQLException;
public class CustomTable extends AbstractTableModel {
String[] colName = {"Classification", "Student ID", "First Name", "Last Name", "Status", "Mentor", "GPA", "Credit Hours", "Level", "Thesis Titile", "Thesis Advisor", "Company"};
ArrayList<Student> students = new ArrayList<Student>();
public String getColumnName(int col){
return colName[col];
}
public int getColumnCount(){
return colName.length;
}
public int getRowCount(){
return students.size();
}
@Override
public String getValueAt(int row, int col){
int j = 10;
switch (col){
case 0: return students.get(row).getClass().toString().replace("class kft1task4.", "");
case 1: return Integer.toString(students.get(row).studentID);
case 2: return students.get(row).nameFirst;
case 3: return students.get(row).nameLast;
case 4: return students.get(row).status;
case 5: return students.get(row).mentor;
case 6: return Double.toString(students.get(row).gpa);
case 7: return Integer.toString(students.get(row).creditHours);
case 8: if( students.get(row) instanceof Undergraduate){Undergraduate st = (Undergraduate)students.get(row); return st.level;} else {return null;}
case 9: if( students.get(row) instanceof Graduate){Graduate st = (Graduate)students.get(row); return st.thesisTitle;} else {return null;}
case 10: if( students.get(row) instanceof Graduate){Graduate st = (Graduate)students.get(row); return st.thesisAdvisor;} else {return null;}
case 11: if( students.get(row) instanceof PartTime){PartTime st = (PartTime)students.get(row); return st.company;} else {return null;}
default: return "Default";
}
}
public boolean isCellEditable(int col, int row){
return true;
}
@Override
public void setValueAt(Object s, int row, int col){
fireTableDataChanged();
}
public void reQuery() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
try{
students.clear();
students = Misc.query();
}
catch (ClassNotFoundException f){System.out.println("Exception");}
catch (InstantiationException f){System.out.println("Exception");}
catch (IllegalAccessException f){System.out.println("Exception");}
catch (SQLException f){System.out.println("Exception");}
fireTableDataChanged();
}
CustomTable() {
//reQuery();
}
}
</code></pre>
<p><strong>Misc class:</strong></p>
<pre><code>package kft1task4;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class Misc {
Misc(){
}
public static ArrayList<Student> query() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
ArrayList<Student> studs = new ArrayList<Student>();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/kft1task4?" + "user=root&password=");
Statement stmt = conn.createStatement();
String cl = "";
ResultSet rs = stmt.executeQuery("Select * from students");
while(rs.next()){
cl = rs.getString("class");
if(cl.equals("Undergraduate")){
studs.add(new Undergraduate(rs.getString("nameFirst"),rs.getString("nameLast"),rs.getInt("student_id"),rs.getDouble("gpa"),rs.getString("status"),rs.getString("mentor"),rs.getInt("creditHours"),rs.getString("level")));
}
else if(cl.equals("Graduate")){
studs.add(new Graduate(rs.getString("nameFirst"),rs.getString("nameLast"),rs.getInt("student_id"),rs.getDouble("gpa"),rs.getString("status"),rs.getString("mentor"),rs.getInt("creditHours"), rs.getString("thesisTitle"),rs.getString("thesisAdvisor")));
}
else if(cl.equals("PartTime")){
studs.add(new PartTime(rs.getString("nameFirst"),rs.getString("nameLast"),rs.getInt("student_id"),rs.getDouble("gpa"),rs.getString("status"),rs.getString("mentor"),rs.getInt("creditHours"),rs.getString("Company")));
}
}
conn.close();
stmt.close();
rs.close();
return studs;
} //end query method
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><pre><code>@Override\npublic void actionPerformed(ActionEvent e) {\n try {\n ct.reQuery();\n</code></pre>\n\n<p>Action listeners run on the <a href=\"https://en.wikipedia.org/wiki/Event_dispatching_thread\" rel=\"nofollow noreferrer\">Event dispatching thread</a> and they should be fast. Otherwise the GUI will be irresponsive. <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html\" rel=\"nofollow noreferrer\">Worker Threads and SwingWorker</a></p></li>\n<li><pre><code>conn.close();\nstmt.close();\nrs.close();\n</code></pre>\n\n<p>I guess they should be closed in the reverse order:</p>\n\n<pre><code>rs.close();\nstmt.close();\nconn.close();\n</code></pre>\n\n<p>Anyway, they should be closed in a <code>finally</code> block or with try-with-resources. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow noreferrer\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><p>The <code>Misc.query</code> method creates a new connection on every call. It could cache the <code>Connection</code> objects for lower latency.</p></li>\n<li><p>The if-elseif-elseif structure in the <code>Misc.query</code> method looks too complicated. Results of <code>rs.get*</code> calls which are used in every case could have local variables:</p>\n\n<pre><code>while (rs.next()) {\n String classname = rs.getString(\"class\");\n String firstname = rs.getString(\"nameFirst\");\n String lastname = rs.getString(\"nameLast\");\n ...\n}\n</code></pre>\n\n<p>Anyway, I'd go with JPA or Hibernate, they do this object-relational mapping quite well.</p></li>\n<li><pre><code>return students.get(row).getClass().toString().replace(\"class kft1task4.\", \"\");\n</code></pre>\n\n<p>This could be</p>\n\n<pre><code>return students.get(row).getClass().getSimpleName();\n</code></pre>\n\n<p>You could declare a <code>getName()</code> method in the <code>Student</code> class and override it in subclassess appropriately.</p></li>\n<li><p>Instead of printing the same <code>Exception</code> string I'd try to show a useful error message to the user and log the stacktrace of the exception. See: <a href=\"https://stackoverflow.com/q/2727500/843804\">log4j vs. System.out.println - logger advantages?</a> (I suggest you SLF4J with Logback.)</p></li>\n<li><p>A great comment from <a href=\"https://codereview.stackexchange.com/a/19459/7076\"><em>@tb-</em>'s answer</a>:</p>\n\n<blockquote>\n <p>Do not extend <code>JPanel</code>, instead have a private <code>JPanel</code> \n attribute and deal with it (Encapsulation). \n There is no need to give access to all \n <code>JPanel</code> methods for code dealing with a <code>UserPanel</code>\n instance. If you extend, you are forced to stay with this forever, \n if you encapsulate, you can change whenever you want without \n taking care of something outside the class.</p>\n</blockquote>\n\n<p>(Substitute <code>JPane</code> with <code>JFrame</code>.)</p></li>\n<li><p>Fields should be <code>private</code>. (<em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>)</p></li>\n<li><p>I would use longer variable and method names than <code>pane</code>, <code>ct</code> etc. Longer names would make the code more readable since readers don't have to decode the abbreviations every time when they write/maintain the code and don't have to guess which abbreviation the author uses.</p>\n\n<p><code>reQuery()</code> also could be <code>refresh()</code>.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p></li>\n<li><pre><code>JButton butt = new JButton(\"Push Me To Update The Table\");\n</code></pre>\n\n<p>This kind of behaviour usually referred as <em>refresh</em>, I'd use that as text.</p></li>\n<li><p><code>ArrayList<...></code> reference types should be simply <code>List<...></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>ArrayList<Student> students = new ArrayList<Student>();\n</code></pre>\n\n<p>Another one:</p>\n\n<pre><code>public static ArrayList<Student> query() ...\n</code></pre></li>\n<li><pre><code>CustomTable() {\n // reQuery();\n}\n</code></pre>\n\n<p>Constructors should be at (almost) the beginning of the class, then the other methods. (According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a>, 3.1.3 Class and Interface Declarations.)</p></li>\n<li><p>Commented out code is bad:</p>\n\n<pre><code>CustomTable() {\n // reQuery();\n}\n</code></pre>\n\n<blockquote>\n <p>Why are those two lines of code commented? Are they important? Were they left as\n reminders for some imminent change? Or are they just cruft that someone commented-out\n years ago and has simply not bothered to clean up.</p>\n</blockquote>\n\n<p>Source: <em>Robert C. Martin</em>: <em>Clean Code</em>, <em>Chapter 4: Comments</em>, <em>Commented-Out Code</em>:</p></li>\n<li><p>I'd give a more descriptive name to <code>Misc</code> which says the purpose of the class. (<code>StudentDatabase</code>, for example.)</p></li>\n<li><pre><code>String cl = \"\";\nResultSet rs = stmt.executeQuery(\"Select * from students\");\n\nwhile (rs.next()) {\n cl = rs.getString(\"class\");\n</code></pre>\n\n<p>About the <code>cl</code> variable: Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs could highlight blocks.</p>\n\n<pre><code>} // end query method\n</code></pre>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/q/53274/36726\">“// …” comments at end of code block after } - good or bad?</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T23:35:16.150",
"Id": "42996",
"ParentId": "28256",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T17:12:21.987",
"Id": "28256",
"Score": "5",
"Tags": [
"java",
"mvc"
],
"Title": "Combining a JFrame, AbstractTableModel, and SQL Query"
}
|
28256
|
<p>I wanted to eliminate some duplication and came up with something I've not seen so I figured I post it and see if others had.</p>
<p>Using a delegate to allow the method to return another call to itself.</p>
<p>The commented out code is what I replaced.</p>
<pre><code>delegate ChainRepositoryCommand ChainRepositoryCommand(Action<Data.Repository> action);
ChainRepositoryCommand RepositoryCommand(Action<Data.Repository> action)
{
using (var repo = new Data.Repository(true))
{
action(repo);
}
return new ChainRepositoryCommand(a => RepositoryCommand(a));
}
public void Register(ISender<T> sender)
{
RepositoryCommand
(repo => repo.AddClient(sender.Name, true))
(repo => repo.AddMessageType<T>())
(repo => repo.AddRegistration<T>(this.name, sender.Name));
//using (var repo = new Data.Repository(true))
//{
// repo.AddClient(sender.Name, true);
//}
//using (var repo = new Data.Repository(true))
//{
// repo.AddMessageType<T>();
//}
//using (var repo = new Data.Repository(true))
//{
// repo.AddRegistration<T>(this.name, sender.Name);
//}
sender.Sending += sender_Sending;
}
</code></pre>
<p>Update: I worked it into my repository class as a static method. I know this is all probably obfuscating from a clean code standpoint, but it's fun to experiment with new things from time to time.</p>
<pre><code>public class Repository : IDisposable
{
...
public delegate Chain Chain(Action<Repository> action);
public static Chain Command(Action<Repository> action)
{
using (var repo = new Data.Repository(true))
{
action(repo);
}
return new Chain(next => Command(next));
}
...
}
public class Server<T> : IServer<T>
{
...
public Server(string name)
{
serverName = name;
Data.Repository.Command
(repo => repo.AddServer(name));
}
public void Register(ISender<T> sender)
{
Data.Repository.Command
(repo => repo.AddClient(sender.Name, true))
(repo => repo.AddMessageType<T>())
(repo => repo.AddRegistration<T>(this.serverName, sender.Name));
sender.Sending += sender_Sending;
}
...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T20:10:42.257",
"Id": "44199",
"Score": "0",
"body": "That... Is rather interesting. And a little disturbing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T06:56:09.857",
"Id": "44343",
"Score": "0",
"body": "Your business logic and data access is intermingled, which defeats the purpose of repository pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T23:46:01.353",
"Id": "44422",
"Score": "0",
"body": "to which business logic are you referring? I admit I tend to think of a Repository as a general purpose wrapper around a data context..."
}
] |
[
{
"body": "<blockquote>\n <p>Using a delegate to allow the method to return another call to itself.</p>\n</blockquote>\n\n<p>You don't necessarily need a delegate to allow another call to itself. For example:</p>\n\n<pre><code>public class SimpleCalculation\n{\n private int result;\n\n public int Result\n {\n get { return result; }\n }\n\n public SimpleCalculation Add(int i)\n {\n result += i;\n return this;\n }\n\n public SimpleCalculation Subtract(int i)\n {\n result -= i;\n return this;\n }\n}\n\n//Usage:\nvar sc = new SimpleCalculation();\nsc.Add(5).Subtract(2);\nConsole.WriteLine(sc.Result); //Writes '3' to the screen\n</code></pre>\n\n<p>I'm not saying your code is wrong, only saying that you don't need delegates to achieve this. Also this:</p>\n\n<pre><code>//using (var repo = new Data.Repository(true))\n//{\n// repo.AddClient(sender.Name, true);\n//}\n//using (var repo = new Data.Repository(true))\n//{\n// repo.AddMessageType<T>();\n//}\n//using (var repo = new Data.Repository(true))\n//{\n// repo.AddRegistration<T>(this.name, sender.Name);\n//}\n</code></pre>\n\n<p>Could also be rewritten as:</p>\n\n<pre><code>using (var repo = new Data.Repository(true))\n{\n repo.AddClient(sender.Name, true);\n repo.AddMessageType<T>();\n repo.AddRegistration<T>(this.name, sender.Name);\n}\n</code></pre>\n\n<p>I don't know if you already knew or tried this but I'm just pointing it out as a possibility. But I agree with you: experimenting with code is fun! :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T07:04:03.697",
"Id": "28270",
"ParentId": "28259",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T18:34:52.677",
"Id": "28259",
"Score": "5",
"Tags": [
"c#",
"functional-programming"
],
"Title": "helper method returning a call to itself"
}
|
28259
|
<p>We are in the process of creating a book with the purpose of teaching people the art of html and CSS to create a website from scratch. In our book the focal point, so to say, is that the reader is given a webdesign that he converts into a website by himself.</p>
<p>The reader is given the webdesign for the website of a (fictive) restaurant. The website will, when finished by the reader, consist of just the front page and three almost identical sub pages (only the text content will differ).</p>
<p>To be sure of an ideal, down to Earth, basic and typical website we are asking for a code review of the HTML and CSS behind these pages that make up this website. We have strained our selves to keep the code short, simple, clean and strict.</p>
<p>The reviewers should keep in mind that the site ought to be illustrating</p>
<ul>
<li><strong>recommended methods in coding</strong> the different parts as well as</li>
<li><strong>best practice</strong> and</li>
<li><strong>recommended ways of organising the code</strong>, and the site should contain</li>
<li><strong>typical standard parts</strong> for a website to be basic and fundamental for a students learning.</li>
</ul>
<p>Please ask any relevant questions to clarify things. Below you will see first the entire html for the front page, then the CSS and then the HTML for a sub page. In the bottom you will find a screenshot of both front page and sub page.</p>
<p>(Note: The page is in Danish)</p>
<p>We hope for some useful feedback and hope you like it.</p>
<p><strong>HTML (frontpage index.html)</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/global.css">
<title>Eos Café</title>
</head>
<body>
<div id="container">
<header>
<a href="/"><img src="images/logo.jpg" alt="Eos Café" id="logo"></a>
<nav>
<a href="#">Menu</a>
<a href="#">Bestil</a>
<a href="#">Arrangementer</a>
<a href="#">Kontakt</a>
</nav>
</header>
<nav id="submenu">
<ul>
<li><a href="menu/forretter.html">Forretter</a></li>
<li><a href="menu/hovedretter.html">Hovedretter</a></li>
<li><a href="menu/desserter.html">Desserter</a></li>
<li><a href="#">Salater</a></li>
<li><a href="#">Supper</a></li>
<li><a href="#">Vine</a></li>
<li><a href="#">Drikke</a></li>
</ul>
</nav>
<section id="content">
<h1>Madforkælelse</h1>
<div id="text">
<div id="manchet">
<img src="images/coffeecup.jpg" alt="">
<p>Velkommen til Eos Café. Vi har de lækre retter på bordet og den helt rigtige vin. Kom ind og oplev maden og stemningen! Velkommen til Eos Café.</p>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempus accumsan tincidunt.<br>
Etiam eget sem nec massa facilisis vulputate. Fusce suscipit dictum sodales. Etiam tempus sollicitudin mauris ut eleifend. Duis aliquet lacus sit amet dolor blandit fermentum. Cras iaculis metus quis odio <a href="#">auctor fringilla</a>. Nunc tristique quam mi, in interdum felis. Cras lobortis vehicula ligula, quis condimentum mauris porttitor at. Cras in augue ut leo blandit fringilla blandit eget mi.</p>
</div>
<img id="img1" src="images/dummy1.jpg" alt="">
<img id="img2" src="images/dummy1.jpg" alt="">
<img id="img3" src="images/dummy3.jpg" alt="">
</section>
<footer>
<div id="openhours">
<h4>Åbningstider</h4>
<table cellspacing="0">
<tr>
<th colspan="2">Caféens åbningstider</th>
<th colspan="2">Køkkenets åbningstider</th>
</tr>
<tr>
<td>Man-tors</td>
<td>11.00-21.00</td>
<td>Man-tors</td>
<td>11.00-21.00</td>
</tr>
<tr>
<td>Fre-lør</td>
<td>11.00-22.00</td>
<td>Fre-lør</td>
<td>11.00-22.00</td>
</tr>
<tr>
<td>Søn</td>
<td>17.00-21.30</td>
<td>Søn</td>
<td>17.00-21.30</td>
</tr>
</table>
</div>
<div id="address">
<h4>Her bor vi</h4>
Adresse:<br>
Engsvinget 45<br>
3400 Hillerød<br>
Se kort
</div>
<div id="socialicons">
<hr>
&copy; Eos Café
<span>
Hold dig opdateret:
<img src="images/facebook.jpg" alt="Facebook">
<img src="images/google.jpg" alt="Google+">
<img src="images/twitter.jpg" alt="Twitter">
<img src="images/rss.jpg" alt="RSS">
</span>
</div>
</footer>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS (global.css)</strong></p>
<pre><code>* {margin: 0; padding: 0;} /*Fjerne standardegenskaber*/
/*GENERELT*/
section,
header,
footer {
position: relative;
}
body,
html {
background-color: #929292;
margin: 0;
padding: 0;
}
#container {
background-color: #e6e6e6;
margin: 0 auto; /*Centrering*/
width: 1000px;
}
nav a { /*Generelt til navigation*/
font-family: verdana;
text-decoration: none;
}
/*SIDEHOVED*/
header {
height: 160px;
background-color: white;
border-top: solid 3px #912124;
border-bottom: solid 1px #dad9d9;
padding: 20px 0 0 90px;
}
#logo {
width: 160px;
}
header nav { /*Topmenu*/
bottom: 20px;
height: 30px;
position: absolute;
right: 100px;
}
header nav a { /*Topmenu-links*/
color: #979696;
font-size: 14px;
margin: 0 10px;
padding-bottom: 5px;
text-transform: uppercase;
}
header nav a:hover {
border-bottom: solid 3px #912124;
color: #606060;
}
/*SIDEMENU*/
#submenu {
float: left;
width: 200px;
}
#submenu ul {
float: right;
list-style: none;
margin-top: 50px;
text-align: center;
}
#submenu ul a {
color: #912124;
font-size: 12px;
}
#submenu ul a:hover {
color: black;
}
#submenu li {
margin: 10px 0;
}
/*INDHOLD*/
section {
background-color: #ededed;
color: #1f1f1f;
float: right;
font-family: arial;
font-size: 12px;
padding: 50px 50px 50px 50px;
width: 650px; /*750px minus padding*/
}
section p {
margin: 5px 0;
}
section h1 {
color: #525252;
font-size: 24px;
margin-bottom: 20px;
text-transform: uppercase;
}
section #manchet,
h2 {
color: #912124;
font-family: georgia;
font-style: italic;
margin-bottom: 20px;
}
section #manchet img {
float: left;
margin-right: 10px;
}
section #text {
float: left;
padding: 0 20px 20px 0;
width: 400px;
}
section #img1 { height: 180px; float: right; }
section #img2 { clear: left; height: 180px; float: left;}
section #img3 { height: 180px; float: right; }
section a {
color: #6ba6c1;
}
section a:hover {
text-decoration: none;
}
/*SIDEFOD*/
footer, footer table {
color: white;
font-family: arial;
font-size: 12px;
}
footer {
background-color: #1f1f1f;
clear: both;
padding-top: 30px;
}
footer #openhours {
float: left;
padding-left: 300px;
width: 400px;
}
footer #address {
float: left;
}
footer th {
padding-right: 60px;
}
footer th,
footer td {
line-height: 150%;
}
footer h4 {
font-size: 14px;
margin-bottom: 10px;
text-transform: uppercase;
}
footer hr {
border-bottom: solid 1px #292929;
border-left: none;
border-right: none;
border-top: solid 1px #030303;
margin-bottom: 20px;
}
footer #socialicons {
clear: both;
margin: 0 auto; /*Centrering*/
padding: 20px 80px;
position: relative;
text-align: center;
text-transform: uppercase;
}
footer #socialicons span {
position: absolute;
right: 80px;
top: 42px;
}
/*UNDERSIDER*/
h2 {
font-size: 12px; /*Overskriv standardegenskaber*/
font-weight: normal;
}
.dish {
position: relative;
height: 97px;
}
.dish img {
float: left;
margin-right: 44px;
}
hr {
clear: both;
border: none;
border-top: solid 1px #dad9d9;
margin: 12px 0;
}
.dish span {
position: absolute;
right: 10px;
top: 0;
font-style: italic;
}
</code></pre>
<p><strong>HTML (subpage menu/forretter.html)</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="/css/global.css">
<title>Eos Café</title>
</head>
<body>
<div id="container">
<header>
<a href="/"><img src="/images/logo.jpg" alt="Eos Café" id="logo"></a>
<nav>
<a href="#">Menu</a>
<a href="#">Bestil</a>
<a href="#">Arrangementer</a>
<a href="#">Kontakt</a>
</nav>
</header>
<nav id="submenu">
<ul>
<li><a href="#">Forretter</a></li>
<li><a href="#">Hovedretter</a></li>
<li><a href="#">Desserter</a></li>
<li><a href="#">Salater</a></li>
<li><a href="#">Supper</a></li>
<li><a href="#">Vine</a></li>
<li><a href="#">Drikke</a></li>
</ul>
</nav>
<section id="content">
<hgroup>
<h1>Forretter</h1>
<h2>Menukort</h2>
</hgroup>
<div class="dish">
<img src="/images/dummy2.jpg" alt="#">
<h3>Flamberet and</h3>
<p>Med grønne æbler og hvid sovs.<br>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempus accumsan tincidunt. Etiam eget sem nec massa facilisis vulputate. Fusce suscipit dictum sodales.</p>
<span>Pris: 199,-</span>
</div>
<hr>
<div class="dish">
<img src="/images/dummy2.jpg" alt="#">
<h3>Flamberet and</h3>
<p>Med grønne æbler og hvid sovs.<br>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempus accumsan tincidunt. Etiam eget sem nec massa facilisis vulputate. Fusce suscipit dictum sodales.</p>
<span>Pris: 199,-</span>
</div>
<hr>
<div class="dish">
<img src="/images/dummy2.jpg" alt="#">
<h3>Flamberet and</h3>
<p>Med grønne æbler og hvid sovs.<br>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempus accumsan tincidunt. Etiam eget sem nec massa facilisis vulputate. Fusce suscipit dictum sodales.</p>
<span>Pris: 199,-</span>
</div>
</section>
<footer>
<div id="openhours">
<h4>Åbningstider</h4>
<table>
<tr>
<th colspan="2">Caféens åbningstider</th>
<th colspan="2">Køkkenets åbningstider</th>
</tr>
<tr>
<td>Man-tors</td>
<td>11.00-21.00</td>
<td>Man-tors</td>
<td>11.00-21.00</td>
</tr>
<tr>
<td>Fre-lør</td>
<td>11.00-22.00</td>
<td>Fre-lør</td>
<td>11.00-22.00</td>
</tr>
<tr>
<td>Søn</td>
<td>17.00-21.30</td>
<td>Søn</td>
<td>17.00-21.30</td>
</tr>
</table>
</div>
<div id="address">
<h4>Her bor vi</h4>
Adresse:<br>
Engsvinget 45<br>
3400 Hillerød<br>
Se kort
</div>
<div id="socialicons">
<hr>
&copy; Eos Café
<span>
Hold dig opdateret:
<img src="/images/facebook.jpg" alt="Facebook">
<img src="/images/google.jpg" alt="Google+">
<img src="/images/twitter.jpg" alt="Twitter">
<img src="/images/rss.jpg" alt="RSS">
</span>
</div>
</footer>
</div>
</body>
</html>
</code></pre>
<p><strong>Screenshot, frontpage:</strong></p>
<p><img src="https://i.stack.imgur.com/WkpOD.jpg" alt="Screenshot, frontpage"></p>
<p><strong>Screenshot, subpage:</strong></p>
<p><img src="https://i.stack.imgur.com/ksKBo.jpg" alt="Screenshot, subpage"></p>
<p><strong>Screenshot of the page on a larger screen:</strong></p>
<p><img src="https://i.stack.imgur.com/9Wh3x.jpg" alt="Screenshot, larger screen"></p>
|
[] |
[
{
"body": "<p>Your logo (resp. site title) should be in a <code>h1</code>. Otherwise your page (→ <code>body</code>) got <s>no heading</s> a wrong heading in the outline (see explanation below): <code><h1><a href=\"/\"><img src=\"images/logo.jpg\" alt=\"Eos Café\" id=\"logo\"></a></h1></code></p>\n\n<p>You could specify <a href=\"http://www.w3.org/TR/2014/WD-html5-20140617/embedded-content-0.html#dimension-attributes\" rel=\"nofollow noreferrer\"><code>width</code>/<code>height</code> attributes</a> for the <code>img</code>. (Thanks, <a href=\"https://codereview.stackexchange.com/users/32917/darcher\">@darcher</a>)</p>\n\n<p>Instead of <code><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></code> you could use the shorter HTML5 <a href=\"https://stackoverflow.com/q/4696499/1591669\">variant</a>: <code><meta charset=\"utf-8\"></code></p>\n\n<p>The links in the <code>nav</code> should (but don’t <em>have</em> to) be in a <code>ul</code> (which is very common). If you don’t want to use a list, you should at least use block elements around each link (<code>div</code> probably), otherwise the links will be listed in one line for users without CSS, making the navigation hard to use (because of no delimiters).</p>\n\n<p>Don’t start with <code>h4</code> in the <code>footer</code>. If you use <code>h1</code> for the site title (see above), use <code>h2</code>. Or use <code>section</code> explicitly, then you could use <code>h1</code> (or stay with <code>h2</code>).</p>\n\n<p>You could use the <code>time</code> element for the opening hours.</p>\n\n<p><code>hgroup</code> is gone. As there is no real alternative yet, use a <code>div</code> (resp. <code>p</code> if applicable) for the subheading/tagline (and group both, the heading and the subline, in <code>header</code>).</p>\n\n<p>You could use the <code>small</code> element for \"© Eos Café\".</p>\n\n<p>I don’t think that your uses of <a href=\"http://www.w3.org/TR/html5/grouping-content.html#the-hr-element\" rel=\"nofollow noreferrer\"><code>hr</code></a> is correct here (\"[…] a <strong>paragraph-level</strong> thematic break […]\").</p>\n\n<hr>\n\n<p>Znarkus asked in the comments, why the site title should be in a <code>h1</code>:</p>\n\n<p>It’s because of the <a href=\"http://www.w3.org/TR/html5/sections.html#headings-and-sections\" rel=\"nofollow noreferrer\">document outline</a> (note that the behaviour changed in the <a href=\"http://www.w3.org/html/wg/drafts/html/master/sections.html#sample-outlines\" rel=\"nofollow noreferrer\">Editor’s Draft</a>, but we’d have to wait to see what happens to it in the future; it’s <a href=\"http://lists.w3.org/Archives/Public/public-html/2013Apr/0001.html\" rel=\"nofollow noreferrer\">discussed</a> on the mailing list). I <a href=\"https://stackoverflow.com/a/14920215/1591669\">explained it</a> some time ago on Stack Overflow, too (which might be easier to follow than this try here ;)).</p>\n\n<p>In HTML5, every sectioning element/root has an own heading, so to speak, even if you don’t explicitly provide one. If you don’t, you’ll get an <em>implied</em> heading (→ \"untitled\" section in the document outline). Practically that means, if you use sectioning elements correctly everywhere, you wouldn’t have to provide a heading at all, and you’d still get a perfect outline (but of course this would be a bad practice).</p>\n\n<p>Now the problem in this example document is, that there are also headings that are not included in a sectioning element. As the <code>body</code> is a sectioning root, it longs for a heading. And it finds one: the <code>h4</code> in the footer: \"Åbningstider\", because it is the first heading that is not part of a sectioning element (<code>section</code>, <code>article</code>, <code>nav</code>, <code>aside</code>). That means that the document outline will look like:</p>\n\n<blockquote>\n <ul>\n <li>1: Åbningstider (the first <code>h4</code> in the <code>footer</code>)\n \n <ul>\n <li>1.1: <em>Untitled</em> (the <code>nav</code>, missing a heading)</li>\n <li>1.2; <em>Untitled</em> (the <code>nav</code> (submenu), missing a heading)</li>\n <li>1.3: Madforkælelse (the <code>h1</code> in the <code>section</code>)</li>\n </ul></li>\n <li>2: Her bor vi (the <code>h4</code> in the <code>footer</code>)</li>\n </ul>\n</blockquote>\n\n<p>This is of course <strong>wrong</strong>. The page heading shouldn’t be \"Åbningstider\" nor \"Her bor vi\".</p>\n\n<p>If we’d enclose the sections (introduced by the <code>h4</code>s) in the footer in sectioning elements, we’d get the following outline:</p>\n\n<blockquote>\n <ul>\n <li>1: <em>Untitled</em> (the <code>body</code>, missing a heading)\n \n <ul>\n <li>1.1: <em>Untitled</em> (the <code>nav</code>, missing a heading)</li>\n <li>1.2: <em>Untitled</em> (the <code>nav</code> (submenu), missing a heading)</li>\n <li>1.3: Madforkælelse (the <code>h1</code> in the <code>section</code>)</li>\n <li>1.4: Åbningstider (the section in the <code>footer</code>)</li>\n <li>1.5: Her bor vi (the section in the <code>footer</code>)</li>\n </ul></li>\n </ul>\n</blockquote>\n\n<p>Now this outline is correct. But the untitled top-heading is, of course, ugly. Let’s think about what the correct heading would be: It should be a heading that describes <em>all</em> sub-sections (1.1 to 1.5), that is, <em>everything</em> that is included in the page. There can only be one answer: The site title. It describes the <strong>site-wide</strong> navigation and the <strong>site-wide</strong> footer. </p>\n\n<p>You can’t use the main content heading as <strong>page</strong> heading, because the site-wide navigation is <em>not</em> in scope of the main content. There is typically only one case where you can use the main content heading as the page heading: if there is no \"site\", i.e. if there is no navigation/footer/sidebar (that would be a stand-alone document).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T09:44:48.430",
"Id": "44355",
"Score": "0",
"body": "Why should `h1` be the site title? The `h1` should be the page title imo, which it is in the question's code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T11:14:01.080",
"Id": "44357",
"Score": "0",
"body": "@Znarkus: I edited my answer. Please comment again if anything is still unclear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T19:59:13.557",
"Id": "44397",
"Score": "0",
"body": "I understood what you meant, but think it's wrong :) Every page on the site could be thought of as a document, and the h1 is the document title. So for the contact page the h1 would be \"Contact us\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T06:38:46.857",
"Id": "44442",
"Score": "0",
"body": "@Znarkus: Yes, the `h1` (or whatever level, they don’t really matter if you use sectioning elements) of the **main content** would be \"Contact us\". But do you think the **main navigation** (containing links to the about page, the front page etc.) could be described by the heading \"Contact us\"? \"Contact us\" only describes a *section* of the page (→ the main content), but not *everything* on the page (→ the site-wide navigation, the site-wide footer, sidebars etc.). (By using HTML5, it can be automatically extracted which is the main content.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T06:45:36.413",
"Id": "44443",
"Score": "0",
"body": "@Znarkus: Also: the `h1` is not the document title. That would be the `title` element. In a HTML5 document using sectioning elements everywhere where needed, you could use only `h1`, if you like. The sectioning elements describe the nesting level, not the `h1`-`h6` elements. Now there are typically two headings that could be considered most important: the main content heading, and the page heading. They are (typically) not the same!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-25T22:50:14.953",
"Id": "96851",
"Score": "0",
"body": "also should add image dimensions to this response, e.g. height/width. Some Microdata/RDFa suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T05:37:35.130",
"Id": "96880",
"Score": "0",
"body": "@darcher: Thanks, good suggestions. I added `width`/`height` to my answer. However, I don’t think that Microdata/RDFa would be on-topic as this code is for OP’s teaching book and it seems that Microdata/RDFa aren’t topics there."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T15:39:50.807",
"Id": "28295",
"ParentId": "28261",
"Score": "5"
}
},
{
"body": "<p>As this site is for teaching purposes and since I am a student, I would suggest you include every possible HTML tag and CSS property. I noticed HTML tags like <code><b></code>, <code><i></code>, <code><em></code>, etc. are not used. I know such tags are not of much importance when we are using CSS, but it will be very helpful to readers. Also, include a page for making a simple form on the website. Forms are widely used on websites, and it would greatly help the readers and beginners.</p>\n\n<p>Rather than only making them prepare an external CSS stylesheet, include some internal and inline CSS code to explain the difference between each and their execution.</p>\n\n<p>These were just some suggestions on my part. I hope I could help you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T18:46:13.093",
"Id": "79012",
"Score": "2",
"body": "The use of `<b>` and `<i>` should only be used as a last resort in HTML5 but I would expect `<strong>`, `<em>` and `<form>` elements in a project like this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T11:49:09.733",
"Id": "29057",
"ParentId": "28261",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28295",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T20:29:06.137",
"Id": "28261",
"Score": "10",
"Tags": [
"html",
"css",
"html5"
],
"Title": "Strict and clean HTML and CSS for teaching website"
}
|
28261
|
<p>I'm working on a simple CMS. It's working quite ok, but I think my code can be improved a bit. I work with a section.php, which is included from the index.php with (example):</p>
<pre><code>switch($_GET['key'])
{
case '': $page='section'; $id='1'; break;
case 'home': $page='section'; $id='1'; break;
}
include ('header.php');
include ($page.'.php');
include ('footer.php');
</code></pre>
<p>But I would like some feedback on my section.php code. I have very little knowledge of OOP, but if possible I would like to use it for section.php. I used it a little for <code>$validator</code> which checks for clean URLs. But I have trouble with re-using the same <code>$sql_queries</code>.</p>
<p>section.php:</p>
<pre><code><?php
#-------------------------------------------#
# SIDEBAR #
#-------------------------------------------#
echo "<div id='sidebar'>";
$result = mysql_query('SELECT ID,title,tagline FROM cmsarticles WHERE section = '.$id.' ORDER BY id ASC LIMIT 4');
while ($row = mysql_fetch_array($result)){
$path = 'photos/';
$safeid = $validator->clean_url($row['title'].'-'.$row['ID']);
$get_photo = "SELECT name,artId,posId FROM images WHERE artId = ".$row['ID']." AND posId = 2 LIMIT 3";
$photothumbs = mysql_query($get_photo) or die(mysql_error());
while($photothumb = mysql_fetch_array($photothumbs)){
echo '<a rel="group_image" href="photos/'.$photothumb['name'].'"><img class="photo" src='.$path.'thumb_'.$photothumb['name'].' title="'.$row['title'].'" width="250"></a>';
}
}
echo "</div>";
#-------------------------------------------#
# CONTENT #
#-------------------------------------------#
echo "<div id='content'>";
$query= mysql_query('SELECT cmsarticles.ID AS artID, cmsarticles.title, cmsarticles.tagline, cmsarticles.thearticle, cmsarticles.section, cmssections.ID, cmssections.name
FROM cmsarticles, cmssections
WHERE cmsarticles.section = cmssections.ID
AND cmsarticles.section ='.$id.' ORDER BY cmsarticles.ID ASC');
$num_results = mysql_num_rows($query);
if ($num_results == 0){
echo 'Nothing here at the moment.';
}else{
while($result = mysql_fetch_array($query)) {
$safeid = $validator->clean_url($result['title'].'-'.$result['artID']);
echo "<div id=id".$result['artID']." class='article'>
<h1>".$result['title']."</h1>";
$query2 = mysql_query('SELECT name,artId,posId FROM images WHERE artId = '.$result['artID'].' AND posId = 1 LIMIT 1');
while($result2 = mysql_fetch_array($query2)){
echo '<img src=photos/'.$result2['name'].'>';
}
echo"<p>".$result['thearticle']."</p>
</div>";
}
}
echo "</div>";
?>
</code></pre>
|
[] |
[
{
"body": "<p>Well,\nfirst of all, OOP is not something you simply use. OOP is a concept of classes and objects. But it doesnt magically make your code better.</p>\n\n<p>Your main problem here is that your business logic is tightly coupled with you displaying of date (the view). You are fetching data, validating data and rendering the output all in the same file and on the same line. You should look in to <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> and <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">Separation of Concerns</a></p>\n\n<p>What I would start with is removing all business logic from your html. Thus creating a file that fetches all the data and stores it in a variable (e.g. $data) and a template file that only contains html and some statements (ofcourse foreach loops for lists are also user). This way you can develop templates without having to worry about messing up your business logic.</p>\n\n<p>To sume up: OOP is never an answer. OOP is simply a concept, just like functional programming is a concept. If used correctly they can be very powerfull. And that is the fun part of PHP, it supports both.</p>\n\n<p>Then some remarks ad your SQL:\nWhat you are doing is the following:</p>\n\n<pre><code>1st query: Fetch me the last 4 cmsarticles from section $section\n2nd query: Fetch me all cmsarticles from section $section, and append the section.name to it from section $section\n</code></pre>\n\n<p>This could be rewritten to:</p>\n\n<pre><code>1st query: Fetch me the section.name from section $section\n2nd query: Fetch me all cmsarticles from section $section\n</code></pre>\n\n<p>The queries will perform faster since you are simply looking up one table. And it will use less memory since the section.name in your current 2nde query will always be the same.</p>\n\n<p>I hope this answer helps you! feel free to ask some more</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:44:28.257",
"Id": "44274",
"Score": "0",
"body": "Thank you very much! I'll try to improve my code with your tips."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:58:01.643",
"Id": "44292",
"Score": "0",
"body": "Btw, DON'T use mysql_* functions. http://www.php.net/manual/en/function.mysql-connect.php see the big red warning? read it ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T17:51:57.013",
"Id": "44377",
"Score": "0",
"body": "It's on my to-do list to rewrite the system to mysqli. But i'm assuming it will take some time so i've postponed it a little. There's no way around the warning hah!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T09:37:02.357",
"Id": "28278",
"ParentId": "28262",
"Score": "2"
}
},
{
"body": "<p>I'd rewrite the <strong>first part</strong> like this:</p>\n\n<pre><code>if(empty($_GET['key']) or !strcmp($_GET['key'], 'home')){\n $page = 'section';\n $id = 1; // integer not string\n}elseif(!strcmp($_GET['key'], 'blahblah')){\n $page = 'blahblah';\n $id = 2; // integer not string\n} // ...\ninclude ('header.php');\ninclude (\"{$page}.php\");\ninclude ('footer.php');\n</code></pre>\n\n<ul>\n<li>Switch for strings is not always the best idea. You might want case insensitive compare and that's the <code>strcasecmp</code> realm.</li>\n<li>If <code>$_GET['key']</code> is missing, you will get a notice with the switch while <code>empty()</code> is safe.</li>\n<li><code>$id</code> seems to be an integer <code>1</code> so why make it a string <code>'1'</code>?</li>\n<li>Why concatenate like this <code>$page.'.php'</code> when you can have php do it for you <code>\"{$page}.php\"</code>?</li>\n</ul>\n\n<p>As of the <strong>second part</strong>, things are not too great:</p>\n\n<ul>\n<li>Why concatenate on <code>echo</code> like this <code>echo 'string'.'string'</code> when echo is a language construct and allows this <code>echo 'string', 'string'</code> which skips the concatenation?</li>\n<li>Why use <code>$num_results == 0</code> when you can just use <code>!$num_results</code>?</li>\n<li>Why not escape arguments in MySQL Query <em>(let's just say you have an <code>$id</code> integer and might get away with it here)</em> when SQL injections are so nasty :)</li>\n</ul>\n\n<p><strong>PS</strong>: AND YOU need to <strong>work on your formatting</strong> A LOT... like very much!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:43:43.550",
"Id": "44273",
"Score": "0",
"body": "Thank you very much. I will adjust my code and formatting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:57:15.927",
"Id": "44291",
"Score": "1",
"body": "use $num_results === 0 for comparison and check for FALSE (false doesn't mean nothing was returned, it means something went wrong)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T20:07:17.617",
"Id": "44294",
"Score": "1",
"body": "@Pinoniq In most cases, when something goes wrong and your query is correct... it's a MySQL server issue and it's kind of out of your control. You usually don't need to go into such detail with error handling unless you are into very detailed logging and I don't think he's into that just yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T07:48:07.683",
"Id": "44346",
"Score": "0",
"body": "@CodeAngry true. But he should know about the difference between === and =="
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T17:49:54.443",
"Id": "44376",
"Score": "1",
"body": "I did not know about ===, i'll read into it. Thx"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T10:04:24.517",
"Id": "28280",
"ParentId": "28262",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T20:44:23.947",
"Id": "28262",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"sql"
],
"Title": "Simple content management system"
}
|
28262
|
<p>I am attempting to come up with a better method for doing this:</p>
<pre><code>public static String longToPlayerName(long name) {
int i = 0;
char[] nameCharacters = new char[12];
while (name != 0L) {
long ll = name;
name /= 37L;
nameCharacters[11 - i++] = playerNameXlateTable[(int) (ll - (name * 37L))];
}
return new String(nameCharacters, 12 - i, i);
}
public static long playerNameToInt64(String s) {
long l = 0L;
for (int i = 0; (i < s.length()) && (i < 12); i++) {
final char c = s.charAt(i);
l *= 37L;
if ((c >= 'A') && (c <= 'Z')) {
l += (1 + c) - 65;
} else if ((c >= 'a') && (c <= 'z')) {
l += (1 + c) - 97;
} else if ((c >= '0') && (c <= '9')) {
l += (27 + c) - 48;
}
}
while (((l % 37L) == 0L) && (l != 0L)) {
l /= 37L;
}
return l;
}
</code></pre>
<p>I can't seem to come up with a better way. Any ideas would be excellent!</p>
|
[] |
[
{
"body": "<p>Pretty good overall, but a few things:</p>\n\n<ul>\n<li>Don't hard-code the 37. Instead, use the translation table's size.</li>\n<li><code>ll</code> is a bad variable name. It's not descriptive at all, and it looks like <code>11</code>.</li>\n<li><p>Your loop in <code>longToPlayerName</code> can be simplified:</p>\n\n<pre><code>final int base = playerNameXlateTable.length;\nwhile (name != 0L) {\n final long ch = name % base;\n nameCharacters[11 - i++] = playerNameXlateTable[ch];\n name /= base;\n}\n</code></pre></li>\n<li><p>Be careful with inlined <code>++i</code> or <code>i++</code>. They can be easy to overlook, and the human brain (mine anyway) doesn't parse arithmetic expressions that cause mutations very well.</p></li>\n<li><p>I think you've overused parenthesis a bit. For example, I would just do:</p>\n\n<pre><code>if (c >= 'A' && c <= 'Z') {\n</code></pre></li>\n<li><p><code>playerNameToInt64</code> should be <code>playerNameToLong</code></p></li>\n<li><code>s</code> is a bad parameter name. Call it something like <code>name</code>\n<ul>\n<li>Other than for loop controls, single letter variables should typically be avoided.</li>\n<li>It should also probably be <code>final</code>, but it's immutable, so it doesn't really matter in this case.</li>\n</ul></li>\n<li>Use <code>Character.toLowerCase</code> to eliminate one of the branches in <code>playerNameToInt64</code>.</li>\n<li>It might be better to group your shifts like <code>1 + (c - 97)</code> instead of how they're grouped. It doesn't matter in the current code, but if <code>(1 + c) - 97</code> can in theory overflow, but <code>1 + (c - 97)</code> cannot</li>\n<li><p>Rather than 97/65/48, use character literals:</p>\n\n<pre><code>1 + (c - 'a')\n</code></pre></li>\n<li><p>The truncation loop is a bit troubling. For a-zA-Z0-9, there never will be any trailing 0 valued base-37 digit. This means that you're worried an invalid character will be provided. But... what if one is in the middle of the string?</p></li>\n<li>If you made a reverse translation table, you could decouple your code from ASCII\n<ul>\n<li>no point in doing this though, as it's probably always going to be ASCII (or a superset of ASCII)</li>\n</ul></li>\n<li>Fold the double comparison in the <code>toLong</code> loop into a <code>Math.min()</code> call and use that</li>\n<li>Assuming this class is dedicated to player name translation and only player name translation (as it should be), <code>playerNameXlateTable</code> could be shortened to <code>translationTable</code>\n<ul>\n<li>In the context of a single-responsibility class, it's obvious what the table is translating</li>\n<li>Though partly I'm just saying this because <code>xlate</code> makes me cry, but <code>playerNameTranslationTable</code> does too in all of its 26 character glory.</li>\n</ul></li>\n<li>Will you ever have any other name encodings? If so, it might be worth-while to consider making an interface and having these methods be non-static.\n<ul>\n<li>It would make your code a bit more verbose, but it would allow for a bit more decoupling</li>\n</ul></li>\n<li>Make 12 a constant\n<ul>\n<li>It would be nice to calculate it since <code>maxLetters = floor(log(2^LONG_BITS) / log(37))</code>, but there's no non-hideous way to calculate this</li>\n<li>If it's a constant and you later expand the translation table, you'll only have to change 12 in one place instead of multiple. It's always good to reduce the chance of introducing future bugs.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Since the code is short, I gave it a go at revising it:</p>\n\n<pre><code>public class Review {\n\n private static char[] translationTable = buildTranslationTable();\n private static int maxLetters = 12;\n\n public static void main(String[] args)\n {\n System.out.println(playerNameToLong(\"Corbin92\"));\n System.out.println(longToPlayerName(324533943486L));\n }\n\n public static String longToPlayerName(long name) {\n int i = 0;\n char[] nameCharacters = new char[maxLetters];\n final long base = translationTable.length;\n while (name != 0L) {\n final long ch = name % base;\n nameCharacters[maxLetters - ++i] = translationTable[(int) ch];\n name /= base;\n }\n return new String(nameCharacters, maxLetters - i, i);\n }\n\n public static long playerNameToLong(final String name) {\n final long base = translationTable.length;\n final int len = Math.min(name.length(), maxLetters);\n long l = 0L;\n for (int i = 0; i < len; ++i) {\n final char c = Character.toLowerCase(name.charAt(i));\n l *= base;\n if (c >= 'a' && c <= 'z') {\n l += 1 + (c - 'a');\n } else if (c >= '0' && c <= '9') {\n l += 27 + (c - '0');\n }\n }\n return l;\n }\n\n private static char[] buildTranslationTable()\n {\n char[] table = new char[37];\n for (char c = 'a'; c <= 'z'; ++c) {\n table[1 + c - 'a'] = c;\n }\n for (int i = 0; i < 10; ++i) {\n table[i + 27] = (char) (i + '0');\n }\n return table;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T02:53:06.177",
"Id": "44340",
"Score": "0",
"body": "Wow! Thanks for the excellent tips! :- )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T18:44:34.687",
"Id": "44495",
"Score": "0",
"body": "@AtomicInt_ Glad I could help! If possible at all, by the way, you should try to use abuzittin gillifirca's approach. It uses a different encoding with different properties, so it might not be possible, but what your code is essentially changing bases, which his done in 2 lines :)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T06:11:39.207",
"Id": "28269",
"ParentId": "28264",
"Score": "6"
}
},
{
"body": "<p>You can directly convert an alphanumeric string to int64 and back in Java, using <code>Long.parseLong</code> and <code>Long.toString</code> using base 36. Like so:</p>\n\n<pre><code>System.out.println(Long.toString(994264677686L, 36));\nSystem.out.println(Long.parseLong(\"Corbin92\", 36));\n</code></pre>\n\n<p>What you then need to do is validation, for example check that the input string consists of alphanumeric characters; and handle edge cases, for example check that string is not too long or the number is not too small or too big etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T08:59:47.390",
"Id": "44223",
"Score": "0",
"body": "Hmmm, well that's awkward.... Seems my Java rustiness is showing :)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T08:27:52.463",
"Id": "28272",
"ParentId": "28264",
"Score": "5"
}
},
{
"body": "<p>Note: I realize both that this is old and that there is a <a href=\"https://codereview.stackexchange.com/a/28272/71574\">more direct answer</a>. But I think that knowing how and when to use a <code>StringBuilder</code> is more important in general than solving this problem.</p>\n<blockquote>\n<pre><code>public static String longToPlayerName(long name) {\n int i = 0;\n char[] nameCharacters = new char[12];\n while (name != 0L) {\n long ll = name;\n name /= 37L;\n nameCharacters[11 - i++] = playerNameXlateTable[(int) (ll - (name * 37L))];\n }\n return new String(nameCharacters, 12 - i, i);\n}\n</code></pre>\n</blockquote>\n<p>This is what a <code>StringBuilder</code> is designed to do. Then you don't have to muck with internals like <code>i</code>. Consider</p>\n<pre><code>private static final char[] ALPHABET = " abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();\n\npublic static String longToPlayerName(long packed) {\n StringBuilder reversed = new StringBuilder();\n for (; packed > 0L; packed /= ALPHABET.length) {\n reversed.append(ALPHABET[packed % ALPHABET.length]);\n }\n\n return reversed.reverse().toString();\n}\n</code></pre>\n<p>No <code>i</code> to maintain. And it doesn't have to jump through hoops to get just the part of the array that represents the characters.</p>\n<p>Doesn't have to hard code the length. Nor the size of the alphabet.</p>\n<p>It's more obvious that the intermediate representation is reversed.</p>\n<p>While I love math, each math operation is a potential error. This reduces the number of math operations to three (including the comparison). The original code had six (comparison, subtraction, increment, multiplication, subtraction, subtraction) and two hard coded constants.</p>\n<p>And again, the base 36 solution is more appropriate to this particular problem. It's even a more compact encoding. But if you are writing a solution to a problem like this, a <code>StringBuilder</code> is a better tool than a character array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-17T07:19:31.977",
"Id": "259655",
"ParentId": "28264",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28269",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-07-08T21:56:32.363",
"Id": "28264",
"Score": "4",
"Tags": [
"java",
"strings",
"converting",
"integer"
],
"Title": "Long-to-string and string-to-long while checking characters within a xlate table"
}
|
28264
|
<p>As far as I can tell, no gem currently exists to wrap shred, the *nix utility to securely delete files. I created a small class to do this, the key methods are:</p>
<pre><code>def self.run cmd
stdout,stderr,status = Open3.capture3 cmd
raise "Failed executing #{cmd}: stdout: #{stdout}, stderr: #{stderr}, status #{status}" unless status.nil? || status == 0
stdout
end
def self.validate_path path, required_regex=nil
raise if required_regex && !required_regex.is_a?(Regexp)
File.expand_path(path).tap do |path|
raise if path == '/'
raise if required_regex && !path.match(required_regex)
end
end
def self.dir! path, opts={}
return unless Dir.exist?(path)
validate_path path, opts[:path_must_match]
stdout = run "find #{path} -type f -exec #{shred_cmd} '{}' ';'"
FileUtils.rm_rf path
stdout
end
</code></pre>
<ul>
<li>find is used to execute shred, since it lacks a recursive option. I initially tried execdir instead of exec for security, but travis and other build environments hate it. Potential problem?</li>
<li>validate_path tries to keep the user from screwing themselves by expanding the path, better ways of doing this?</li>
</ul>
|
[] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><code>def self.run cmd</code>: Omiting parentheses on signatures is less and less idiomatic as time goes by, people have realized they are harder to read. I'd put them.</li>\n<li><code>Open3.capture3 cmd</code>: It's also less idiomatic than it was years ago to omit parentheses on calls (except for very specific DSL code).</li>\n<li><code>stdout,stderr,status</code>: Always a space after a comma.</li>\n<li><code>def self.validate_path path, required_regex=nil</code>. Positional optional arguments tend to get messy when you need to add new ones. I'd use always an <code>options = {}</code> hash. Ruby 2.0 has keyword arguments so this problem is fortunately gone.</li>\n<li><code>raise if required_regex && !required_regex.is_a?(Regexp)</code>. I wouldn't check the type of the variable, it's the caller's responsability to get it right.</li>\n<li><code>File.expand_path(path).tap</code>. This kind of <code>tap</code> usages are IMO cryptic and unnecessary.</li>\n<li>Lots of <code>raise ... if condition</code>: Inline conditionals save some lines at the cost of making the branching logic harder to follow. I prefer writing full-fledged indentend conditionals (indentation is a powerful conveyor of information).</li>\n<li><code>Open3.capture3 cmd</code>. Running command from strings is dangerous (files with spaces anyone?), you should use some mechanism to escape them. </li>\n<li><code>find #{path} -type f</code>. It's ok to call external commands when the the language is unable to do the task, but here you can easily perform a recursive find with, well, module <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/find/rdoc/Find.html\" rel=\"nofollow\">find</a>.</li>\n</ul>\n\n<p>I'd write something like this:</p>\n\n<pre><code>require 'find'\nrequire 'open3'\nrequire 'fileutils'\nrequire 'shellwords'\n\nclass SafeRemover\n def self.run(command_array)\n command_string = Shellwords.join(command_array)\n stdout, stderr, status = Open3.capture3(command_string)\n if !status || status == 0\n stdout\n else\n fail(\"Failed executing #{cmd}: stdout: #{stdout}, stderr: #{stderr}, status #{status}\")\n end\n end\n\n def self.validate_path(path, options = {})\n required_regexp = options[:required_regexp] \n path2 = File.expand_path(path)\n if !Dir.exist?(path2)\n fail(\"Directory does not exist: #{path2}\")\n elsif path2 == \"/\"\n fail(\"You cannot delete /\")\n elsif required_regexp && !path2.match(required_regexp)\n fail(\"Path and required_regexp do not match\")\n end\n end\n\n def self.dir!(root_directory, options = {})\n validate_path(root_directory, :required_regexp => options[:path_must_match])\n paths = Find.find(root_directory).select { |p| FileTest.file?(p) }\n output = paths.each_slice(100).map { |paths| run([\"shred\", *paths]) }.join\n FileUtils.rm_rf(root_directory)\n output\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T13:50:46.750",
"Id": "44249",
"Score": "0",
"body": "Thanks for the feedback @tokland. I think we differ on style issues (the less parens the better!), but I understand your points about more explicit branching. Your approach of invoking shred independently is interesting, and I like that it bypasses whatever issues find might have. I wonder about performance though, since you are creating a new subshell for every file deleted. I suppose bench-marking the two approaches would be the way to tell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:07:02.707",
"Id": "44254",
"Score": "0",
"body": "@juwiley: Note the `each_slice(100)`, I am spawning 1 shred per 100 files. Anyway, in your code, won't a find -exec fork 1 shred per file? Regarding the parens: yes, it's subjective. But IMHO Haskell/Ocaml got it right in the parens-less section, you can either have parens or commas to separate arguments, but commas and optional parens (Ruby/Coffescript) is usally a mess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:13:35.037",
"Id": "44255",
"Score": "0",
"body": "Also the Shellwords module is a good find, hadn't been aware of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:16:45.740",
"Id": "44256",
"Score": "0",
"body": "Duh, you're exactly right about -exec. I think using xargs would get around that, but it may croak on a certain number of files which brings us back to your approach and makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:50:26.940",
"Id": "44275",
"Score": "0",
"body": "`xargs`, yes, instead of find -exec I tend to do something like: `find directory | xargs -n100 command`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T11:50:04.747",
"Id": "28286",
"ParentId": "28265",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28286",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T01:34:50.480",
"Id": "28265",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "Securely deleting files, while attempting to protect the user against obviously dangerous inputs"
}
|
28265
|
<p>I made an example for learning <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency inversion principle</a> in JavaScript OOP programming .</p>
<pre><code>String.prototype.ucfirst = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
function textHandler(){
this.printRedbox = function( ){
return ' Red Box text ';
}
this.printBluebox = function( ){
return ' Blue Box text ';
}
};
function htmlHandler( handler ){
var block = [],
box = document.getElementById('container');
this.boxContentHandler = handler ;
this.setType = function( handler ){
this.boxContentHandler = handler
};
this.appendBlock = function( html ){
block.push( html );
box.innerHTML = block.join('');
};
this.printBox = function ( action ){
var title = this.printTitle() ,
text = this.boxContentHandler[ 'print'+ action.ucfirst() ](),
html = '<div class="box '+ action.replace('box','') +'">'
+ title + text
+'</div>' ;
this.appendBlock( html );
};
this.printTitle = function( ) {
return 'Title ' + block.length + ' <br />';
};
};
</code></pre>
<p>Here I am doing the action handling part </p>
<pre><code>var htmlHandle = new htmlHandler( new textHandler() );
document.getElementById('bluebox').addEventListener( 'click', function(){
htmlHandle.printBox( this.id );
},false );
document.getElementById('redbox').addEventListener( 'click', function(){
htmlHandle.printBox( this.id );
},false );
</code></pre>
<p>I would like to know, is there a way to make it better. Did I miss anything here ?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T11:53:23.660",
"Id": "44232",
"Score": "0",
"body": "Why is the DOM element created inside `htmlHandle` (rather than injected)? Why are you creating HTML from strings? Why are you joining strings for property lookup? You might want to read http://www.martinfowler.com/articles/injection.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T12:19:57.300",
"Id": "44235",
"Score": "0",
"body": "@BenjaminGruenbaum yes that code is in JAVA . I only know server side langauge PHP . On this example I am trying make html string . and collect them into array.. on clicking button the innerHTML changes `box.innerHTML = block.join('')`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T21:34:00.683",
"Id": "44304",
"Score": "2",
"body": "@rab: I suppose you mean JavaScript, not Java, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:58:24.493",
"Id": "84921",
"Score": "0",
"body": "@MichaelZedeler yes in `JavaScript`."
}
] |
[
{
"body": "<p>From a once over;</p>\n\n<ul>\n<li><code>ucfirst</code> <- not a great name</li>\n<li>Single comma separated <code>var</code> statements <- nice</li>\n<li>Consider using <code>use strict</code></li>\n<li>You need more comments explaining how you made DIP work, honestly I am not convinced that this is a good example of DIP ( I could be wrong )</li>\n<li><s>The link between the <code>id</code> and the function name makes for brittle code</s> <- Apparently that's the point ;)</li>\n<li>You are not using <code>setType</code> anywhere in your example</li>\n<li><code>htmlHandler</code> <- probably should have been <code>boxHandler</code> given how everything inside references <code>box</code> and <code>block</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:40:42.223",
"Id": "47881",
"ParentId": "28273",
"Score": "4"
}
},
{
"body": "<p>This is a decent way to implement Dependency Inversion, from the standpoint of your implementing classes. The only improvements I would recommend is to find a good class library that does the lookup of dependencies for you.</p>\n\n<p>Really Inversion of Control/Dependency Inversion involves several parts:</p>\n\n<ol>\n<li>Writing your classes so that they receive their dependencies via one of three methods:\n<ol>\n<li>Constructor injection (like you have) <code>new Foo(x)</code></li>\n<li>Property injection <code>a.foo = b</code></li>\n<li>Setter injection <code>a.setFoo(b)</code></li>\n</ol></li>\n<li>An object factory that can turn a class name in the form of a String into a new object</li>\n<li>An dependency resolver that does the lookup of dependencies and injects them into a new object</li>\n<li>A \"container\" object allowing you to configure your dependencies and wire your classes together</li>\n</ol>\n\n<p>I've created <a href=\"https://github.com/gburghardt/hypodermic\">Hypodermic</a> for this purpose, though I think it should be refactored to separate the \"container\" from the \"dependency resolver\" functionality. I would be interested in finding out if there are other Dependency Injection libraries out there for JavaScript.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:08:53.720",
"Id": "47883",
"ParentId": "28273",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T08:45:22.493",
"Id": "28273",
"Score": "6",
"Tags": [
"javascript",
"jquery"
],
"Title": "OOP Dependency Inversion Principle"
}
|
28273
|
<p>I have session controller for mobile devices. I would like to refactor it a little, for example because my session controller is sub class of <code>Devise::SessionsController</code> I had to duplicate error methods from <code>BaseController</code>.</p>
<pre><code>class Api::V1::SessionsController < Devise::SessionsController
include Devise::Controllers::Helpers
prepend_before_filter :require_no_authentication, only: [:create]
skip_load_and_authorize_resource
before_filter :ensure_params_exist, only: [:create]
respond_to :json
def create
if user_find params[:user][:member_id]
self.resource = warden.authenticate!(auth_options)
sign_in(resource_name, resource)
resource.reset_authentication_token!
resource.save!
else
error :not_found
end
end
def destroy
sign_out(resource_name)
end
private
def user_find(id)
User.find_by member_id: id
end
def ensure_params_exist
unless params[:user]
error :bad_request
end
end
def error type, context=nil
render json: { message: error_message(type, context) }, status: type
end
def error_message type, context
scope = [:api, :error, self.controller_name.to_sym]
scope.push context if context
t(type, scope: scope)
end
end
class Api::V1::BaseController < ApplicationController
load_and_authorize_resource
respond_to :json
rescue_from CanCan::AccessDenied do |exception|
render_status :unauthorized
end
private
def error type, context=nil
render json: {message: error_message(type, context)}, status: type
end
def error_message type, context
scope = [:api, :error, self.controller_name.to_sym]
scope.push context if context
t(type, scope: scope)
end
def render_status state
render status: state, json: {}
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Put the common error methods in a Module and include it in each Controller where you need them (in a similar way like you already include <code>Devise::Controllers::Helpers</code>, but this time with your own namespace and module name.)</p>\n\n<p>As for the method signatures</p>\n\n<pre><code>def error type, context=nil\ndef error_message type, context\ndef render_status state\n</code></pre>\n\n<p>it's common to leave the parenthesis out when calling class methods in class context (because they oftentimes make up a nice DSL), but please don't do it when defining methods, that can lead to annoying ambiguities.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T21:31:55.413",
"Id": "44405",
"ParentId": "28274",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T08:48:13.913",
"Id": "28274",
"Score": "2",
"Tags": [
"ruby",
"design-patterns",
"ruby-on-rails",
"api",
"session"
],
"Title": "How can I refactor Api::SessionsController?"
}
|
28274
|
<p>I want to abstract away differences between <a href="http://docs.python.org/2/library/zipfile.html" rel="nofollow">zipfile</a> and <a href="https://pypi.python.org/pypi/rarfile/" rel="nofollow">rarfile</a> modules. In my code i want to call <code>ZipFile</code> or <code>RarFile</code> constructors depending on file format. Currently i do it like that.</p>
<pre><code>def extract(dir, f, archive_type):
'''
archive_type should be 'rar' or 'zip'
'''
images = []
if archive_type == 'zip':
constructor = zipfile.ZipFile
else:
constructor = rarfile.RarFile
with directory(dir):
with constructor(encode(f)) as archive:
archive.extractall()
os.remove(f)
images = glob_recursive('*')
return images
</code></pre>
<p>Is there any more elegant way for dynamic object calling?</p>
|
[] |
[
{
"body": "<p>Classes are first-class objects in Python.</p>\n\n<pre><code>amap = {\n 'zip': zipfile.ZipFile,\n 'rar': rarfile.RarFile\n}\n\n ...\n\nwith amap[archive_type](encode(f)) as archive:\n ...\n</code></pre>\n\n<p>or</p>\n\n<pre><code>with amap.get(archive_type, rarfile.RarFile)(encode(f)) as archive:\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T09:19:30.730",
"Id": "28277",
"ParentId": "28275",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28277",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T09:02:56.733",
"Id": "28275",
"Score": "1",
"Tags": [
"python",
"constructor"
],
"Title": "Dynamic object creation in Python"
}
|
28275
|
<p>I have extension methods to encapsulate query conditions, however I have to separate <code>IQueryable</code> and <code>IEnumerable</code>. Is there any way I can reduce the redundancy and still not lose the performance benefit of <code>IQueryable</code>?</p>
<pre><code>public static class PAYTRACK_PARTNER_Extension
{
public static IQueryable<PAYTRACK_PARTNER> WhereInPayer(this IQueryable<PAYTRACK_PARTNER> query, int payerId)
{
var result = query.Where(q => q.payer_id == payerId);
return result;
}
public static IEnumerable<PAYTRACK_PARTNER> WhereInPayer(this IEnumerable<PAYTRACK_PARTNER> query, int payerId)
{
var result = query.Where(q => q.payer_id == payerId);
return result;
}
public static IQueryable<PAYTRACK_PARTNER> WhereInPayee(this IQueryable<PAYTRACK_PARTNER> query, int payeeId)
{
var result = query.Where(q => q.payee_id == payeeId);
return result;
}
public static IEnumerable<PAYTRACK_PARTNER> WhereInPayee(this IEnumerable<PAYTRACK_PARTNER> query, int payeeId)
{
var result = query.Where(q => q.payee_id == payeeId);
return result;
}
public static IQueryable<PAYTRACK_PARTNER> WhereIsNotApproved(this IQueryable<PAYTRACK_PARTNER> query)
{
var result = query.Where(q => q.partner_is_approve.GetValueOrDefault(false).Equals(false));
return result;
}
public static IEnumerable<PAYTRACK_PARTNER> WhereIsNotApproved(this IEnumerable<PAYTRACK_PARTNER> query)
{
var result = query.Where(q => q.partner_is_approve.GetValueOrDefault(false).Equals(false));
return result;
}
public static PAYTRACK_PARTNER SingleByPayerAndPayee(this IQueryable<PAYTRACK_PARTNER> query, int payerId, int payeeId)
{
var result = query.Single(q => q.payer_id == payerId && q.payee_id == payeeId);
return result;
}
public static PAYTRACK_PARTNER SingleByPayerAndPayee(this IEnumerable<PAYTRACK_PARTNER> query, int payerId, int payeeId)
{
var result = query.Single(q => q.payer_id == payerId && q.payee_id == payeeId);
return result;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You can use <code>IQueryable<T></code> everywhere, because you can convert to it from <code>IEnumerable<T></code> by using <a href=\"http://msdn.microsoft.com/en-us/library/bb507003.aspx\" rel=\"nofollow\"><code>AsQueryable()</code></a>:</p>\n\n<pre><code>public static IQueryable<PAYTRACK_PARTNER> WhereInPayer(\n this IQueryable<PAYTRACK_PARTNER> query, int payerId)\n{\n var result = query.Where(q => q.payer_id == payerId);\n return result;\n}\n\npublic static IEnumerable<PAYTRACK_PARTNER> WhereInPayer(\n this IEnumerable<PAYTRACK_PARTNER> query, int payerId)\n{\n return query.AsQueryable().WhereInPayer(payerId);\n}\n</code></pre>\n\n<p>Also, names in ALL_CAPS are not commonly used in C#, you should adopt c# naming conventions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T12:15:20.437",
"Id": "44234",
"Score": "0",
"body": "thank you :) i can't change to all cap though because it is dbml generated from db and they named it like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T03:58:09.827",
"Id": "51375",
"Score": "0",
"body": "I can't convert it in linq to entity.\nlike company.T_RFQs when T_RFQs is entity set.\ni just can't convert to by asQueryable. compiler said it is not support :("
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T10:06:45.833",
"Id": "28281",
"ParentId": "28276",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28281",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T09:12:26.640",
"Id": "28276",
"Score": "2",
"Tags": [
"c#",
"iterator"
],
"Title": "Refactor IQueryable and IEnumerable that share the same condition"
}
|
28276
|
<p>I have, in Java, an <code>arraylist</code> with these values (many lines, this is just an extract):</p>
<blockquote>
<p>20/03/2013 23:31:46 6870 6810 6800 6720 6860 6670 6700 6650 6750 6830 34864 34272
20/03/2013 23:31:46 6910 6780 6800 6720 6860 6680 6620 6690 6760 6790 35072 34496</p>
</blockquote>
<p>where the first two values are strings that contain data and are stored in a single element.</p>
<p>What I want to do is to compare the string data elements and delete, for example, the second one and all the elements referred to that line.</p>
<p>For now, I've used a for cycle that every 13 elements compares the string (in order to compare only data strings).</p>
<p>Can I implement this with other better solutions?</p>
<pre><code>import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Downsampler {
public static void main(String[] args) throws Exception{
//The input file
Scanner s = new Scanner(new File("prova.txt"));
//Saving each element of the input file in an arraylist
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
//Arraylist to save modified values
ArrayList<String> ds = new ArrayList<String>();
int i;
for(i=0; i<=list.size()-13; i=i+14){
//combining the first to values to obtain data
String str = list.get(i)+" "+list.get(i+1);
ds.add(str);
//add all the other values to arraylist ds
int j;
for(j=2; j<14; j++){
ds.add(list.get(i+j));
}
//comparing data values
int k;
for(k=0; k<=ds.size()-12; k=k+13){
ds.get(k); //first data string element
//Comparing with other strings and delete
//TODO
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:48:41.353",
"Id": "44287",
"Score": "0",
"body": "Please, for future maintainer/international safety, use an ISO-formatted locale-independent 'local'-timezone-ignorant [timestamp](http://en.wikipedia.org/wiki/ISO_8601). In the US, there's about something like 7 or 8 different times that those stamps _could_ be, given timezones. If the day-of-month wasn't greater than 12, you have the potential to switch month/day-of-month, depending on reader."
}
] |
[
{
"body": "<p>To answer your question.. it depends on how you want to handle the data. Take a step back and put your self in the users shoes. Lets say the user has those numbers saved as bank account transactions.. He would want those numbers saved somewhere, but not necessarily visible. If that was the case you wouldn't want \"delete\" that data. You could, however, parse the data into say a table. You could give each cell in that table a class that has a boolean value called visible, and a int value. Then you could set a row or column to not visible as you wish. That would give you the ability to then just loop through the rows and columns and output the data as needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T13:24:17.367",
"Id": "44247",
"Score": "0",
"body": "In my case it's important that in case of duplicates, i keep only one value because i have duplicates every seconds and one line of values it's enough. But still i try to find a good solution"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:57:40.520",
"Id": "44261",
"Score": "0",
"body": "@Markviduka if it is in a table you can filter it as needed. There is probably a way to do this easily, I just don't know how to do it in java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T15:24:38.453",
"Id": "44264",
"Score": "0",
"body": "I solved, i used a simple if statement and equals to strings. Thanks a lot"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T13:18:40.530",
"Id": "28288",
"ParentId": "28284",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28288",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T11:45:50.450",
"Id": "28284",
"Score": "1",
"Tags": [
"java",
"strings"
],
"Title": "Make an arraylist of unique values"
}
|
28284
|
<p>I know that there is a function <code>bsearch</code> present in <code>stdlib.h</code> but still I want to implement this. </p>
<p>This is my code for binary search. Any and all reviews are welcome.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
int compare (const void * a, const void * b)
{
return (*(int*)a - *(int*)b);
}
int bin_search(int arr[], int min_index, int max_index, int element)
{
/*
Searches for an element in the array arr
Returns fist index of element if present else returns -1
*/
if (min_index > max_index){
return -1;
}
else
{
//Don't change this assignment of mid_point. It avoids overflow
int mid_point = min_index + (max_index - min_index)/2;
if (arr[mid_point] > element){
return bin_search(arr, min_index, mid_point - 1, element);
}
else if (arr[mid_point] < element){
return bin_search(arr, mid_point + 1, max_index, element);
}
else{
return mid_point;
}
}
}
int main()
{
int length;
while (1)
{
printf("Enter a positive length: ");
scanf("%d", &length);
if (length > 1){
break;
}
else{
printf("You entered length = %d\n\n", length);
}
}
int *arr = malloc(sizeof(int) * length);
if (arr == NULL)
{
perror("The following error occurred");
exit(-1);
}
for (int i = 0; i < length; i++){
scanf("%d", &arr[i]);
}
int element;
printf("\nEnter the element to be searched: ");
scanf("%d", &element);
qsort(arr, length, sizeof(int), compare);
int index = bin_search(arr, 0, length - 1, element);
if (index == -1){
printf("\nElement not in the array");
}
else{
printf("\nIndex of element is %d", index);
}
free(arr);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:34:33.790",
"Id": "44285",
"Score": "1",
"body": "Any discussion regarding this question can be done in this [chat room](http://chat.stackexchange.com/rooms/9579/discussion-between-aseem-bansal-and-josay). @codesparkle Just leave this comment if you want to delete all others"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:51:05.983",
"Id": "44391",
"Score": "0",
"body": "Why make `element` a `const` and not `min` and `max`? Such `const` markup on parameters passed by value does no harm but is not part of the function's interface - in other words the caller does not care. From an interface point of view, `const` only has meaning for pointers, such as `arr`. It could be considered to have some utility in telling the reader that the call parameters remain unchanged (but personally I rarely, if ever, use it for parameters passed by value)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T04:06:07.703",
"Id": "44428",
"Score": "0",
"body": "@WilliamMorris I am still confused about what is the best way to use `const`. I commented on ruds' answer about this confusion as he added 1 more `const` here. Perhaps you can answer my comments there."
}
] |
[
{
"body": "<p>Update <code>bin_search</code> with a best-case scenario <strong>O(1)</strong>, if the array has only 1 element.</p>\n\n<pre><code>int bin_search (int arr[], int min_index, int max_index, int element)\n{\n // this is the best case scenario\n if(min_index == max_index)\n {\n if(arr[min_index] == element) \n return min_index;\n else \n return -1;\n }\n if (min_index > max_index)\n {\n return -1;\n }\n else\n { \n int mid_index = (min_index + max_index) / 2;\n if (arr[mid_index] > element)\n {\n return bin_search(arr, min_index, mid_index - 1, element);\n }\n else if (arr[mid_index] < element)\n {\n return bin_search(arr, mid_index + 1, max_index, element);\n }\n else\n { \n return mid_index;\n }\n }\n}\n</code></pre>\n\n<p>There is also an iterative process.</p>\n\n<pre><code>int bin_search (const int arr[], int min, int max, int element)\n{\n int high = max+1;\n int low = min;\n while(low < (high-1))\n {\n int mid = (low + high)/2;\n if(element < arr[mid])\n high = mid;\n else\n low = mid;\n }\n if(arr[low] == element)\n return low;\n else\n return -1; // not found\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:25:17.260",
"Id": "44267",
"Score": "0",
"body": "The complexity doesn't change a bit but performance suffers in this code. My implementation is tail-recursive so there shouldn't be much overhead for function calls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:27:41.637",
"Id": "44270",
"Score": "0",
"body": "@AseemBansal: Note, \"tail-recursive\" is still \"recursive\" -- and by default still has any other recursion's performance issues. You don't gain anything from it performancewise unless the compiler does tail-call optimizations (which it's not required to do)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:34:56.733",
"Id": "44271",
"Score": "0",
"body": "@cHao What about gcc? I use Code:blocks IDE with gcc compiler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:05:27.157",
"Id": "44277",
"Score": "0",
"body": "@AseemBansal: Looks like if you compile with `-O2`, `-O3`, or `-Os`, or add `-foptimize-sibling-calls` to the command line, it should at least try. At that point, the result depends on how good the detection is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:06:33.857",
"Id": "44278",
"Score": "0",
"body": "@AseemBansal and why my code is not \"tail-recursive\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:21:16.760",
"Id": "44280",
"Score": "0",
"body": "@tintinmj I didn't imply that your code isn't tail-recursive. I just think that these changes are unnecessary **because** the code is recursive. If `n = 1` then your code will take 2 comparisons to get the answer while mine will take at most 4 comparisons. That is an improvement of `2 comparisons` for this case. In all other cases as the code is recursive it adds `log n` more comparisons. As it is `log base 2 of n` so even for `n = 8` the number of extra comparisons introduced by the changes outweigh the benefit introduced already. That's why I said that performance suffers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:25:49.103",
"Id": "44282",
"Score": "0",
"body": "@AseemBansal your code can also have two comparisons just add `if (arr[mid] == element) return mid;` after first `else`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:30:47.450",
"Id": "44284",
"Score": "0",
"body": "@tintinmj Same problem. It will add `log(base 2) n` comparison for all other cases except the base case."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T16:48:32.150",
"Id": "28298",
"ParentId": "28285",
"Score": "0"
}
},
{
"body": "<p>The functions says it \"Returns fist index of element if present\". If I give it the numbers 2, 2, 2 and ask it to find 2 it says the 1, but the first index with value 2 is clearly 0.</p>\n\n<p>Some minor comments on the code:</p>\n\n<ul>\n<li><p>the <code>arr</code> parameter to <code>bin_search</code> should be <code>const</code>. This tells the compiler and the reader that the array is not changed by the function. The compiler will then enforce this if you, by mistake, try to modify the array data. The reader/user knows that her data is unchanged after the call.</p></li>\n<li><p>the parameter names <code>min_index</code> and <code>max_index</code> could be shortened to <code>min</code> and <code>max</code>. Giving names an appropriate size is a service to the reader (auto-completion by the IDE is a service to you). In general, the shorter the names, the less dense the code and the easier it is to read. This can be taken too far of course, once names become meaningless. </p></li>\n<li><p>Note that it would be more normal to pass the start of the array and its size instead of the array plus two offsets. </p></li>\n<li><p>functions could be static. This is of no significance in a one-file program but becomes important with bigger programs. Making functions and global variables static restricts their scope to the file which allows extra optimisation and reduces namespace pollution.</p></li>\n<li><p>the output message needs a trailing \\n</p></li>\n<li><p>there is no prompt for the input values - ok that is trivial. Personally I find this sort of test better with values entered on the command line. </p></li>\n<li><p>exit status is normally 1 (EXIT_FAILURE) on failure, not -1. On success it is 0 (EXIT_SUCCESS). These are UNIX conventions.</p></li>\n</ul>\n\n<p><hr>\n<strong>EDIT</strong></p>\n\n<p>You questioned the use of <code>const</code>. Its utility when used on parameters passed by\nreference - pointers/array passed into functions - is, I think clear.</p>\n\n<p>However, its use with parameters passed by value is not so clear. It plays no\npart in the interface seen by callers of a function, as it can have no\ninfluence on the caller. You can declare a function prototype in a public\nheader like this </p>\n\n<pre><code>int bin_search(const int arr[], int min, int max, int element);\n</code></pre>\n\n<p>and then define the function implementation like this:</p>\n\n<pre><code>int bin_search(const int arr[], const int min, const int max, const int element) {...}\n</code></pre>\n\n<p>And the compiler will be quite happy with the difference.</p>\n\n<p>So it is purely an implementation issue. Hence you should definitely <strong>not</strong> use <code>const</code> on pass-by-value parameters in public prototypes, only in the implementation (if at all). Used in the implementation, <code>const</code> tells the reader and the compiler\nthat a parameter is not (and cannot be) changed. This gives the reader some\nextra information and of course the compiler will enforce this read-only\nbehaviour.</p>\n\n<p>So shouldn't you use it on all parameters that are not changed (and some might say that parameters should never be changed)? Good question! I never use <code>const</code> on call parameters but would have no hesitation in adding <code>const</code> to a local variable</p>\n\n<pre><code>int cirle_area(double radius)\n{\n const double pi = 3.14;\n return pi * radius * radius;\n}\n</code></pre>\n\n<p>A lot of good programming style concerns consistency, so my inconsistency here\nis troubling. And my previous comment - that if you make the <code>element</code>\nparameter <code>const</code>, then you should be consistent and do the same for <code>min</code> and\n<code>max</code> uses consistency as an argument!</p>\n\n<p>I'm afraid I can do no better than that. I've programmed for 20 years in C\nand have rarely seen <code>const</code> applied to parameters. But maybe it should be. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:19:58.023",
"Id": "44266",
"Score": "0",
"body": "I'll take care of the incorrect comment. About `arr` being `const` why? I used `min` and `max` but `max` is defined in C++ and the IDE that I use(Code:blocks) starts to highlight it as a keyword so I thought to change them. It has auto-completion so length of variables isn't a problem. Any particular reason why I should use `static` functions? Can you tell me what it is this called so I can read up a bit(like `static` for variables is `storage class`)? About exit status, is that a convention or what?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:55:04.917",
"Id": "44276",
"Score": "0",
"body": "So `const` should be used whenever I am passing pointers but not changing the contents. Correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:57:00.767",
"Id": "44290",
"Score": "0",
"body": "Yes, that is correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T14:07:15.670",
"Id": "44472",
"Score": "0",
"body": "Asked a [question on programmers](http://programmers.stackexchange.com/questions/204500/when-and-for-what-purposes-should-the-const-keyword-be-used-in-c-for-variables) about use of the `const` keyword. Please give your comments and suggest improvements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-23T10:47:23.007",
"Id": "254209",
"Score": "0",
"body": "Signaling the array as const is a good idea, for the other parameters const it's meaningless and just bloats the code. As for the the identifiers, I would argue that max_index is better than just max. A good rule of thumb (that do not work for every case) is to have a noun in the mix."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:04:08.707",
"Id": "28299",
"ParentId": "28285",
"Score": "4"
}
},
{
"body": "<p>If your average case is that the looked-for element is distributed uniformly randomly (and that your array is pulled from the same distribution), you actually gain in the average case by not returning early if arr[mid] == element.</p>\n\n<hr>\n\n<p>William Morris's comment about <code>static</code> was most likely meant to apply to your <code>compare</code> helper function; presumably <code>bin_search</code> will be declared in a header file to be included in other translation units, in which case it must not be declared <code>static</code>.</p>\n\n<hr>\n\n<p>Combining these comments:</p>\n\n<pre><code>int bin_search(const int arr[], int min, int max, const int element)\n{\n /*\n Searches for an element in the array arr\n Returns index of element if present else returns -1\n */\n if (min >= max) {\n return arr[max] == element ? max : -1;\n }\n\n //Don't change this assignment of mid. It avoids overflow\n const int mid = min + (max - min) / 2;\n\n if (arr[mid] < element) {\n return bin_search(arr, mid + 1, max, element);\n } else {\n return bin_search(arr, min, mid, element);\n}\n</code></pre>\n\n<p>This has exactly 2 * lg(N) + 1 comparisons (2 for each halving of the size, plus 1 on the final return). Your version has worst-case 3 * lg(N) comparisons and is worse in the average case (2.5 average comparisons per layer, saving on average (N-1)*2^-N + (N-2)*2^(N-1) + ... + 1*2^-1 layers, means that you get about 2.5 * (lg(N)-2) comparisons on average).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:54:27.703",
"Id": "44289",
"Score": "1",
"body": "My solution has the downside that it accesses uninitialized memory when `max` < 0 initially, which may happen e.g. when code doesn't check for an empty array before calling `bin_search`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T08:53:57.137",
"Id": "44350",
"Score": "0",
"body": "Any function that needs to called in other files by including the header files shouldn't be `static`. But these functions can access the `static` functions from the files from which they are called. Am I correct? As an example of what I think you have said, in this [question](http://codereview.stackexchange.com/questions/28224/recursive-implementation-of-merge-sort-optimization) the `merge_parts` function should be `static` but the `merge_sort` shouldn't be. Declaring `merge_parts` as `static` won't effect the use of `merge_sort` in another file. Correct me if I am wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T09:06:15.920",
"Id": "44352",
"Score": "0",
"body": "About declaring `mid` and `element` as `const`, should any variable, that isn't changed in the called function, be decalred `const`? I understand that declaring `arr` as `const` is relevant because it is a pointer that can be changed but the calling function's original value passed to the variable `element` cannot be effected here. Is this declaration of `const` for the purposes of clarity and perhaps a security measure in the scope of the called function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T09:13:17.477",
"Id": "44353",
"Score": "0",
"body": "Your code is missing a brace after the last else and shouldn't it be `2 * lg(N) + 2`. In the final case there are 2 comparisons, 1 for the `if` and 1 inside it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:55:44.707",
"Id": "44590",
"Score": "0",
"body": "After some thinking I think I might have found the best of both worlds. I'll update with a code that uses the same number of comparisons as you have suggested while still taking care of accessing uninitialized memory."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:53:08.680",
"Id": "28305",
"ParentId": "28285",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28299",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T11:49:36.997",
"Id": "28285",
"Score": "5",
"Tags": [
"optimization",
"c",
"performance"
],
"Title": "Binary Search in C - Optimization"
}
|
28285
|
<p>This is the relevant piece of my code (false is returned if the whole cycle is finished, pattern is a String passed to the function):</p>
<pre><code>for (FileLine fileLine : fileLines) {
itemText = fileLine.getText();
itemStrings = new ArrayList<String>();
itemStrings.addAll(Arrays.asList((itemText).split(" ")));
for (String itemString : itemStrings) {
if (itemString.equalsIgnoreCase(pattern)) {
return true;
}
}
}
</code></pre>
<p>How can I speed this up? I've tried using regex, something like:</p>
<pre><code>//before the for cycle
Pattern regexPattern = Pattern.compile(pattern);
//in the cycle
if (regexPattern.matcher(itemText).matches())
return true;
</code></pre>
<p>But it doesn't work for some reason. Maybe I'm doing it wrong, or there's a completely different way of accomplishing this?</p>
|
[] |
[
{
"body": "<p>You should probably be using <code>find()</code> instead of <code>matches()</code> (<a href=\"https://stackoverflow.com/questions/7459263/regex-whole-word#answer-7459291\">source</a>).</p>\n\n<p>I would recommend using <a href=\"http://regexpal.com/\" rel=\"nofollow noreferrer\">regexpal</a> to test out your pattern, just in case.</p>\n\n<p>Whether or not the Regex solution is faster, you'd have to run some tests, but I suspect it's MUCH faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:42:55.207",
"Id": "28293",
"ParentId": "28289",
"Score": "2"
}
},
{
"body": "<p>Why are you creating a new ArrayList each time, then filling it with (read: basically copying each element of) a list you created from an array? You have no need right here for the dynamic-ness of a List.</p>\n\n<p>Why not skip the two extraneous creations (and the resulting GC work, if this is a big file), and work with the array directly...and only create the ArrayList once you find a match?</p>\n\n<pre><code>for (FileLine fileLine : fileLines) {\n itemText = fileLine.getText();\n String[] candidate = itemText.split(\" \");\n\n for (String itemString : candidate) {\n if (itemString.equalsIgnoreCase(pattern)) {\n\n // Note: if `itemStrings` is local, you don't even have to create it.\n // This code is only necessary if it's an instance or class variable.\n itemStrings = new ArrayList<String>();\n itemStrings.addAll(Arrays.asList(candidate));\n\n return true;\n }\n }\n}\n</code></pre>\n\n<p>The biggest difference here is that if you don't find a match, <code>itemStrings</code> never gets set -- whereas with the original code, it'll be set to the last line, regardless of whether that line was a match.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:48:15.067",
"Id": "28300",
"ParentId": "28289",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T13:46:23.890",
"Id": "28289",
"Score": "2",
"Tags": [
"java",
"performance",
"regex"
],
"Title": "Matching a pattern in many lines of text"
}
|
28289
|
<p>I'm working on figuring out the best way to design this so that it's well organized and it seems like the factory design pattern makes sense. </p>
<p>Updated:
<strong>What I'm building:</strong>
- Pricing calculator
- There are 4 products each having their own specific pricing rules that vary from user input
- The person can choose between 1 product or all products</p>
<p>Should I have a Calculator class to determine product pricing or leave the calculations in each product type?</p>
<pre><code>/*
* Use Factory Pattern to build objects
*/
class ProductFactory {
public static function createProduct($type) {
switch ($type) {
case 'solution1':
return new Solution1Product();
break;
case 'solution2':
return new Solution2Product();
break;
case 'solution3':
return new Solution3Product();
break;
case 'solution4':
return new Solution4Product();
break;
}
}
}
/*
* Abstract Product
*/
abstract class AbstractProduct {
protected $price;
protected $max_limit;
protected $max_amount;
abstract public function calculatePrice($dob, $gender, $amount);
}
/*
* Solution 1 Product
*/
class Solution1Product extends AbstractProduct {
protected $max_limit = 50000;
function __contruct() {
print "Test";
return "Solution1";
}
function calculatePrice($dob, $gender, $amount) {
$rate = 1.03;
$price = 55;
if ($amount >= $this->max_limit) {
return "Max Limit Reached";
}
//@TODO go lookup price from tables
$this->price = $rate * $price;
return $this->price;
}
}
$solution1 = ProductFactory::createProduct('solution1');
print $solution1->calculatePrice("02/25/1982", "male", 100000);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T20:16:28.603",
"Id": "44295",
"Score": "1",
"body": "I love the `return; break;` combos. I always do that too. I type `case ...:` and `break;` and then anything in between. But I always have a `default: break;` too :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T13:36:44.803",
"Id": "44361",
"Score": "0",
"body": "default, yes will be adding that one :)\nIn terms of the ProductFactory - I think I've changed my thinking on this. Where Solution1Product would be the actual product - to be more of a type of product. Eg: BookProduct - book would have price, isbn, author, etc, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:10:27.547",
"Id": "44409",
"Score": "0",
"body": "Isn't it nice :) `$classname = ucfirst( strtolower( $type ) ).\"Product\";\nif ( class_exists( $classname ) ) {\n return new $classname;\n}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:12:49.587",
"Id": "44556",
"Score": "0",
"body": "you have a Procutfactory that creates Solutions? hmm... Personally I think you are looking at the problem the wrong way. I'll try and get an answer by this evening"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T18:26:19.030",
"Id": "44598",
"Score": "1",
"body": "*\"return ...; break;\"* simply doesn't make any sense. Adding a *\"default:\"* on the other hand would make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T14:30:55.550",
"Id": "44832",
"Score": "0",
"body": "Solution is actually a type of product, like a Bike or a Book.\nThanks, removed the break; after return"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-02T07:09:01.727",
"Id": "53957",
"Score": "0",
"body": "you have \"return\" in _construct. you shouldn't have return in constructor."
}
] |
[
{
"body": "<h2>Flexible approach</h2>\n\n<ol>\n<li>First defining an ultimate abstraction of the factory</li>\n<li>Implement it with product type - class mapping</li>\n<li><p>Creating an entry point to register and use the factory</p>\n\n<pre><code>interface IProductFactory {\n\n function createProduct($type);\n}\n\nclass DefaultProductFactory implements IProductFactory {\n\n private $_mappings;\n\n public function __construct(array $mappings = array()) {\n $this->_mappings = $mappings;\n }\n\n public function addMappings(array $mappings) {\n $this->_mappings = array_merge($this->_mappings, $mappings);\n }\n\n public function createProduct($type) {\n if (!isset($this->_mappings[$type])) {\n throw new \\Exception(\"Cannot create product of type \" . $type);\n }\n\n $class = $this->_mappings[$type];\n\n //can be passed to a DI container to instantiate if needed\n\n return new $class();\n }\n}\n\nclass ProductFactory {\n\n private static $_factory;\n\n public static function setCurrent(IProductFactory $factory) {\n $this->_factory = $factory;\n }\n\n public static function getCurrent() {\n return $this->_factory;\n }\n}\n\nProductFactory::setCurrent(new DefaultProductFactory(array(\n \"solution1\" => \"Solution1Product\",\n \"solution2\" => \"Solution2Product\",\n \"solution3\" => \"Solution3Product\",\n \"solution4\" => \"Solution4Product\",\n \"solution5\" => \"\\\\\\\\In\\\\\\Some\\\\\\\\Other\\\\\\\\Namespace\\\\\\\\Solution5Product\",\n )));\n\n$solution1 = ProductFactory::getCurrent()->createProduct('solution1');\n\nprint $solution1->calculatePrice(\"02/25/1982\", \"male\", 100000);\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-02T06:22:26.280",
"Id": "33692",
"ParentId": "28290",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:15:33.110",
"Id": "28290",
"Score": "1",
"Tags": [
"php",
"design-patterns",
"factory-method"
],
"Title": "PHP design pattern factory input for products and quotes"
}
|
28290
|
<p>I'm yet to add garbage cleanup, ID regeneration and the ability to unset sessions, but this is what I have so far.</p>
<ul>
<li>Does this help prevent session hijacking/fixation?</li>
<li>Can you see any vulnerabilities?</li>
</ul>
<p><strong>index.php</strong></p>
<p>
<pre><code>require 'Session.class.php';
// I know this isn't done very well
$pdo = new PDO('mysql:host=localhost;dbname=session', 'root', 'root');
$session = new Session($pdo);
$session->set(array(
'username' => 'hello'
));
echo $session->get('username');
</code></pre>
<p><strong>Session.class.php</strong></p>
<pre><code><?php
class Session {
private $_db = null;
private $_expiry = 7200;
private $_id;
private $_data = array();
public function __construct(PDO $db) {
$this->_db = $db;
$this->_run();
if (mt_rand(0, 10) <= 8) $this->_garbageCleanup();
}
public function get($key) {
return isset($this->_data[$key]) ? $this->_data[$key] : FALSE;
}
public function set($data = array()) {
$this->_data = array_merge($data, $this->_data);
$query = $this->_db->prepare("UPDATE `sessions` SET `session_data` = ? WHERE `session_id` = ?");
$query->bindValue(1, serialize($this->_data));
$query->bindValue(2, $this->_id);
$query->execute();
}
private function _run() {
if (isset($_COOKIE['session'])) {
$this->_id = $_COOKIE['session'];
$query = $this->_db->prepare("SELECT * FROM `sessions` WHERE `session_id` = ? AND `session_ip` = ? AND `session_user_agent` = ?");
$query->bindValue(1, $this->_id);
$query->bindValue(2, $_SERVER['REMOTE_ADDR']);
$query->bindValue(3, $_SERVER['HTTP_USER_AGENT']);
$query->execute();
$result = $query->fetch();
$this->_data = unserialize($result['session_data']);
} else {
$this->_createSession();
}
}
private function _createSession() {
$this->_id = md5(microtime() . mt_rand(0, 100));
$query = $this->_db->prepare("INSERT INTO `sessions` VALUES (?, ?, ?, ?)");
$query->bindValue(1, $this->_id);
$query->bindValue(2, serialize($this->_data));
$query->bindValue(3, $_SERVER['REMOTE_ADDR']);
$query->bindValue(4, $_SERVER['HTTP_USER_AGENT']);
$query->execute();
setcookie('session', $this->_id, time() + $this->_expiry);
}
private function garbageCleanup() {
// Does nothing yet, but will later!
}
}
</code></pre>
|
[] |
[
{
"body": "<p>At this moment $_SESSION would be a lot safer then storing it in the database.</p>\n\n<p>What you are doing is the same as session, but instead of storing everything in a file in the filesystem (like $_SESSION does) you are storing it in the database.</p>\n\n<p>$_SESSION works with a cookie (just like your code) that sets an id. The only validation is that 'id'. Once you have guessed that one, you have succesfully hijacked the session.</p>\n\n<p>The only difference here is you are adding</p>\n\n<ol>\n<li>HTTP_USER_AGENT (pointless, this is simply data comming from the\nclient so it can't be trusted)</li>\n<li>REMOTE_ADDR (also comming from the client and it won't protect vs\nman in the middle atacks).</li>\n</ol>\n\n<p>So what your left is, is an id. Just like $_SESSION. And just like with $_SESSION, security stands and falls with the generation of that ID.</p>\n\n<ul>\n<li>You use md5 as hashing algorithm. This is bad, very bad:\n<a href=\"http://en.wikipedia.org/wiki/MD5#Security\" rel=\"nofollow\">http://en.wikipedia.org/wiki/MD5#Security</a> (just read the first\nsentnce).</li>\n<li>Apart from md5, you are also generating it using a time-based\nalgorithm, never, just never do that. If i know the time a session\nstarted, I only need 100 trys... (mt_rand(1,100)). Oh, and mt_rand isn't really random. It is (yes you guessed it, time based pseudo random).</li>\n</ul>\n\n<p>What i recommend is that you use a much stronger algorithm for creating that ID. e.g. pbkdf2: <a href=\"http://php.net/manual/en/function.hash-pbkdf2.php\" rel=\"nofollow\">http://php.net/manual/en/function.hash-pbkdf2.php</a> or similar.</p>\n\n<p>the code itself looks clean! but i have some performance problems:</p>\n\n<p>Everytime you set a var, you do an update to the database. This is inperformant.\nSimply use a __destruct() function where the actual database record gets updated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T07:59:47.447",
"Id": "49291",
"Score": "0",
"body": "REMOTE_ADDR is only \"coming from the client\" in that it is the source address the client is putting on its packets. In order for an attacker to forge that info, it would have to either operate blindly (to the point where it wouldn't even know the connection was successful, let alone that a new session was created, let alone what that session ID is, because the server's responses wouldn't be addressed to it), or have access to one of the networks/routers handling the victim's traffic. And requiring SSL would make REMOTE_ADDR effectively unforgeable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T16:13:31.213",
"Id": "28336",
"ParentId": "28291",
"Score": "1"
}
},
{
"body": "<p>The code has much duplication that should be eliminated.</p>\n\n<p>Every database call, technically, is duplicated functionality. The call to <code>$this->_db->prepare</code> occurs many times, but need only occur once. Consider the following idea:</p>\n\n<pre><code><?php\nuse PDO;\nuse PDOException;\n\n/**\n * Used for interacting with the database. Usage:\n * <pre>\n * $db = Database::get();\n * $db->call( ... );\n * </pre>\n */\nclass Database {\n private static $instance;\n private $dataStore;\n\n /**\n * Sets the connection that this class uses for database transactions.\n */\n public function __construct() {\n global $dbhost;\n global $dbname;\n global $dbuser;\n global $dbpass;\n\n try {\n $this->setDataStore(\n new PDO( \"pgsql:dbname=$dbname;host=$dbhost\", $dbuser, $dbpass ) );\n }\n catch( PDOException $ex ) {\n $this->log( $ex->getMessage() );\n }\n }\n\n /**\n * Returns the singleton database instance.\n */\n public function get() {\n if( self::$instance === null ) {\n self::$instance = new Database();\n }\n\n return self::$instance;\n }\n\n /**\n * Call a database function and return the results. If there are\n * multiple columns to return, then the value for $params must contain\n * a comma; otherwise, without a comma, the value for $params is used\n * as the return column name. For example:\n *\n *- SELECT $params FROM $proc( ?, ? ); -- with comma\n *- SELECT $proc( ?, ? ) AS $params; -- without comma\n *- SELECT $proc( ?, ? ); -- empty\n *\n * @param $proc Name of the function or stored procedure to call.\n * @param $params Name of parameters to use as return columns.\n */\n public function call( $proc, $params = \"\" ) {\n $args = array();\n $count = 0;\n $placeholders = \"\";\n\n // Key is zero-based (e.g., $proc = 0, $params = 1).\n foreach( func_get_args() as $key => $parameter ) {\n // Skip the $proc and $params arguments to this method.\n if( $key < 2 ) continue;\n\n $count++;\n $placeholders = empty( $placeholders ) ? \"?\" : \"$placeholders,?\";\n array_push( $args, $parameter );\n }\n\n $sql = \"\";\n\n if( empty( $params ) ) {\n // If there are no parameters, then just make a call.\n $sql = \"SELECT $proc( $placeholders )\";\n }\n else if( strpos( $params, \",\" ) !== false ) {\n // If there is a comma, select the column names.\n $sql = \"SELECT $params FROM $proc( $placeholders )\";\n }\n else {\n // Otherwise, select the result into the given column name.\n $sql = \"SELECT $proc( $placeholders ) AS $params\";\n }\n\n $statement = $this->getDataStore()->prepare( $sql );\n\n //$this->log( \"SQL: $sql\" );\n\n for( $i = 1; $i <= $count; $i++ ) {\n //$this->log( \"Bind \" . $i . \" to \" . $args[$i - 1] );\n $statement->bindParam( $i, $args[$i - 1] );\n }\n\n $statement->execute();\n $result = $statement->fetchAll();\n $this->decodeArray( $result );\n\n return $result;\n }\n\n /**\n * Converts an array of numbers into an array suitable for usage with\n * PostgreSQL.\n *\n * @param $array An array of integers.\n */\n public function arrayToString( $array ) {\n return \"{\" . implode( \",\", $array ) . \"}\";\n }\n\n /**\n * Recursive method to decode a UTF8-encoded array.\n *\n * @param $array - The array to decode.\n * @param $key - Name of the function to call.\n */\n private function decodeArray( &$array ) {\n if( is_array( $array ) ) {\n array_map( array( $this, \"decodeArray\" ), $array );\n }\n else {\n $array = utf8_decode( $array );\n }\n }\n\n private function getDataStore() {\n return $this->dataStore;\n }\n\n private function setDataStore( $dataStore ) {\n $this->dataStore = $dataStore;\n }\n}\n?>\n</code></pre>\n\n<p>For some example usages, see: <a href=\"https://codereview.stackexchange.com/q/26507/20611\">Generic method for database calls</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-08T18:45:33.460",
"Id": "30961",
"ParentId": "28291",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:27:10.340",
"Id": "28291",
"Score": "4",
"Tags": [
"php",
"session"
],
"Title": "My Session Handler"
}
|
28291
|
<p>I have written an infix-to-postfix program that I would like reviewed and with a few suggestions on improving it, such as a more modularized approach.</p>
<pre><code>package basicstrut;
import java.util.Stack;
public class Infix {
private String infixStr;
private Stack<Character> oprStack;
public Infix(String infixStr){
oprStack = new Stack<Character>();
this.infixStr = infixStr;
}
public String toPostFix(){
StringBuffer buf = new StringBuffer(infixStr.length());
for(int i=0;i<infixStr.length();i++){
char str = (infixStr.charAt(i));
if(valueOfOpr(str) == 0){
buf.append(str);
if(i != infixStr.length()-1 && !oprStack.isEmpty()){
char nextChar = (infixStr.charAt(i+1));
char opStack = oprStack.peek();
int compare = compareOperators (opStack,nextChar);
if(compare >0 && valueOfOpr(opStack) != 5) {
opStack = oprStack.pop();
buf.append(opStack);
}
}
}
if(i == infixStr.length()-1){
if(valueOfOpr(str) > 0 && valueOfOpr(str) != 6) throw new RuntimeException("Invalid Expression");
while(!oprStack.isEmpty()){
char temp = oprStack.pop();
if(valueOfOpr(temp) != 5)buf.append(temp);
}
}else if (valueOfOpr(str) > 0){
if(oprStack.isEmpty()) {
oprStack.push(str);
}else{
if(valueOfOpr(str) == 6){
while(!oprStack.isEmpty()){
char temp = oprStack.pop();
if(valueOfOpr(temp) != 5)buf.append(temp);
}
}else{
char opStack = oprStack.pop();
int compare = compareOperators (opStack,str);
if(compare >0) {
oprStack.push(str);oprStack.push(opStack);
}else{
oprStack.push(opStack);oprStack.push(str);
}
}
}
}
}
return buf.toString();
}
public int compareOperators(char op1 , char op2){
return valueOfOpr( op1) - valueOfOpr( op2) ;
}
public int valueOfOpr(char op){
int value = 0;
switch (op) {
case '*':
value = 4;
break;
case '/':
value = 3;
break;
case '+':
value = 2;
break;
case '-':
value = 1;
break;
case '[':
case ']':
case '(':
value = 5;
break;
case ')':
value = 6;
break;
default:
break;
}
return value;
}
public static void main(String[] args) {
Infix i = new Infix("A+B");
/* System.out.println("A+B -->"+i.toPostFix());
i = new Infix("A+B-C");
System.out.println("A+B-C -->"+i.toPostFix());
i = new Infix("A+B*C");
System.out.println("A+B*C -->"+i.toPostFix());
i = new Infix("A*B+C");
System.out.println("A*B+C -->"+ i.toPostFix());
i = new Infix("A/B+C");
System.out.println("A/B+C -->"+i.toPostFix());
i = new Infix("A+B/C");
System.out.println("A+B/C -->"+ i.toPostFix());
*/
i = new Infix("A*(B+C)");
System.out.println("A*(B+C) -->"+ i.toPostFix());
i = new Infix("A*(B+C)*(D+E)");
System.out.println("A*(B+C)*(D+E) -->"+ i.toPostFix());
i = new Infix("A*(B+C)-D/(E+F)");
System.out.println("A*(B+C)-D/(E+F) -->"+ i.toPostFix());
i = new Infix("A*(B+C)-D/(E+F)*G+H");
System.out.println("A*(B+C)-D/(E+F)*G+H -->"+ i.toPostFix());
i = new Infix("(A*B*(C+D))");
System.out.println("(A*B*(C+D)) -->"+ i.toPostFix());
i = new Infix("(A*B*(C+D)*E+F)");
System.out.println("(A*B*(C+D)*E+F) -->"+ i.toPostFix());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T11:30:40.750",
"Id": "44358",
"Score": "0",
"body": "@DaveJarvis What kind of life cycle for `Infix` are you imagining such that it ever needs to be thread-safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:45:29.337",
"Id": "44402",
"Score": "0",
"body": "@abuzittingillifirca: Simultaneous calls to `toPostFix` will corrupt the `oprStack` variable. Since `oprStack` is only ever used by `toPostFix`, move it into that method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T06:06:04.110",
"Id": "44435",
"Score": "0",
"body": "@DaveJarvis You are absolutely right about `oprStack` belonging to `toPostFix` (Also `infixStr` should be `final`. ); with or without `Infix` needing to be thread-safe. And it needs not. Actually `toPostFix` will not be called in a thread twice either. `Infix` is just a function masquerading as a class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T08:44:09.267",
"Id": "44452",
"Score": "0",
"body": "@Dave - yes sure thing."
}
] |
[
{
"body": "<p>One small thing you can do is improve the readability of things like </p>\n\n<pre><code>valueOfOpr(opStack) != 5\n</code></pre>\n\n<p>by making an <code>Operator enum</code> like so (notice I took the liberty of re-ordering the square brackets, correct me if I'm wrong):</p>\n\n<pre><code>public static enum Operator {\n NOT_AN_OPERATOR(0, \"\"),\n SUBTRACTION(1, \"-\"),\n ADDITION(2, \"+\"),\n DIVISION(3, \"/\"),\n MULTIPLICATION(4, \"*\"),\n OPEN_BRACKET(5, \"[(\"),\n CLOSE_BRACKET(6, \"])\");\n\n private final int precedence;\n private final String symbol;\n\n private Operator(int precedence, String symbol) {\n this.precedence = precedence;\n this.symbol = symbol;\n }\n\n public int getPrecedence() {\n return precedence;\n }\n\n public static boolean isOperator(char symbol, Operator operator) {\n return operator.symbol.indexOf(symbol) != -1;\n }\n}\n</code></pre>\n\n<p>That way, </p>\n\n<pre><code>valueOfOpr(str) == 0\nvalueOfOpr(opStack) != 5\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>!Operator.isOperator(str, Operator.NOT_AN_OPERATOR);\n!Operator.isOperator(opStack, Operator.OPEN_BRACKET);\n</code></pre>\n\n<p>etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:22:42.660",
"Id": "44487",
"Score": "0",
"body": "@kuporific: I'd recommend `Operator.isOperator( str, Operator.NOT_AN_OPERATOR )` over using a `get` method. Typically `get` methods are not OO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:52:13.203",
"Id": "44490",
"Score": "1",
"body": "@DaveJarvis Thanks for the recommendation, I have edited the answer accordingly. `isOperator` produces a much cleaner solution (no more case/switch)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T17:57:20.890",
"Id": "28301",
"ParentId": "28294",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T15:05:01.093",
"Id": "28294",
"Score": "2",
"Tags": [
"java",
"performance",
"algorithm",
"math-expression-eval"
],
"Title": "Infix to Postfix conversion in Java"
}
|
28294
|
<p>I have a method:</p>
<pre><code> def removeExpiredCookies(jar: CookieJar): CookieJar = {
val currentDate = System.currentTimeMillis / 1000L
jar.filter(_._2._2 > currentDate)
}
</code></pre>
<p>You use said method like so.</p>
<pre><code>var cookieJar = new CookieJar
cookieJar = removeExpiredCookies(cookieJar)
</code></pre>
<p>That method has no side effects. But it's used inside a class:</p>
<pre><code>class CookieManager {
type ExpiryDate = Long
type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]
var cookieJar = new CookieJar
private def removeExpiredCookies(jar: CookieJar): CookieJar = {
val currentDate = System.currentTimeMillis / 1000L
jar.filter(_._2._2 > currentDate)
}
def getCookie(domain: String): Set[Cookie] = {
cookieJar = removeExpiredCookies(cookieJar)
cookieJar.find(_._1 endsWith (domain))
}
}
</code></pre>
<p>Is it better to write the method such as above or to have a more succinct and readable code but with side-effecting methods? I'm guessing as this is encapsulated inside a class, this is actually "better" for maintainability but it is not as pure functional programming. It's an imperative style. However, the strongest argument against this is that it's more difficult to test as the tests are not as isolated. </p>
<pre><code>class CookieManager {
type ExpiryDate = Long
type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]
var cookieJar = new CookieJar
private def removeExpiredCookies {
val currentDate = System.currentTimeMillis / 1000L
cookieJar = cookieJar.filter(_._2._2 > currentDate)
}
def getCookie(domain: String): Set[Cookie] = {
removeExpiredCookies() //bracket to indicate side effect
cookieJar.find(_._1 endsWith (domain))
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T21:15:31.163",
"Id": "44299",
"Score": "0",
"body": "You could also put `removeExpiredCookies` to `CookieManager`'s (along with the types) companion object. This way, it'd be obvious that it doesn't use or modify any `CookieManager`'s state."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T01:57:34.203",
"Id": "44336",
"Score": "0",
"body": "Actually putting the types in the companion object seems to hide them - I guess I can call them out at CookieManager.CookieJar"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T02:20:28.150",
"Id": "44339",
"Score": "0",
"body": "Yes I think you're right - putting things in the companion object appears to be much nicer. The methods are side effect free so anything that is side effect free can be static. It makes the class very nice."
}
] |
[
{
"body": "<p>(I'm making my comment into an answer.) You can separate everything that is static (not using the state of instances of <code>CookieManager</code>) into a companion object (and import the object at the beginning of the class for convenience). This way, it is clear what functions use <code>this</code> directly or indirectly (by accessing class variables). This often helps me make my code clearer, and prevents stupid mistakes such as confuse class variables with function arguments etc.</p>\n\n<pre><code>class CookieManager {\n import CookieManager._\n\n var cookieJar = new CookieJar\n\n def getCookie(domain: String): Set[Cookie] = {\n cookieJar = removeExpiredCookies(cookieJar)\n cookieJar.find(_._1 endsWith (domain))\n }\n}\n\nobject CookieManager {\n type ExpiryDate = Long\n type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]\n\n private def removeExpiredCookies(jar: CookieJar): CookieJar = {\n val currentDate = System.currentTimeMillis / 1000L\n jar.filter(_._2._2 > currentDate)\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T13:28:07.570",
"Id": "44360",
"Score": "0",
"body": "I think this is a good improvement"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T16:34:23.947",
"Id": "44371",
"Score": "0",
"body": "Implicits can be used as well - I'm going to edit your post to demonstrate how implicit can be used to further get the code cleaner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T16:48:17.420",
"Id": "44372",
"Score": "0",
"body": "@JasonG I'd say in this case implicits go against clean code. Generally, implicits make often code harder to read - you have to search, from where an implicit comes from. I'd definitely not use it in this case. I'd rather make `removeExpiredCookies` a member of the class and let it use `cookieJar` variable directly, if you want to take this approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T17:04:15.543",
"Id": "44374",
"Score": "0",
"body": "Okay I'll revert that"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T05:02:47.333",
"Id": "28316",
"ParentId": "28297",
"Score": "2"
}
},
{
"body": "<p>What I see in your code are side effects which are completely orthogonal to readability. Why are you purging the cookie jar whenever you fetch a cookie? If you are doing it to save having a separate Purge method, that's lazy in the worst way. What is ostensibly a read-only method is modifying the object. Why? What do you gain apart from not having to think about cookie management (this is lazy in a <strong>bad</strong> way)? What you lose is the ability to inspect and manage expired cookies (there may be many valid reasons for wanting to do this). Why hide a surprise side effect like this?</p>\n\n<p>If you want getCookie only to return current cookies, have it fetch from a filtered cookiejar. You can achieve this simply by changing that method to this:</p>\n\n<pre><code>def getCookie(domain: String): Set[Cookie] = {\n val safeCookieJar = removeExpiredCookies(cookieJar)\n safeCookieJar.find(_._1 endsWith (domain))\n}\n</code></pre>\n\n<p>Create a separate purgeJar method which actually removes expired cookies. <strong>Know</strong> when you are modifying the object.</p>\n\n<p>Personally, I'd rather give the calling code the choice about how to filter the jar. If you </p>\n\n<ol>\n<li>add a set of useful filters to the CookieManager class (including a noExpiredCookies filter)</li>\n<li>allow for the creation of new cookieJar filters</li>\n<li>add a filter parameter to getCookie</li>\n<li>have that parameter default to noExpiredCookies</li>\n</ol>\n\n<p>You get the current behaviour while offering much more flexibility.</p>\n\n<p>Really, though, for the best of readability, minimisation of unexpected side-effects <em>and</em> flexibility, I recommend you create a CookieJar class which knows how to do all the basic things with cookies and a CookieManager class which knows how to enforce policy on cookies (e.g. ensuring that only current cookies are returned by default, choosing a cookie purging policy etc.) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T17:39:47.203",
"Id": "47761",
"Score": "1",
"body": "Really good advice about the side effects of purging - I agree with that 100% and have to bring that attentiveness to my day to day. Thanks for the review!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T21:05:27.897",
"Id": "48097",
"Score": "0",
"body": "Hey I wanted to come back and thank you again - I just reviewed and refactored a co-workers code today and I pulled out the same piece of advice where there was a side-effect stuffed somewhere. I pulled it out and put it into the top level space where a message was being handled. Much better now -easier to understand etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-27T09:22:09.513",
"Id": "48134",
"Score": "0",
"body": "No problem :) The people who have to deploy your code and make it scale will be very grateful to you. For them, it is usually very important to know which code changes state (and thus requires write access to some persistent store) and which code does not (and so can make do with a read-only cache/replica)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T15:00:47.130",
"Id": "30083",
"ParentId": "28297",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T16:40:46.573",
"Id": "28297",
"Score": "3",
"Tags": [
"functional-programming",
"scala"
],
"Title": "What takes precedence: readability or elimination of side effects?"
}
|
28297
|
<p>this code works fine but i want to know if this can be improved in any manner .</p>
<p>For every user I am fetching the namesList corresponding to that user and for each fetched nameList , i am fetching the ItemsList .</p>
<p>I have tried to replicate the sample using this below standalone program as i cant paste my project code as it got huge dependencies </p>
<p>So i am hardcoding the users and the names List corresponding to that user .</p>
<pre><code>package com;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String args[]) {
List<String> users = new ArrayList<String>();
users.add("user101");
users.add("adminuser");
for (String user : users) {
try {
ArrayList<String> namesCorrespondingtoUser = getNamesCorrespondingtoUser(user);
for (String Id : namesCorrespondingtoUser) {
List<String> Items = getItemsCorrespondingtoId(user, Id);
filter(Items, user,Id);
}
} catch (Exception e) {
}
}
}
public static ArrayList<String> getNamesCorrespondingtoUser(String userName)
throws Exception {
ArrayList<String> names = new ArrayList<String>();
if (userName.equals("user101")) {
names.add("UBSC1");
names.add("HDBG1");
names.add("GHYU1");
}
if (userName.equals("adminuser")) {
names.add("UBSC1");
names.add("HDBG1");
names.add("GHYU1");
}
return names;
}
public static List<String> getItemsCorrespondingtoId(String userName,
String Id) throws Exception {
ArrayList<String> items = new ArrayList<String>();
return items ;
}
private static void filter(List<String> Items, String user,String Id) {
// do something with the ID value of that User .
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:37:24.387",
"Id": "44286",
"Score": "0",
"body": "`Names` is orthogonal to `Items`, right? That is, names are related to a user, and items are related to a user, but (user) names aren't really related to items. `getItemsCorrespondingToId()` is operating by `user` - doing it _per name_ is just burning cycles, get the same answer multiple times. Pull the item list retrieval out of that second loop. Do you actually need to do something per-name?"
}
] |
[
{
"body": "<p>Before avoiding to nesting for loop you must have to clean you code ..Here is the same code mentioned in your question with little bit of correction which helps you to write clean code. \nChanges : </p>\n\n<ul>\n<li>Use interfaces instead of implementations</li>\n<li>Use final in methos parameters so that reference can't be changed</li>\n<li>use if else if instead of multiple if's where only 1 can be true at a time</li>\n</ul>\n\n<p><strong>getNamesCorrespondingtoUser</strong></p>\n\n<pre><code>public static List<String> getNamesCorrespondingtoUser(final String userName) {\n List<String> names = new ArrayList<String>();\n if (userName.equals(\"user101\")) {\n names.add(\"UBSC1\");\n names.add(\"HDBG1\");\n names.add(\"GHYU1\");\n } else if (userName.equals(\"adminuser\")) {\n names.add(\"UBSC1\");\n names.add(\"HDBG1\");\n names.add(\"GHYU1\");\n }\n return names;\n}\n</code></pre>\n\n<p><strong>getItemCorrespondingToId</strong></p>\n\n<pre><code>public static List<String> getItemsCorrespondingtoId(final String userName, final String Id) {\n List<String> items = new ArrayList<String>();\n return items ;\n}\n</code></pre>\n\n<p><strong>main</strong></p>\n\n<pre><code>public static void main(String args[]) {\n List<String> users = new ArrayList<String>();\n users.add(\"user101\");\n users.add(\"adminuser\");\n\n for (String user : users) {\n try {\n List<String> namesCorrespondingtoUser = getNamesCorrespondingtoUser(user);\n for (String Id : namesCorrespondingtoUser) {\n List<String> Items = getItemsCorrespondingtoId(user, Id);\n filter(Items, user,Id);\n }\n } catch (Exception e) {\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T03:20:52.853",
"Id": "28312",
"ParentId": "28302",
"Score": "2"
}
},
{
"body": "<p>I've seen, that you made up this code as an example, so I hope, that this is not your production code: </p>\n\n<pre><code>public static ArrayList<String> getNamesCorrespondingtoUser(String userName)\n throws Exception {\n ArrayList<String> names = new ArrayList<String>();\n if (userName.equals(\"user101\")) {\n names.add(\"UBSC1\");\n names.add(\"HDBG1\");\n names.add(\"GHYU1\");\n }\n if (userName.equals(\"adminuser\")) {\n names.add(\"UBSC1\");\n names.add(\"HDBG1\");\n names.add(\"GHYU1\");\n }\n return names;\n\n}\n</code></pre>\n\n<p>If you take a look at both blocks, they are the same, aren't they?\nBut for further improvement, I would suggest working with a <code>Map</code> where you have usernames as the key and the according List of Names as the result.</p>\n\n<p><em>Second</em>: I would reccomend you to take a look at Google's Guava Library esp. the section about <a href=\"https://code.google.com/p/guava-libraries/wiki/FunctionalExplained#Predicates\" rel=\"nofollow\">predicates</a> .</p>\n\n<p><em>Third</em>: I am wondering, how you could retrieve any correct item. As far as I can see your names have to be unique to resolve the correct items. The collision rate for (nick-)names is generally high. So it would be better to switch to some ID-mechanism. </p>\n\n<p><em>Fourth</em>: The task is in itself nested; you need to iterate over a list of items and over a list of users. So you couldn't \"avoid\" a nested loop. Okay: If you let a database do the magic, you didn't loop at all - the database does. But I think, that is not the answer you wanted. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T08:19:12.530",
"Id": "28318",
"ParentId": "28302",
"Score": "3"
}
},
{
"body": "<p>The code needs <span class=\"math-container\">\\$m \\times n\\$</span> loops. I don't think looping can be avoided (application or database), but a number of round-trips can be avoided if source of names and items are same. This will improve the latency introduced by repeated network calls to distant database or web-services. For example: </p>\n\n<ol>\n<li>In case of database - stored procedure can be called to return user data-set required for filter method.</li>\n<li>In case of web-service - coarse grained API calls can be made (if available from service provider). </li>\n</ol>\n\n<p>Another way to improve the turnaround time for processing each user by introducing some parallelism; e.g., with the help of Java8's parallel streams. </p>\n\n<pre><code>users.parallelStream().forEach(user -> processUser(user));\n</code></pre>\n\n<p>Code inside outer loop moved into <code>processUser()</code> which uses <code>parallelStream</code> further down the line.</p>\n\n<pre><code>private static void processUser(String user) {\n try {\n getNamesCorrespondingtoUser(user).parallelStream().forEach(id -> {\n List<String> items = getItemsCorrespondingtoId(user, id);\n filter(items, user, id);\n });\n } catch(Exception e) {\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T11:04:17.667",
"Id": "220899",
"ParentId": "28302",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28318",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T18:12:04.293",
"Id": "28302",
"Score": "1",
"Tags": [
"java"
],
"Title": "Can I avoid nested for loop in this case?"
}
|
28302
|
<p>I have a Rails app and in it I have two models, widget and votes. Votes are used to keep track of the desirability of a widget.</p>
<p>In my models I have:</p>
<pre><code>class Vote < ActiveRecord::Base
belongs_to :widget
end
class Widget < ActiveRecord::Base
has_many :votes
end
</code></pre>
<p>I am trying to figure out the best way to route votes up and votes down. At the moment I am leaning towards this: </p>
<pre><code>resources :widgets do
member do
put :vote_up
put :vote_down
end
end
</code></pre>
<p>Where the respective functions reside in the widgets' controller and it creates and saves votes in that controller. However, I realize that this doesn't really fit correctly with the MVC idea (votes should be created and built in their own controller). Is this acceptable or should I be doing something more like:</p>
<pre><code>resources :widgets do
resources :votes do
member do
put :vote_up
put :vote_down
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>I would not create custom controller actions. <code>up</code> and <code>down</code> are attributes of a <code>Vote</code>, so I would do the following:</p>\n\n<pre><code>resources :widgets do\n resources :votes, only: [:new, :create]\nend\n</code></pre>\n\n<p>And then send a <code>POST</code> to <code>VotesController#create</code> with <code>params[direction: 'up']</code> and have an attribute on <code>Vote</code> called <code>direction</code>.</p>\n\n<p>Then validate <code>Vote#direction</code> can only be up or down:</p>\n\n<pre><code>class Vote < ActionController:Base\n validates_inclusion_of :direction, in: %w(up down)\nend \n</code></pre>\n\n<p>Your check for this kind of routing decision is to run <code>rake routes</code> and make sure the route aliases make sense, in this case we are really creating <code>widget_votes</code>, which looks like:</p>\n\n<pre><code> Prefix Verb URI Pattern Controller#Action\n widget_votes POST /widgets/:widget_id/votes(.:format) votes#create\nnew_widget_vote GET /widgets/:widget_id/votes/new(.:format) votes#new\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:51:17.683",
"Id": "41901",
"ParentId": "28303",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:13:08.967",
"Id": "28303",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"mvc",
"url-routing"
],
"Title": "Nested routes and proper place for a function?"
}
|
28303
|
<p>Is there a better way to implement this class, or does it not constitute implementation in the first place? This is one of my first few tries at OOP. Any suggestions will be much appreciated. </p>
<pre><code>#include <iostream>
#include <vector>
#include <cmath>
class PrimeList
{
public:
std::vector<int> vPrime;
void initVector(int n)
{
for (int i=2; i <= n; ++i)
vPrime.push_back(i);
}
};
int main()
{
// Instantiate an object "primes" of type PrimeList.
PrimeList primes;
// Get the input variable to pass to the initVector method.
std::cout << "Enter the upper limit of the list of primes you want to generate:" << std::endl;
int n;
std::cin >> n;
// Create a vector filled with every integer from 2 to n.
primes.initVector(n);
// Begin the sieve
for (int a=0; a < sqrt(n); ++a) {
for (int b=a+1; b < primes.vPrime.size(); ++b) {
if (primes.vPrime[b] % primes.vPrime[a] == 0) {
primes.vPrime.erase(primes.vPrime.begin() + b);
}
}
}
// Print the list of primes from 2 to n.
for (int i=0; i < primes.vPrime.size(); ++i)
std::cout << primes.vPrime[i] << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T22:38:36.707",
"Id": "44319",
"Score": "1",
"body": "You have a small typo -- `sqrt` should be `std::sqrt`. Unfortunately, some compilers don't warn about this, and then we're in for a nasty surprise when the code suddenly refuses to compile on another platform."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T23:15:54.077",
"Id": "44326",
"Score": "0",
"body": "Thanks matt! I think that means this loop was iterating while a < n! Assuming that the compiler just ignored the sqrt() and ran with its parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T23:22:48.090",
"Id": "44329",
"Score": "0",
"body": "@ao2130: not quite. I've been in this same situation before-- my compiler just ignored the absent `std::` but still called the function. I have no idea why some compilers don't catch this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T00:39:19.707",
"Id": "44333",
"Score": "2",
"body": "What's worse, is that unqualified functions will be called as C-style functions (**without** overloading -- important, since this means truncation & losing precision). Compare C++'s `std::abs` (will work on `double` and others) with C's `abs` (will only work with `int`). When a \"lenient\" (but actually unhelpful) compiler doesn't warn about a misuse like this (which happens all to often :[), the same source code may produce completely wrong results on another platform :-( Really wish compilers (looking at MSVC here in particular) were more strict about this."
}
] |
[
{
"body": "<ul>\n<li><p>As a general rule for classes: data members (variables), such as <code>vPrime</code>, should be <code>private</code>. They can either be declared under <code>private</code> or outside of <code>public</code> (a <code>class</code> is <code>private</code> by default).</p></li>\n<li><p>For a simple use of classes here, you don't need a mutator. Just declare your object with an argument:</p>\n\n<pre><code>PrimeList primes(n);\n</code></pre>\n\n<p>Since this would make <code>n</code> (or let's just make it <code>number</code>) a data member, modify your constructor as such and initialize the object like this:</p>\n\n<pre><code>// 'n' is the parameter and 'number' is the class's data member\nPrimeList::PrimeList(int n) : number(n) {initVector();}\n</code></pre>\n\n<p>As you can see, the constructor now calls <code>initVector()</code>. With <code>number</code> now as a data member, <code>initVector()</code> no longer needs an argument. Since this function is not part of the interface, make it <code>private</code>.</p></li>\n<li><p>The display for-loop in <code>main()</code> can also be put into a class method:</p>\n\n<pre><code>void display() const; // header declaration\n\n// .cpp implementation\n\nvoid PrimeList::display() const\n{\n // your object is no longer referenced inside the class\n for (int i = 0; i < vPrime.size(); ++i)\n {\n std::cout << vPrime[i] << std::endl;\n }\n}\n</code></pre>\n\n<p>Then simple call it in <code>main()</code> with your object:</p>\n\n<pre><code>primes.display();\n</code></pre>\n\n<p>Note the use of <code>const</code> fin this function. If you're <em>not</em> changing any data members, create your functions as such. If you accidentally violate this, your compiler will stop you. This is to ensure that your data members are not unintentionally modified, depending on the functions's purpose.</p></li>\n<li><p>Your sieve calculations can <em>also</em> be put into a class method. Get the idea now? Again, it should be <code>private</code>. It will NOT be <code>const</code> since you're changing the <code>vector</code> inside the class. You can call it in <code>initVector()</code> since they're both non-<code>const</code> (you cannot call <code>const</code> functions in non-<code>const</code> functions and vice-versa).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T22:14:42.620",
"Id": "44314",
"Score": "0",
"body": "@user2164854: You're welcome! Happy to help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T20:58:28.023",
"Id": "28308",
"ParentId": "28306",
"Score": "3"
}
},
{
"body": "<p>Your <code>PrimeList</code> doesn't follow object-oriented design principles; it's just a thin wrapper for a <code>std::vector</code> that doesn't do much.</p>\n\n<p>A goal of object-oriented design is to create objects as \"smart\" data. Your <code>PrimeList</code> class should know how to maintain itself in a self-consistent state. <code>PrimeList</code> is supposed to know all about how to find prime numbers. Users of the class should be able to ask it what the <em>n</em><sup>th</sup> prime number is. Instead, you have made your <code>main()</code> function do all the hard work.</p>\n\n<p>Think about how users of your class would want to call your code. For example, this would be a nice interface:</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n PrimeList primes;\n // http://en.wikipedia.org/wiki/List_of_prime_numbers#The_first_500_prime_numbers\n std::cout << primes[0] << \" should be 2\" << std::endl;\n std::cout << primes[499] << \" should be 3571\" << std::endl;\n return 0;\n}\n</code></pre>\n\n<p>Now, let's design the class to make that happen. Here's a start:</p>\n\n<pre><code>class PrimeList {\n public:\n PrimeList();\n\n // Returns the nth prime number\n // (primelist[0] is 2, primelist[1] is 3, etc.)\n unsigned long operator[](size_t nth);\n};\n</code></pre>\n\n<p>To make that work, though, <code>PrimeList</code> needs to keep some state internally. I would use a vector for running the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a>. For convenience and efficiency, I would keep another vector of just the primes that have been discovered using that sieve. I also need to have some code for creating and maintaining that sieve. That code and the two vectors are part of the internal workings of <code>PrimeList</code>, and are none of the caller's business. Therefore, they should be declared as <code>private</code> members of the <code>PrimeList</code> class:</p>\n\n<pre><code>class PrimeList {\n public:\n PrimeList();\n\n // Returns the nth prime number\n // (primelist[0] is 2, primelist[1] is 3, etc.)\n unsigned long operator[](size_t nth);\n\n private:\n std::vector<bool> sieve; // sieve[i] is true if i is prime\n std::vector<unsigned long> knownPrimes;\n\n void findMorePrimes();\n};\n</code></pre>\n\n<p>Then, it's just a matter of filling in the code. =) Here is a possible solution.</p>\n\n<pre><code>PrimeList::PrimeList() {\n sieve.push_back(false); // 0 is not prime\n sieve.push_back(false); // 1 is not prime\n knownPrimes.push_back(2);\n}\n\nunsigned long PrimeList::operator[](size_t nth) {\n while (nth >= knownPrimes.size()) {\n findMorePrimes();\n }\n return knownPrimes[nth];\n}\n\nvoid PrimeList::findMorePrimes() {\n // Initially, sieve is a vector where every element is assumed\n // to be prime (sieve[i] = true).\n // Then, we will set sieve[i] = false for all i where i is non-\n // prime. Special cases for non-primes sieve[0] = false and\n // sieve[1] = false were already established in the constructor.\n\n // Enlarge the sieve by some arbitrary amount\n std::vector<bool>::size_type prevSieveSize = sieve.size();\n sieve.resize(4 * prevSieveSize, /* is_prime= */ true);\n\n // Strike out the composite numbers from the enlarged sieve\n for (std::vector<unsigned long>::iterator p = knownPrimes.begin();\n p != knownPrimes.end();\n ++p) {\n for (std::vector<bool>::size_type multiple = (prevSieveSize / (*p)) * (*p);\n multiple < sieve.size();\n multiple += (*p)) {\n sieve[multiple] = false;\n }\n }\n\n // Harvest the newly discovered prime numbers\n for (std::vector<bool>::size_type i = prevSieveSize; i < sieve.size(); ++i) {\n if (sieve[i]) {\n knownPrimes.push_back(i);\n }\n }\n}\n</code></pre>\n\n<p>Note that in order to maintain the illusion of an unbounded list of primes, <code>findMorePrimes()</code> is more complicated than an implementation of the Sieve of a predetermined size. That additional bookkeeping is the price to be paid for the desire to present a pretty interface to the outside world. It's also illustrates the power of object-oriented programming to manage complexity, as you can see in the simplicity of the <code>main()</code> example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T07:02:15.257",
"Id": "51562",
"Score": "1",
"body": "Properly speaking, `PrimeList` should use the [singleton pattern](http://en.wikipedia.org/wiki/Singleton_pattern), but I wanted to keep things simple for now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T06:55:59.950",
"Id": "32275",
"ParentId": "28306",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28308",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:55:06.117",
"Id": "28306",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"classes",
"beginner",
"primes"
],
"Title": "Object-oriented design of list of primes"
}
|
28306
|
<p>Here's a simple algorithm that walks the DOM given a node:</p>
<pre><code>function walkDOM(n) {
do {
console.log(n);
if (n.hasChildNodes()) {
walkDOM(n.firstChild)
}
} while (n = n.nextSibling)
}
</code></pre>
<p>I wanted to implement it iteratively as an exercise, and came up with this:</p>
<pre><code>function walkDOM2(n) {
var recStack = [];
// First get the parent of the given node, so that
// you can get the siblings of the given node too
// (starting from the last sibling),
// rather than just start with the children of the
// given node.
// (This is to make this behave the
// same way as the recursive one.)
recStack.push(n.parentNode);
while (recStack.length > 0) {
var current = recStack.pop();
// Log only if the current node is
// the given node or a node below it.
// (This is to make this behave the
// same way as the recursive one.)
if (current != n.parentNode)
console.log(current);
if (!current.hasChildNodes())
continue;
current = current.lastChild;
do {
recStack.push(current);
// Skip the sibling nodes
// before the given node.
// (This is to make this behave the
// same way as the recursive one.)
if (current === n)
break;
} while (current = current && current.previousSibling);
}
}
</code></pre>
<p>I have used a couple tricks to make it behave the same way as the first recursive version. Is there a more concise way of writing this without recursion?</p>
|
[] |
[
{
"body": "<p>I know you are doing this as an exercise, and personally I like the recursive function. But just as an alternative, there is also the much forgotten <kbd><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/treeWalker?redirectlocale=en-US&redirectslug=DOM/treeWalker\" rel=\"noreferrer\">TreeWalker API</a></kbd>.</p>\n\n<blockquote>\n <p><strong>Browser compatibility</strong></p>\n \n <p>Supported by IE9+, FF2+, Chrome 1+, Safari 3+, Opera 9+</p>\n</blockquote>\n\n<p>Javascript</p>\n\n<pre><code>var treeWalker = document.createTreeWalker(document.getElementById(\"list\"), NodeFilter.SHOW_ALL, {\n acceptNode: function (node) {\n return NodeFilter.FILTER_ACCEPT;\n }\n}, false);\n\ndo {\n console.log(treeWalker.currentNode);\n} while (treeWalker.nextNode());\n</code></pre>\n\n<p>On <kbd><a href=\"http://jsfiddle.net/Xotic750/Ttgn7/\" rel=\"noreferrer\">jsfiddle</a></kbd></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-16T15:49:37.680",
"Id": "333488",
"Score": "0",
"body": "This is very nice... there's just one fly in the ointment for practical use: in the `acceptNode` method (method of `NodeFilter` interface, it seems) there appears to be no easy way of getting the depth of the node passed as the parameter. Shame - non-recursive tree traversal is usually preferable because of memory questions, etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T00:02:12.580",
"Id": "28447",
"ParentId": "28307",
"Score": "9"
}
},
{
"body": "<p>Here is another version that uses <a href=\"/questions/tagged/iteration\" class=\"post-tag\" title=\"show questions tagged 'iteration'\" rel=\"tag\">iteration</a> rather than <a href=\"/questions/tagged/recursion\" class=\"post-tag\" title=\"show questions tagged 'recursion'\" rel=\"tag\">recursion</a>. It uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue\" rel=\"nofollow\"><code>continue</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break?redirectlocale=en-US&redirectslug=JavaScript/Reference/Statements/break\" rel=\"nofollow\"><code>break</code></a>, and a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label?redirectlocale=en-US&redirectslug=JavaScript/Reference/Statements/label\" rel=\"nofollow\"><code>label</code></a>.</p>\n\n<blockquote>\n <p><strong>Avoid using labels</strong></p>\n \n <p>Labels are not very commonly used in JavaScript since they make\n programs harder to read and understand. As much as possible, avoid\n using labels and, depending on the cases, prefer calling functions or\n throwing an error.</p>\n</blockquote>\n\n<p>Javascript</p>\n\n<pre><code>function walkDOM(root, func) {\n var node = root;\n\n start: while (node) {\n func(node);\n if (node.firstChild) {\n node = node.firstChild;\n continue start;\n }\n\n while (node) {\n if (node === root) {\n break start;\n }\n\n if (node.nextSibling) {\n node = node.nextSibling;\n continue start;\n }\n\n node = node.parentNode;\n }\n }\n}\n\nwalkDOM(document.body, function (node) {\n console.log(node);\n});\n</code></pre>\n\n<p>On <kbd><a href=\"http://jsfiddle.net/Xotic750/8T8WS/\" rel=\"nofollow\">jsfiddle</a></kbd></p>\n\n<p>Finally, here is a <kbd><a href=\"http://jsperf.com/recursive-vs-iterative-dom-walking\" rel=\"nofollow\">jsperf</a></kbd> of the Recursive vs Iterative methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T01:41:02.050",
"Id": "28449",
"ParentId": "28307",
"Score": "2"
}
},
{
"body": "<p>Here is a solution that is about as concise as your recursive solution. (8 lines of code.)</p>\n\n<pre><code> function walkDOM2(n) {\n var stack = [n];\n while (stack.length > 0) {\n var node = stack.pop();\n console.log(node);\n stack = stack.concat(Array.prototype.slice.call(node.childNodes, 0).reverse());\n }\n }\n</code></pre>\n\n<p>Some notes on the above:</p>\n\n<ul>\n<li>After you pop an item off the end of the stack, you replace it with it's children.</li>\n<li>The children are reversed so that the first child is placed at the end of the stack, so it will be the next node to be popped.</li>\n<li>Use <code>Array.prototype.slice.call()</code> to turn the <code>childNodes</code> NodeList into an Array so it can be added to the stack with <code>concat</code>.</li>\n<li>There is no <code>hasChildNodes()</code> check, but sometimes there will be no child nodes and an empty array will be added to the stack.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-24T00:26:39.673",
"Id": "179201",
"Score": "2",
"body": "Can you explain why your alternative version is better than the original version?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-24T01:35:17.570",
"Id": "179216",
"Score": "1",
"body": "Ooh, *clever*. I hadn't thought of this as a DFS problem. You deserve more upvotes!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-24T01:42:01.877",
"Id": "179219",
"Score": "0",
"body": "I do wonder if it's possible to do the append-all-reversed in a better way. I'm not nearly familiar enough with javascript to know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-25T01:00:47.353",
"Id": "179417",
"Score": "0",
"body": "@Hosch250 which original version are you referring to? The one with recursion? The original poster was asking for a concise solution without recursion: that's what I was going for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-25T01:09:19.303",
"Id": "179418",
"Score": "0",
"body": "@o11c I don't know about a better way, but some may find this easier to read: `for (var i = node.childNodes.length-1; i >= 0; i--) { stack.push(node.childNodes[i]); }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-16T16:35:08.317",
"Id": "333491",
"Score": "0",
"body": "Very nice... please see my slight variation on this theme, in which you can get the depth of each node as you iterate..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-17T10:51:08.630",
"Id": "333555",
"Score": "0",
"body": "PPS also there is a slicker way to do the reversing and adding of the child nodes in ES6: `stack.push( ... Array.from( node.childNodes ).reverse() );` - no reassignment of `stack`, so `stack` can be `const`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-24T00:13:50.930",
"Id": "97886",
"ParentId": "28307",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T20:38:31.160",
"Id": "28307",
"Score": "12",
"Tags": [
"javascript",
"recursion",
"dom",
"iteration"
],
"Title": "Implementing an algorithm that walks the DOM without recursion"
}
|
28307
|
<p>I started learning JavaScript a week ago, and I made a sorting function on my own. It does work, but I need reviews and how to write a better one.</p>
<pre><code><body>
<ul id="list">
<li>Art</li>
<li>Mobile</li>
<li>Education</li>
<li>Games</li>
<li>Magazines</li>
<li>Sports</li>
</ul>
var list = document.getElementById("list");
var myList = list.getElementsByTagName("li");
var a = [];
for (var i = 0; i < myList.length; i++) {
a[i] = myList[i].innerHTML;
}
a.sort();
for (var i = 0; i < myList.length; i++) {
myList[i].innerHTML = a[i];
}
</code></pre>
<p>Output:</p>
<blockquote>
<ul>
<li>Art</li>
<li>Education</li>
<li>Games</li>
<li>Magazines</li>
<li>Mobile</li>
<li>Sports</li>
</ul>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T01:52:28.010",
"Id": "44335",
"Score": "0",
"body": "What is your purpose for this? What would constitute a \"better\" sorting function? As I see it, it seems to accomplish the purpose fairly nicely..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T08:33:28.227",
"Id": "44349",
"Score": "0",
"body": "A better one would be not to recreate the DOM elements after sorting. Wouldn't it be better to directly sort the list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T10:55:16.417",
"Id": "44356",
"Score": "0",
"body": "You're not recreating DOM elements though... Your changing the innerHTML of existing DOM elements..."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><code>var myList</code>: Don't use generic names like <code>myList</code>. My list of what? Variable names are very important, they should inform about the nature of their content, not their type (although it's indeed important to use singular variable names for single elements and plurals for collections).</li>\n<li><code>var myList = list.getElementsByTagName(\"li\");</code>. What if <code>list</code> is <code>null</code>? no checks?</li>\n<li><code>myList[i].innerHTML = a[i];</code>. You are overwriting HTML contents, it would probably be better to move DOM elements instead.</li>\n</ul>\n\n<p>I'll leave a pure Javascript re-write to others, if you are interested in solutions that use external libraries, using jQuery and underscore I'd write:</p>\n\n<pre><code>var sorted_lis = _.sortBy($(\"#list li\"), function(li) { return li.innerText; });\n$(\"#list\").empty().append(sorted_lis);\n</code></pre>\n\n<p>The original ten lines reduced to two (one actually, but it's good to break things a bit and give names to intermediate values), thanks to functional style (underscore) and easy DOM manipulation (jQuery).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:26:40.963",
"Id": "44585",
"Score": "0",
"body": "Ten lines reduced to `2 + all the jquery + all the underscore code = god knows how many more`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:32:58.793",
"Id": "44586",
"Score": "0",
"body": "@JonnySooter: Well, we agree that using underscore/jQuery or any other external library if all we want to do is sort some tags makes no sense. But it's usually the case that you're doing some other things and including them pays off on the long run. Also, you can count the whole sum of lines to see, I don't know, the load size of the page, but not when considering code complexity (the one, most important factor in programming). We don't care if those libraries require 100 or 100K lines to work, we are worried about the complexity of the code *we* have to maintain. Here, that's 2 lines :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T12:19:43.287",
"Id": "28323",
"ParentId": "28310",
"Score": "1"
}
},
{
"body": "<p>Unfortunately a list of html nodes (NodeList) in Javascript does not have a <code>sort</code> method, otherwise you could apply that directly. However, if you transform it into an array, you can sort it easily by content and then append it back to the list. On balance I'm not sure this is really better than your original solution though!</p>\n\n<pre><code>var myListParent = document.getElementById('list');\n myListChildren = myListParent.children,\n myListArray = [];\nfor (var i = 0; i < myListChildren.length; i++) {\n myListArray.push(myListChildren[i]);\n}\nfunction sortByInnerHTML(a, b) {\n var h1 = a.innerHTML,\n h2 = b.innerHTML;\n if (h1 == h2) return 0;\n else if (h1 < h2) return -1;\n else return 1;\n}\n\nmyListArray.sort(sortByInnerHTML);\n\nfor (var i = 0; i < myListArray.length; i++) {\n myListParent.appendChild(myListArray[i]);\n}\n</code></pre>\n\n<p>(<a href=\"http://jsfiddle.net/pPCCV/\" rel=\"nofollow\">jsfiddle</a>)</p>\n\n<p>However, to make your code neater and more reusable you could create some functions here.</p>\n\n<pre><code>function sortHTML(parent) {\n var a = [], children = parent.children;\n for (var i = 0; i < children.length; i++) {\n a.push(children[i]);\n }\n a.sort(sortBy('innerHTML'));\n for (var i = 0; i < a.length; i++) {\n parent.appendChild(a[i]);\n }\n}\n\nfunction sortBy(p) {\n return function(a, b) {\n return a[p] < b[p] ? -1 : a[p] > b[p];\n }\n}\n\nsortHTML(document.getElementById('list'));\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/DL7Xa/2/\" rel=\"nofollow\">http://jsfiddle.net/DL7Xa/2/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T19:27:04.827",
"Id": "28342",
"ParentId": "28310",
"Score": "0"
}
},
{
"body": "<p>There are a few things you might want to consider.</p>\n\n<ol>\n<li>The way you are sorting, the nodes stay in the same place, but the content changes. However, what if each node had DOM events attached to them?</li>\n<li>Any time you change content, you may cause page reflow events. This can be avoided, well, not entirely, but it can be done all at once using a Document Fragment: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment</a></li>\n</ol>\n\n<p>Combining the two, here's an idea for a sorter: <a href=\"http://jsfiddle.net/jfcox/647YA/\" rel=\"nofollow\">http://jsfiddle.net/jfcox/647YA/</a></p>\n\n<p>If you are concerned about IE8 support, you apparently cannot use <code>children</code>, you'd have to use childNodes and only add the elements (skipping text nodes, etc.).</p>\n\n<p>Edit: It turns out that in sorting, because the elements to be sorted are already in the DOM tree, reflow still occurs (as the elements are removed and placed into the documentFragment). To remedy, I've modified it to move the parentElement to the documentFragment, move the elements within the fragment, and then move the parent back to the DOM. It's quite a bit faster: <a href=\"http://jsfiddle.net/jfcox/HPxZz/\" rel=\"nofollow\">http://jsfiddle.net/jfcox/HPxZz/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T02:06:43.000",
"Id": "28395",
"ParentId": "28310",
"Score": "0"
}
},
{
"body": "<p>I would probably do it something like this, by moving the original <a href=\"/questions/tagged/dom\" class=\"post-tag\" title=\"show questions tagged 'dom'\" rel=\"tag\">dom</a> elements, using some generic functions that can be reused and that are cross-browser (should work IE5+).</p>\n\n<p>Javascript</p>\n\n<pre><code>function getText(node, text) {\n if (typeof text !== \"string\") {\n text = \"\";\n }\n\n if (node.nodeType === 3) {\n text += node.nodeValue;\n }\n\n node = node.firstChild;\n while (node) {\n text += getText(node, text);\n node = node.nextSibling;\n }\n\n return text;\n}\n\nfunction emptyNode(node) {\n while (node.firstChild) {\n node.removeChild(node.firstChild);\n }\n}\n\nfunction sortByTextFn(a, b) {\n var textA = getText(a),\n textB = getText(b);\n\n if (textA === textB) {\n return 0;\n }\n\n if (textA < textB) {\n return -1;\n }\n\n return 1;\n}\n\nfunction sortHTMLList(element) {\n if (typeof element === \"string\") {\n element = document.getElementById(element);\n }\n\n var lis = element.getElementsByTagName(\"li\"),\n length = lis.length,\n array = [];\n i = 0;\n\n while (i < length) {\n array.push(lis[i]);\n i += 1;\n }\n\n array.sort(sortByTextFn);\n emptyNode(element);\n while (array.length) {\n element.appendChild(array.shift());\n }\n}\n\nsortHTMLList(\"list\");\n</code></pre>\n\n<p>On <kbd><a href=\"http://jsfiddle.net/Xotic750/XHEDe/\" rel=\"nofollow\">jsfiddle</a></kbd></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T23:10:58.220",
"Id": "28444",
"ParentId": "28310",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T21:21:03.977",
"Id": "28310",
"Score": "4",
"Tags": [
"javascript",
"sorting",
"dom"
],
"Title": "My first javascript sorting"
}
|
28310
|
<pre><code>var timeToWait = TimeSpan.FromSeconds(20);
var interval = TimeSpan.FromMinutes(5);
var t = new Timer(s =>
{
tracker.ProcessAuditLogs();
}, null, timeToWait, interval);
</code></pre>
<p>I'm looking to run a timer or an indefinite period of time, as long as my program/service is running. Will the above work in a production environment?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T08:25:52.570",
"Id": "44348",
"Score": "1",
"body": "Could you give us a bit more context? What are your concerns about this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T23:51:36.957",
"Id": "44893",
"Score": "0",
"body": "Would you please add some representative conditions that might make it fail in a production environment? Are you worried, for example, that the new GC algorithms for servers might cause an inadvertent collection of your timer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T02:22:49.723",
"Id": "44896",
"Score": "0",
"body": "Yes! that is my concern. I didn't know how to word it previously"
}
] |
[
{
"body": "<p>I converted my timer loops to Reactive Extensions a while back to avoid the memory leaks created by event subscriptions and event handlers. A snippet doing the same thing as yours is...</p>\n\n<pre><code> var timer = Observable\n .Timer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3))\n .Subscribe(q =>\n { // this executes every 3 seconds in a detached loop \n Console.WriteLine(\"do something here \" + q);\n });\n // other work goes here\n GC.KeepAlive(timer);\n</code></pre>\n\n<p>Of interest here is the last line. This tells the GC that the object should not be garbage collected until it is reached. You can use the same strategy for your event driven timer.</p>\n\n<p>If you wanted a fascinating glimpse into the new garbage collector introduced in 4.5, Maoni Stephens (the lady who actually wrote the GC) made a video that's a 'must see'... <a href=\"http://channel9.msdn.com/posts/Maoni-Stephens-CLR-45-Server-Background-GC\" rel=\"nofollow\">http://channel9.msdn.com/posts/Maoni-Stephens-CLR-45-Server-Background-GC</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T10:40:57.847",
"Id": "44980",
"Score": "1",
"body": "I doubt very much that `GC.KeepAlive` works here. It only keeps the target in memory until it is reached, but it doesn't keep it alive after that. So it seems useless here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T12:50:25.473",
"Id": "44986",
"Score": "0",
"body": "Good point. I amended the code fragment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T13:23:46.380",
"Id": "44989",
"Score": "0",
"body": "@GarryVass: I think the problem is more in your description (\"object should not be garbage collected even if it goes out of scope\"). It would be better to say the object won't be garbage collected until `GC.KeepAlive(timer)` is reached."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T13:42:42.080",
"Id": "44990",
"Score": "0",
"body": "@Brian, thanks again. It's the problem with downsizing code to relevant snippets for pasting. And yes, in implementation, the whole thing should be (and presumably would be) wrapped."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T23:07:27.793",
"Id": "28620",
"ParentId": "28314",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28620",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T04:31:40.063",
"Id": "28314",
"Score": "1",
"Tags": [
"c#",
".net",
"timer"
],
"Title": "Rewriting timers in .NET with lambda"
}
|
28314
|
<p>This function code works very slowly. How can I speed it up?</p>
<pre><code>CREATE OR REPLACE FUNCTION bill."ReportIngredients"(
_from date,
_to date,
_beginning_date date,
_has_inventory boolean,
_inventory_id uuid,
_restaurant_id uuid,
_stock_id uuid,
_ingredientIds uuid [],
_sort_by character varying,
_limit integer,
_offset integer
)
RETURNS TABLE(
json json
) AS
$BODY$
declare
ingredientFilter character varying = '';
ingredient_id uuid;
ss_date date;
begin
if ( _ingredientIds is not null ) then
ingredientFilter = 'and i.id IN (';
FOREACH ingredient_id in array _ingredientIds loop
ingredientFilter := ingredientFilter || '''' || ingredient_id || ''',';
end loop;
Select trim(trailing ',' from ingredientFilter) into ingredientFilter;
ingredientFilter := ingredientFilter || ') ';
end if;
if ( _has_inventory ) then
return query execute
'select array_to_json(array_agg(row_to_json(t)))
From (
Select i.id, i.title,
(
(
SELECT coalesce(sum(ii.delta_count), 0)
FROM inventory_ingredients ii
Inner Join inventories inven On inven.id = ii.inventory_id
WHERE ii.ingredient_id = i.id
And inven.is_active = true
And inven.stock_id = ''' || _stock_id || '''
And inven.id = ''' || _inventory_id || '''
) + (
SELECT coalesce(sum(ii.count), 0)
FROM invoice_ingredients ii
Inner Join invoices invo On invo.id = ii.invoice_id
WHERE ii.is_active = true
And ii.ingredient_id = i.id
And invo.is_active = true
And invo.restaurant_id = ''' || _restaurant_id || '''
And invo.receiver_id = ''' || _stock_id || '''
And invo.date >= ''' || _beginning_date || '''
And invo.date < ''' || _from || '''
) + (
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.receiver_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _beginning_date || '''
And r.date < ''' || _from || '''
) - (
SELECT coalesce(sum(wi.count), 0)
FROM write_off_ingredients wi
Inner Join write_offs w On w.id = wi.write_off_id
WHERE wi.ingredient_id = i.id
And w.is_active = true
And w.stock_id = ''' || _stock_id || '''
And w.date >= ''' || _beginning_date || '''
And w.date < ''' || _from || '''
) - (
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.sender_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _beginning_date || '''
And r.date < ''' || _from || '''
) - (
Select ((
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _beginning_date || '''
And bc.date < ''' || _from || '''
And bc.calculate_type = ''subtract''
And b.bill_type <> 5
) - (
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id
Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _beginning_date || '''
And bc.date < ''' || _from || '''
And bc.calculate_type = ''add''
And b.bill_type <> 5
)) AS sum
)
) AS start_count,
(
SELECT coalesce(sum(ii.count), 0)
FROM invoice_ingredients ii
Inner Join invoices invo On invo.id = ii.invoice_id
WHERE ii.is_active = true
And ii.ingredient_id = i.id
And invo.is_active = true
And invo.restaurant_id = ''' || _restaurant_id || '''
And invo.receiver_id = ''' || _stock_id || '''
And invo.date >= ''' || _from || '''
And invo.date <= ''' || _to || '''
) AS invoice_count,
(
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.receiver_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _from || '''
And r.date <= ''' || _to || '''
) AS relocation_in_count,
(
SELECT coalesce(sum(wi.count), 0)
FROM write_off_ingredients wi
Inner Join write_offs w On w.id = wi.write_off_id
WHERE wi.ingredient_id = i.id
And w.is_active = true
And w.stock_id = ''' || _stock_id || '''
And w.date >= ''' || _from || '''
And w.date <= ''' || _to || '''
) AS write_off_count,
(
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.sender_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _from || '''
And r.date <= ''' || _to || '''
) AS relocation_out_count,
(
Select ((
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _from || '''
And bc.date <= ''' || _to || '''
And bc.calculate_type = ''subtract''
And b.bill_type <> 5
) - (
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id
Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _from || '''
And bc.date <= ''' || _to || '''
And bc.calculate_type = ''add''
And b.bill_type <> 5
)) AS sum
) AS solds_count,
(
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id
Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _from || '''
And bc.date <= ''' || _to || '''
And bc.calculate_type = ''add''
And b.bill_type <> 5
) AS resign_count
From ingredients i
Where i.is_active = true
And i.restaurant_id = ''' || _restaurant_id || '''
' || ingredientFilter || '
Group by i.id
order by ' || _sort_by || '
limit ' || _limit || '
offset ' || _offset || '
) t';
else
return query execute
'select array_to_json(array_agg(row_to_json(t)))
From (
Select i.id, i.title,
(
(
SELECT coalesce(sum(ii.count), 0)
FROM invoice_ingredients ii
Inner Join invoices invo On invo.id = ii.invoice_id
WHERE ii.is_active = true
And ii.ingredient_id = i.id
And invo.is_active = true
And invo.restaurant_id = ''' || _restaurant_id || '''
And invo.receiver_id = ''' || _stock_id || '''
And invo.date >= ''' || _beginning_date || '''
And invo.date < ''' || _from || '''
) + (
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.receiver_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _beginning_date || '''
And r.date < ''' || _from || '''
) - (
SELECT coalesce(sum(wi.count), 0)
FROM write_off_ingredients wi
Inner Join write_offs w On w.id = wi.write_off_id
WHERE wi.ingredient_id = i.id
And w.is_active = true
And w.stock_id = ''' || _stock_id || '''
And w.date >= ''' || _beginning_date || '''
And w.date < ''' || _from || '''
) - (
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.sender_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _beginning_date || '''
And r.date < ''' || _from || '''
) - (
Select ((
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _beginning_date || '''
And bc.date < ''' || _from || '''
And bc.calculate_type = ''subtract''
And b.bill_type <> 5
) - (
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id
Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _beginning_date || '''
And bc.date < ''' || _from || '''
And bc.calculate_type = ''add''
And b.bill_type <> 5
)) AS sum
)
) AS start_count,
(
SELECT coalesce(sum(ii.count), 0)
FROM invoice_ingredients ii
Inner Join invoices invo On invo.id = ii.invoice_id
WHERE ii.is_active = true
And ii.ingredient_id = i.id
And invo.is_active = true
And invo.restaurant_id = ''' || _restaurant_id || '''
And invo.receiver_id = ''' || _stock_id || '''
And invo.date >= ''' || _from || '''
And invo.date <= ''' || _to || '''
) AS invoice_count,
(
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.receiver_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _from || '''
And r.date <= ''' || _to || '''
) AS relocation_in_count,
(
SELECT coalesce(sum(wi.count), 0)
FROM write_off_ingredients wi
Inner Join write_offs w On w.id = wi.write_off_id
WHERE wi.ingredient_id = i.id
And w.is_active = true
And w.stock_id = ''' || _stock_id || '''
And w.date >= ''' || _from || '''
And w.date <= ''' || _to || '''
) AS write_off_count,
(
SELECT coalesce(sum(ri.count), 0)
FROM relocation_ingredients ri
Inner Join relocations r On r.id = ri.relocation_id
WHERE ri.ingredient_id = i.id
And r.is_active = true
And r.restaurant_id = ''' || _restaurant_id || '''
And r.sender_stock_id = ''' || _stock_id || '''
And r.date >= ''' || _from || '''
And r.date <= ''' || _to || '''
) AS relocation_out_count,
(
Select ((
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _from || '''
And bc.date <= ''' || _to || '''
And bc.calculate_type = ''subtract''
And b.bill_type <> 5
) - (
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id
Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _from || '''
And bc.date <= ''' || _to || '''
And bc.calculate_type = ''add''
And b.bill_type <> 5
)) AS sum
) AS solds_count,
(
SELECT coalesce(sum(bc.count), 0)
FROM bill_calculations bc
Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id
Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id
Inner Join bill.bills b on b.id = bcs.bill_id
WHERE bc.ingredient_id = i.id
And bc.stock_id = ''' || _stock_id || '''
And bc.date >= ''' || _from || '''
And bc.date <= ''' || _to || '''
And bc.calculate_type = ''add''
And b.bill_type <> 5
) AS resign_count
From ingredients i
Where i.is_active = true
And i.restaurant_id = ''' || _restaurant_id || '''
' || ingredientFilter || '
Group by i.id
order by ' || _sort_by || '
limit ' || _limit || '
offset ' || _offset || '
) t';
end if;
end;
$BODY$
LANGUAGE plpgsql STABLE
COST 50
ROWS 1000;
ALTER FUNCTION bill."ReportIngredients"(date, date, date, boolean, uuid, uuid, uuid, uuid[], character varying, integer, integer)
OWNER TO developer;
</code></pre>
<p>EXPLAIN ANALYZE result</p>
<blockquote>
<p>"Result (cost=0.00..5.13 rows=1000 width=0) (actual time=38859.253..38859.254 rows=1 loops=1)"
"Total runtime: 38859.296 ms"</p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:27:53.627",
"Id": "57437",
"Score": "0",
"body": "you have a lot of Nested Select Statements with multiple where statements, is there any way to reduce the Nested select statements? like Temp Tables, Table Variables, joins, etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T05:21:44.573",
"Id": "88535",
"Score": "1",
"body": "Ditto @Malachi; Temp tables or views may improve performance significantly, instead of nested `SELECT` statements. 39K ms seems excessive."
}
] |
[
{
"body": "<p>I will give you kudos on being very explicit in your programming. Here are my thoughts:</p>\n\n<ol>\n<li><p>Not performance related but still a factor, I would suggest that you remain consistent with your casing of key words. Sure SQL is not case-sensitive, but it makes the code easier to read especially in my opinion if SQL key words are all caps. </p></li>\n<li><p>Again likely not performance related, but I notice you reuse table aliases in multiple subqueries for different tables (e.g., <code>ii</code> for<code>inventory_ingredients</code> and <code>invoice_ingredients</code> both) this is not good practice as if you omitted a single parentheses you could get an unpredictable result set or an error from SQL that your table reference is ambiguous. These can be tricky to debug especially in a large script like this. </p></li>\n<li><p>Nested <code>SELECT</code> subqueries, avoid if possible especially for long-running scripts, as it can lock those pages/tables for other users throughout execution. I suggested breaking those into common table expressions or temporary tables (if infrequent execution) or views (if frequent). Not completely familiar with the PostgreSQL syntax for those but same principles apply to all SQL. Note, this would also make your function query much simpler to read while you do your arithmetic calculations.</p></li>\n<li><p>You can try to change the <code>COST 50</code> to a different value. See section labeled <code>execution_cost</code> <a href=\"http://www.postgresql.org/docs/8.4/interactive/sql-createfunction.html\">in this section of the manual</a> for more details on how it works. </p></li>\n<li><p>You use this type of operator throughout: <code>inven.stock_id = ''' || _stock_id || '''</code>. This is ugly, why do you concatenate empty values instead of just <code>inven.stock_id LIKE '%_stock_id%'</code>? SQL engine might interpret this weirdly and may optimize better if you use the <code>LIKE</code> operator.</p></li>\n<li><p>Using comments within your script would help the next programmer understand your code better as to what it does in what order, etc.</p></li>\n</ol>\n\n<p>I can't think of anything else but others are welcome to add/edit to this if warranted. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T17:14:05.103",
"Id": "51557",
"ParentId": "28315",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T04:44:25.747",
"Id": "28315",
"Score": "5",
"Tags": [
"optimization",
"sql",
"postgresql"
],
"Title": "Optimize postgres function"
}
|
28315
|
<p>I am currently learning JavaScript and created this cross-browser event utility as a learning exercise. It was not meant to be used in production code, and I just tried to cover only the cases that I'm aware of, so there might be a lot of edge cases that are not covered. </p>
<p>I'd be happy if you could check it and let me know how it looks and give me suggestions on how to improve it:</p>
<pre><code>var helpers = {
getOldEventName: function(eventName) {
if (eventName.lastIndexOf('on', 0) !== 0) {
return 'on' + eventName;
}
return eventName;
},
getModernEventName: function(eventName) {
if (eventName.lastIndexOf('on', 0) !== -1) {
return eventName.substring(2);
}
return eventName;
},
isCollection: function(variable) {
return variable instanceof Array || variable instanceof HTMLCollection || variable instanceof NodeList;
}
}
var myEvent = {
addListener: function(element, eventName, callback) {
var elements = element;
if (!helpers.isCollection(element))
elements = [element];
for (var i = 0; i < elements.length; i++) {
if (elements[i].addEventListener) {
elements[i].addEventListener(helpers.getModernEventName(eventName), callback, false);
} else if (element.attachEvent) {
elements[i].attachEvent(helpers.getOldEventName(eventName), callback);
} else {
elements[i][helpers.getOldEventName(eventName)] = callback;
}
}
},
removeListener: function(element, eventName, callback) {
var elements = element;
if (!helpers.isCollection(element))
elements = [element];
for (var i = 0; i < elements.length; i++) {
if (elements[i].removeEventListener) {
elements[i].removeEventListener(helpers.getModernEventName(eventName), callback, false);
} else if (elements[i].detachEvent) {
elements[i].detachEvent(helpers.getOldEventName(eventName), callback);
} else {
elements[i][helpers.getOldEventName(eventName)] = null;
}
}
},
getEvent: function(event) {
return event || window.event;
},
getTarget: function(event) {
return (typeof event.target !== 'undefined') ? event.target : event.srcElement;
},
stopPropagation: function(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (typeof event.cancelBubble !== 'undefined') {
event.cancelBubble = true;
}
},
preventDefault: function(event) {
if (event.preventDefault) {
event.preventDefault();
} else if (typeof event.returnValue !== 'undefined') {
event.returnValue = false;
}
}
}
</code></pre>
<p>Usage examples:</p>
<pre><code>function myCallback(e) {
e = myEvent.getEvent(e);
alert(myEvent.getTarget(e).href);
myEvent.stopPropagation(e);
myEvent.preventDefault(e);
}
myEvent.addListener(document.links, 'click', myCallback);
function dynamicDivHandler(e) {
e = myEvent.getEvent(e);
var keyCode = e.keyCode;
var node = document.getElementById('dynamicDiv');
switch (keyCode) {
case 37:
node.style.left = (parseInt(node.style.left) - 5) + 'px';
break;
case 38:
node.style.top = (parseInt(node.style.top) - 5) + 'px';
break;
case 39:
node.style.left = (parseInt(node.style.left) + 5) + 'px';
break;
case 40:
node.style.top = (parseInt(node.style.top) + 5) + 'px';
break;
}
}
myEvent.addListener(document, 'keydown', dynamicDivHandler);
</code></pre>
<p>P.S.: This exercise is from the book "Object-Oriented JavaScript" by Stoyan Stefanov.</p>
|
[] |
[
{
"body": "<p>Your code looks ok. Nothing really jumps out at me except these two things:</p>\n\n<ol>\n<li><p>Event handlers attached via <code>attachEvent</code> are executed in random order (Source: <a href=\"http://msdn.microsoft.com/en-us/library/ie/ms536343%28v=vs.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ie/ms536343%28v=vs.85%29.aspx</a>). You might want to create a shim to get older versions of Internet Explorer to execute event handlers in the order they were attached, which is something I believe jQuery does (or did).</p></li>\n<li><p>Create a function that patches the <code>event</code> object for cross browser compatibility, so your event handlers do not have to constantly call <code>myEvent.getEvent(e)</code>. This will prevent repeated code in your handlers.</p></li>\n</ol>\n\n<p>You could create separate functions to attach events in the three different ways, and use feature detection to determine which one to use:</p>\n\n<pre><code>var myEvent = {\n init: function() {\n if (document.addEventListener) {\n this.addListener = this.addListenerStandard;\n this.removeListener = this.removeListenerStandard;\n }\n else if (document.attachEvent) {\n this.addListener = this.addListenerMSIE;\n this.removeListener = this.removeListenerMSIE;\n }\n else {\n this.addListener = this.addListenerOldSkool;\n this.removeListener = this.removeListenerOldSkool;\n }\n },\n\n listen: function(elements, event, handler) {\n elements = !helpers.isCollection(elements) ? [elements] : elements;\n\n for (var i = 0; i < elements.length; i++) {\n this.addListener(elements[i], event, handler);\n }\n },\n\n stopListening: function(elements, event, handler) {\n elements = !helpers.isCollection(elements) ? [elements] : elements;\n\n for (var i = 0; i < elements.length; i++) {\n this.removeListener(elements[i], event, handler);\n }\n },\n\n addListenerStandard: function(element, event, handler) {\n element.addEventListener(event, handler, false);\n },\n\n addListenerMSIE: function(element, event, handler) {\n element.attachEvent(\"on\" + event, handler);\n },\n\n addListenerOldSkool: function(element, event, handler) {\n element[\"on\" + event] = handler;\n },\n\n removeListenerStandard: function(...) { ... },\n\n removeListenerMSIE: function (...) { ... },\n\n addListenerOldSkool: function(...) { ... },\n\n addListener: null,\n\n removeListener: null\n};\n\nmyEvent.init();\n</code></pre>\n\n<p>That way you won't be detecting the proper DOM method on each iteration of your loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T17:09:03.470",
"Id": "48073",
"ParentId": "28320",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T10:56:16.600",
"Id": "28320",
"Score": "1",
"Tags": [
"javascript",
"cross-browser"
],
"Title": "Implementing a cross-browser event utility as an exercise"
}
|
28320
|
<p>In my ASP.NET MVC code, I like to use controller service classes for my controllers. These service classes contain methods for retrieving viewmodel objects.</p>
<p>Here is an example controller snippet:</p>
<pre><code>public SubscriptionsController(ISubscriptionsControllerService service)
{
_service = service;
}
public ActionResult Index(Guid id)
{
return View("Subscriptions", _service.GetSubscriptionsViewModelOnGet(id));
}
[HttpPost]
public ActionResult Index(SubscriptionsViewModel viewModel)
{
_service.SaveSubscriptions(viewModel);
return View("Subscriptions", _service.GetSubscriptionsViewModelOnPost(viewModel));
}
</code></pre>
<p>As you can see, I have a method for retrieving the subscriptions viewmodel on a GET request, as well as the equivalent for a POST request.</p>
<p>The POST method takes in an existing viewmodel object and updates any relevant data e.g. a list of subscription items, that need to be refreshed before passing back to the view.</p>
<p>My question is whether the naming of the methods (<code>GetSubscriptionsViewModelOnGet()</code> and <code>GetSubscriptionsViewModelOnPost()</code>) makes sense. They seem OK to me, but I'm interested in other people's views.</p>
|
[] |
[
{
"body": "<p>Why not name them both the same? The difference is the type of parameter you're passing. This leaves you free to do some method overloading:</p>\n\n<pre><code>public SubscriptionsViewModel GetSubscriptionsViewModel(Guid id)\n{\n //GET Logic here...\n}\n\npublic SubscriptionsViewModel GetSubscriptionsViewModel(SubscriptionsViewModel viewModel)\n{\n //POST Logic here...\n}\n</code></pre>\n\n<p>Why call them the same? They both <em>do</em> the same: return a <code>SubscriptionsViewModel</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T15:10:27.210",
"Id": "44364",
"Score": "0",
"body": "Yeah, I was thinking the same thing this morning, just before I posted this question. I think it does not matter about the context of when the code is getting the viewmodel e.g. GET/POST. I can make the method names easier i.e. the same."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T14:52:28.260",
"Id": "28331",
"ParentId": "28324",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28331",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T12:38:03.420",
"Id": "28324",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Returning a viewmodel"
}
|
28324
|
<p>I am currently learning JavaScript and created this cross-browser AJAX utility as a learning exercise. It was not meant to be used in production code, and I just tried to cover only the cases that I'm aware of, so there might be a lot of edge cases that are not covered.</p>
<p>I'd be happy if you could check it and let me know how it looks and give me suggestions on how to improve it:</p>
<pre><code>var ajax = {
request: function(url, requestType, callback, queryString) {
var ids = ['MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'],
xhr;
if (typeof window.XMLHttpRequest === 'function') {
xhr = new XMLHttpRequest();
} else { // For IE versions below 7
for (var i = 0; i < ids.length; i++) {
try {
xhr = new ActiveXObject(ids[i]);
break;
} catch(e) {}
}
}
// Do I really need to put the callback in a
// closure, as the xhr object gets recreated
// each time ajax.request() is called?
xhr.onreadystatechange = (function(myXhr) {
return function() {
callback(myXhr);
};
})(xhr);
xhr.open(requestType, url, true);
if (requestType.toUpperCase() === 'GET') {
xhr.send('');
} else if (requestType.toUpperCase() === 'POST') {
xhr.send(queryString);
}
}
}
</code></pre>
<p>P.S.: This exercise is from the book "Object-Oriented JavaScript" by Stoyan Stefanov.</p>
|
[] |
[
{
"body": "<p>I can't specifically comment on your usage of the extra tries for < IE7, as I always make sure my audience is using something better. It seems like there should be a more elegant way to check each of those than a try with an empty catch, but without knowing how IE treats them, I can't say what it would be. The rest is okay, but I would suggest the following. My changes are explained in my own comments.</p>\n\n<pre><code>var ajax = {\n request: function(url, requestType, callback, queryString) {\n var ids = ['MSXML2.XMLHTTP.3.0',\n 'MSXML2.XMLHTTP',\n 'Microsoft.XMLHTTP'],\n xhr;\n\n // Simplification of this check while essentially doing the same thing\n if (window.XMLHttpRequest) {\n xhr = new XMLHttpRequest();\n } else {\n for (var i = 0; i < ids.length; i++) {\n try {\n xhr = new ActiveXObject(ids[i]);\n break;\n } catch(e) {}\n }\n }\n // Calling a function to return a function is redundant.\n // Do what you're trying to with as little extra as possible.\n xhr.onreadystatechange = function() {\n callback(xhr);\n };\n xhr.open(requestType, url, true);\n if (requestType.toUpperCase() === 'GET') {\n // When initiating a get request, the send function needs no arguments at all.\n xhr.send();\n } else if (requestType.toUpperCase() === 'POST') {\n xhr.send(queryString);\n }\n // If you want to be extra careful, include an else here to handle a bad requestType\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:23:52.740",
"Id": "28376",
"ParentId": "28325",
"Score": "3"
}
},
{
"body": "<p><strong>Another idea to extend the callback function</strong></p>\n\n<p>Sometimes it never reaches state 4 (finished), for example in temporary connection loss... in that case you will need to send request again... however the previous callback may suddenly be called also and you get it twice.</p>\n\n<pre><code>x.onreadystatechange = function() {\n if(x.readyState== 4){\n if(x.status==200){\n callbackFunction(x.responseText);\n } else {\n // request error\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-16T19:33:24.630",
"Id": "115212",
"Score": "0",
"body": "I know this isn't terrifically related, but all 20x responses are success, not just 200"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T09:41:01.353",
"Id": "36343",
"ParentId": "28325",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28376",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T12:41:53.373",
"Id": "28325",
"Score": "3",
"Tags": [
"javascript",
"ajax"
],
"Title": "Implementing a cross-browser AJAX utility as an exercise"
}
|
28325
|
<p>This code fetches reviews for the top 100 products on NutraPlanet, finds the Bayesian estimate for each average review, then prints out all reviews sorted by that Bayesian estimate.</p>
<p>How can I improve this code (correctness, elegance, best practices, etc)?</p>
<pre><code><?php
// echo "Remove exit from script to run."; exit;
define("MINIMUM_NUMBER_OF_VOTES_TO_SAVE_PRODUCT", 2);
$locations = array("http://www.nutraplanet.com/top_100");
$reviewUrlFragments = array_unique(getReviewUrlFragments($locations));
$products = getProducts(
$reviewUrlFragments,
MINIMUM_NUMBER_OF_VOTES_TO_SAVE_PRODUCT);
calculateBayesianEstimate($products);
usort($products, function ($a, $b) {
if ($a["bayesian_estimate"] == $b["bayesian_estimate"]) {
return 0;
}
return ($a["bayesian_estimate"] < $b["bayesian_estimate"]) ? 1 : -1;
});
printReviews($products);
function getReviewUrlFragments($locations) {
$reviewUrlFragments = array();
foreach($locations as $location) {
$page = @file_get_contents($location);
preg_match_all("%/product/(.*?)\.html%is", $page, $matches);
$reviewUrlFragments = array_merge($reviewUrlFragments, $matches[1]);
}
return $reviewUrlFragments;
}
function getProducts($productReviewUrlFragments, $minimumNumberOfVotesToSaveProduct) {
$products = array();
foreach($productReviewUrlFragments as $productReviewUrlFragment) {
$reviewUrl = "http://www.nutraplanet.com/manufacturer/" . $productReviewUrlFragment . "/reviews";
$page = @file_get_contents($reviewUrl);
preg_match_all("%<td>&nbsp;<i>(.*?)</i></td>%is", $page, $matches);
$product = array();
$product['name'] = "http://www.nutraplanet.com/product/".$productReviewUrlFragment.".html";
$votes = getVotes($matches[1]);
$product["vote_distribution"] = $votes["votes"];
$product["review_average"] = $votes["average"];
$product["num_votes"] = $votes["num_votes"];
// Only add if there is a vote for the product
if ($product["num_votes"] >= $minimumNumberOfVotesToSaveProduct) {
$products[] = $product;
}
}
return $products;
}
function getVotes($match) {
$votes = array();
$sum_votes = 0;
$total_votes = 0;
$vote_star = 1;
// In ascending order, 1-star to 5
foreach($match as $vote_count) {
$votes[] = $vote_count;
$total_votes += $vote_count;
$sum_votes += ($vote_count * $vote_star++);
}
$product["votes"] = $votes;
$product["average"] = ($total_votes < 1) ? 0 : ($sum_votes / $total_votes);
$product["num_votes"] = $total_votes;
return $product;
}
function calculateBayesianEstimate(&$products) {
// See bottom of page: http://www.imdb.com/chart/top
$m = getMinNumberOfVotes($products);
$C = getAverageReviewAverage($products);
for ($i = 0, $len = count($products); $i < $len; $i++) {
$R = $products[$i]["review_average"];
$v = $products[$i]["num_votes"];
$products[$i]["bayesian_estimate"] = (($v / ($v+$m)) * $R) + (($m / ($v+$m)) * $C);
}
}
function getAverageReviewAverage($products) {
$total = 0;
foreach($products as $product) {
$total += $product["review_average"];
}
return $total / count($products);
}
function getMinNumberOfVotes($products) {
foreach($products as $product) {
if (!isset($minVote) || ($product["num_votes"] < $minVote)) {
$minVote = $product["num_votes"];
}
}
if (!isset($minVote)) {
$minVote = 0;
}
return $minVote;
}
function printReviews($products) {
echo "<table>";
foreach($products as $product) {
$product["vote_distribution"] = implode("</td><td>", $product["vote_distribution"]);
$product = implode("</td><td>", $product);
echo "<tr><td>" . $product . "</td></tr>";
}
echo "<table>";
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T16:02:30.840",
"Id": "44368",
"Score": "0",
"body": "What's up with all the `$`s?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T16:27:01.093",
"Id": "44370",
"Score": "1",
"body": "Ummmm..... OOP?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T16:58:22.603",
"Id": "44373",
"Score": "1",
"body": "How about going the OOP route and also using more descriptive names?"
}
] |
[
{
"body": "<p>I just put this together, so I haven't tested it or anything, there might be bugs and someone else PLEASE come along and improve upon it, but I think this might be a good starting point to answering this question:</p>\n\n<p>OOP version of OP's code:</p>\n\n<p>\n\n<pre><code>$ReviewPrinter = new ReviewPrinter(\"http://www.nutraplanet.com/top_100\", 2);\necho $ReviewPrinter->printReviews();\n\n\n\nclass ReviewPrinter{\n public $products;\n public $locations;\n public $reviewUrlFragments;\n public $minimumNumberOfVotesToSaveProduct;\n\n public function __construct($locations, $minimumNumberOfVotesToSaveProduct){\n if(empty($locations) || empty($minimumNumberOfVotesToSaveProduct)){\n return false;\n } else {\n $this->minimumNumberOfVotesToSaveProduct = $minimumNumberOfVotesToSaveProduct;\n $this->locations = array($locations);\n $this->setReviewUrlFragments();\n $this->products = $this->getProducts();\n $this->calculateBayesianEstimate();\n $this->sortProducts();\n }\n }\n\n public function sortProducts(){\n usort($this->products, function ($a, $b) {\n if ($a[\"bayesian_estimate\"] == $b[\"bayesian_estimate\"]) {\n return 0;\n }\n return (($a[\"bayesian_estimate\"] < $b[\"bayesian_estimate\"]) ? 1 : -1);\n });\n }\n\n public function setReviewUrlFragments(){\n $localReviewUrlFragments = array();\n\n foreach($this->locations as $location) {\n preg_match_all(\"%/product/(.*?)\\.html%is\", @file_get_contents($location), $matches);\n $localReviewUrlFragments = array_merge($localReviewUrlFragments, $matches[1]);\n }\n\n $this->reviewUrlFragments = array_unique($localReviewUrlFragments);\n }\n\n public function getProducts(){\n $functionScopeProducts = array();\n\n foreach($this->reviewUrlFragments as $productReviewUrlFragment) {\n $reviewUrl = \"http://www.nutraplanet.com/manufacturer/\" . $productReviewUrlFragment . \"/reviews\";\n\n preg_match_all(\"%<td>&nbsp;<i>(.*?)</i></td>%is\", @file_get_contents($reviewUrl), $matches);\n\n $localProducts = array();\n $localProducts['name'] = \"http://www.nutraplanet.com/product/\".$productReviewUrlFragment.\".html\";\n\n $votes = $this->getVotes($matches[1]); \n\n $localProducts[\"vote_distribution\"] = $votes[\"votes\"];\n $localProducts[\"review_average\"] = $votes[\"average\"];\n $localProducts[\"num_votes\"] = $votes[\"num_votes\"];\n\n // Only add if there is a vote for the product\n if ($localProducts[\"num_votes\"] >= $this->minimumNumberOfVotesToSaveProduct) {\n $functionScopeProducts[] = $localProducts;\n }\n }\n\n return $functionScopeProducts;\n }\n\n public function getVotes($match){\n $votes = array(); \n $sum_votes = 0;\n $total_votes = 0;\n $vote_star = 1;\n\n // In ascending order, 1-star to 5\n foreach($match as $vote_count) {\n $votes[] = $vote_count;\n $total_votes += $vote_count;\n $sum_votes += ($vote_count * $vote_star++);\n }\n\n $product[\"votes\"] = $votes;\n $product[\"average\"] = ($total_votes < 1) ? 0 : ($sum_votes / $total_votes);\n $product[\"num_votes\"] = $total_votes;\n\n return $product;\n }\n\n public function calculateBayesianEstimate(){ \n /**\n * Algorithm used: (WR) = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C \n * where:\n * WR = Weighted rating\n * R = Average rating\n * v = Number of votes\n * m = Minimum votes required \n * C = Mean vote across the whole report\n */\n $m = $this->getMinNumberOfVotes();\n $C = $this->getAverageReviewAverage(); \n\n for ($i = 0, $len = count(&$this->products); $i < $len; $i++) {\n $R = &$this->products[$i][\"review_average\"];\n $v = &$this->products[$i][\"num_votes\"];\n &$this->products[$i][\"bayesian_estimate\"] = (($v / ($v+$m)) * $R) + (($m / ($v+$m)) * $C);\n }\n }\n\n public function getAverageReviewAverage(){\n $total = 0;\n\n foreach($this->products as $product) {\n $total += $product[\"review_average\"];\n }\n\n return $total / count($this->products);\n }\n\n public function getMinNumberOfVotes(){\n # NOTE: Where is $minVote set or created? \n foreach($this->products as $product) {\n if (!isset($minVote) || ($product[\"num_votes\"] < $minVote)) {\n $minVote = $product[\"num_votes\"];\n }\n }\n\n if (!isset($minVote)) {\n $minVote = 0;\n }\n\n return $minVote;\n }\n\n public function printReviews(){\n $output = \"<table>\";\n foreach($this->products as $product) {\n $product[\"vote_distribution\"] = implode(\"</td><td>\", $product[\"vote_distribution\"]);\n $product = implode(\"</td><td>\", $product);\n $output .= \"<tr><td>\" . $product . \"</td></tr>\";\n }\n $output .= \"<table>\";\n\n return $output;\n }\n}\n</code></pre>\n\n<p>Obviously, there should be separation of concerns, which this does not implement, etc. </p>\n\n<p>++++\nEDIT\n++++</p>\n\n<p>Implemented comments </p>\n\n<p>\n\n<pre><code>// Usage:\n$ReviewPrinter = new ReviewPrinter(\"http://www.nutraplanet.com/top_100\", 2);\necho $ReviewPrinter->printReviews();\n\n\n\nclass ReviewPrinter{\n private $products;\n private $locations;\n private $reviewUrlFragments;\n private $minimumNumberOfVotesToSaveProduct;\n\n public function __construct($locations, $minimumNumberOfVotesToSaveProduct){\n if(empty($locations) || empty($minimumNumberOfVotesToSaveProduct)){\n $c = 2 - (empty($locations) ? 1 : 0) - (empty($minimumNumberOfVotesToSaveProduct) ? 1 : 0);\n throw new Exception(\"Construct expects 2 parameters, $c given.\");\n } else {\n $this->minimumNumberOfVotesToSaveProduct = $minimumNumberOfVotesToSaveProduct;\n $this->locations = array($locations);\n $this->setReviewUrlFragments();\n $this->products = $this->getProducts();\n $this->calculateBayesianEstimate();\n $this->sortProducts();\n }\n }\n\n private function sortProducts(){\n usort($this->products, function ($a, $b) {\n if ($a[\"bayesian_estimate\"] == $b[\"bayesian_estimate\"]) {\n return 0;\n }\n return (($a[\"bayesian_estimate\"] < $b[\"bayesian_estimate\"]) ? 1 : -1);\n });\n }\n\n private function setReviewUrlFragments(){\n $localReviewUrlFragments = array();\n\n foreach($this->locations as $location) {\n preg_match_all(\"%/product/(.*?)\\.html%is\", @file_get_contents($location), $matches);\n $localReviewUrlFragments = array_merge($localReviewUrlFragments, $matches[1]);\n }\n\n $this->reviewUrlFragments = array_unique($localReviewUrlFragments);\n }\n\n private function getProducts(){\n $functionScopeProducts = array();\n\n foreach($this->reviewUrlFragments as $productReviewUrlFragment) {\n $reviewUrl = \"http://www.nutraplanet.com/manufacturer/\" . $productReviewUrlFragment . \"/reviews\";\n\n preg_match_all(\"%<td>&nbsp;<i>(.*?)</i></td>%is\", @file_get_contents($reviewUrl), $matches);\n\n $localProducts = array();\n $localProducts['name'] = \"http://www.nutraplanet.com/product/\".$productReviewUrlFragment.\".html\";\n\n $votes = $this->getVotes($matches[1]); \n\n $localProducts[\"vote_distribution\"] = $votes[\"votes\"];\n $localProducts[\"review_average\"] = $votes[\"average\"];\n $localProducts[\"num_votes\"] = $votes[\"num_votes\"];\n\n // Only add if there is a vote for the product\n if ($localProducts[\"num_votes\"] >= $this->minimumNumberOfVotesToSaveProduct) {\n $functionScopeProducts[] = $localProducts;\n }\n }\n\n return $functionScopeProducts;\n }\n\n private function getVotes($match){\n $votes = array(); \n $sum_votes = 0;\n $total_votes = 0;\n $vote_star = 1;\n\n // In ascending order, 1-star to 5\n foreach($match as $vote_count) {\n $votes[] = $vote_count;\n $total_votes += $vote_count;\n $sum_votes += ($vote_count * $vote_star++);\n }\n\n $product[\"votes\"] = $votes;\n $product[\"average\"] = ($total_votes < 1) ? 0 : ($sum_votes / $total_votes);\n $product[\"num_votes\"] = $total_votes;\n\n return $product;\n }\n\n private function calculateBayesianEstimate(){ \n /**\n * Algorithm used: (WR) = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C \n * where:\n * WR = Weighted rating\n * R = Average rating\n * v = Number of votes\n * m = Minimum votes required \n * C = Mean vote across the whole report\n */\n $m = $this->getMinNumberOfVotes();\n $C = $this->getAverageReviewAverage(); \n\n for ($i = 0, $len = count(&$this->products); $i < $len; $i++) {\n $R = &$this->products[$i][\"review_average\"];\n $v = &$this->products[$i][\"num_votes\"];\n &$this->products[$i][\"bayesian_estimate\"] = (($v / ($v+$m)) * $R) + (($m / ($v+$m)) * $C);\n }\n }\n\n private function getAverageReviewAverage(){\n $total = 0;\n\n foreach($this->products as $product) {\n $total += $product[\"review_average\"];\n }\n\n return $total / count($this->products);\n }\n\n private function getMinNumberOfVotes(){\n # NOTE: Where is $minVote set or created? \n foreach($this->products as $product) {\n if (!isset($minVote) || ($product[\"num_votes\"] < $minVote)) {\n $minVote = $product[\"num_votes\"];\n }\n }\n\n if (!isset($minVote)) {\n $minVote = 0;\n }\n\n return $minVote;\n }\n\n public function printReviews(){\n $output = \"<table>\";\n foreach($this->products as $product) {\n $product[\"vote_distribution\"] = implode(\"</td><td>\", $product[\"vote_distribution\"]);\n $product = implode(\"</td><td>\", $product);\n $output .= \"<tr><td>\" . $product . \"</td></tr>\";\n }\n $output .= \"<table>\";\n\n return $output;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:55:28.407",
"Id": "44404",
"Score": "2",
"body": "Avoid public instance variables: they break the OO principles of encapsulation and information hiding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T00:21:51.193",
"Id": "44423",
"Score": "2",
"body": "`return false` in a constructor makes no sense. If you need to bail out of a constructor, throw an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T13:52:41.437",
"Id": "44471",
"Score": "0",
"body": "Ah true guys. Like I said - just sketched this out as a starting point in case someone wanted to build on it. Didn't really put too much care other than translating OPs existing code into a class."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T17:40:52.483",
"Id": "28338",
"ParentId": "28326",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T13:17:41.600",
"Id": "28326",
"Score": "2",
"Tags": [
"php"
],
"Title": "Finding the Bayesian estimates for the top 100 products on NutraPlanet"
}
|
28326
|
<p>I have written the following Query to retrieve some object's ID. If there are objects in the list that have a larger <code>numbinbatch</code> than the <code>saveditems</code> number in the batch, then it should take that. If not, then it should take the first number from the lower number in batches.</p>
<p>I am wondering if this could be shortened. I'd also like to know if my query is bad for performance and how it can be improved.</p>
<pre><code>int NextItemID = 0;
var items =
rep.FindWhere(i => i.ID == itemID)
.Select(i => i.Batch)
.SelectMany(b => b.Items);
var savedItem = items.First(i => i.ID == itemID);
var unsavedItems = items.Where(i => i.StatusID == (short) ItemStatus.Pending);
var higherNumInBatch = unsavedItems.Where(i => i.NumInBatch > savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);
var lowerNumInBatch = unsavedItems.Where(i => i.NumInBatch < savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);
if (higherNumInBatch.Any())
{
NextItemID = (int)higherNumInBatch.Take(1).First().ID;
}
else
{
NextItemID = (int)lowerNumInBatch.Take(1).First().ID;
}
return NextItemID;
</code></pre>
|
[] |
[
{
"body": "<p>What you certainly can/should do is this:</p>\n\n<pre><code>var higherNumInBatch = unsavedItems.Where(i => i.NumInBatch > savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);\n\nif (higherNumInBatch.Any())\n{\n NextItemID = (int)higherNumInBatch.Take(1).First().ID;\n}\nelse\n{\n var lowerNumInBatch = unsavedItems.Where(i => i.NumInBatch < savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);\n NextItemID = (int)lowerNumInBatch.Take(1).First().ID;\n}\n</code></pre>\n\n<p>This way you'll only fetch the lower numbers in the batch <em>only</em> if there is no higher one. In your case you're always getting both lists which is not always necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T00:26:54.683",
"Id": "44424",
"Score": "0",
"body": "What if unsavedItems is empty. Take(1).First() will fail. Also using .Any() on highNumberInBatch and then .Take() potentially enumerates the list twice. Consider using ToList() first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T07:07:06.370",
"Id": "44445",
"Score": "0",
"body": "You're right, there should be an extry check to see if 'unsavedItems' has any items at all. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T14:45:46.727",
"Id": "28330",
"ParentId": "28328",
"Score": "0"
}
},
{
"body": "<p>You should use <code>MaxBy()</code> from <a href=\"https://stackoverflow.com/a/914198/298754\">here</a>, which is taken from <a href=\"http://code.google.com/p/morelinq/\" rel=\"nofollow noreferrer\">MoreLINQ</a>.</p>\n\n<pre><code>var items = rep.FindWhere(i => i.ID == itemID)\n .Select(i => i.Batch)\n .SelectMany(b => b.Items);\n\nvar NextItem = items.Where(i => i.StatusID == (short) ItemStatus.Pending)\n .MaxBy(i => i.NumInBatch);\n\nreturn NextItem.ID;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:49:19.350",
"Id": "28345",
"ParentId": "28328",
"Score": "1"
}
},
{
"body": "<p>This will be shorter, it takes less selects, and may runs at SQL server side</p>\n\n<pre><code>return rep.FindWhere(i => i.ID == itemID)\n .SelectMany(i => i.Batch.Items)\n .Where(i => i.StatusID == (short) ItemStatus.Pending)\n .MaxBy(i => i.NumInBatch).ID;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T15:39:13.003",
"Id": "30085",
"ParentId": "28328",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T13:48:37.293",
"Id": "28328",
"Score": "0",
"Tags": [
"c#",
"linq"
],
"Title": "Retrieving an object's ID"
}
|
28328
|
<p>I'm currently working on a logfile parser for a pretty old videogame called <em>Team Fortress Classic</em>, which can be compared to <em>Counter-Strike 1.6</em> and is available on Valve's Steam platform.</p>
<p>I started out trying to make a collection of nicknames for each player. Every player joining the server has a unique ID, the <code>STEAM_ID</code>.
Once a player joins the server I can parse the ID off the logfile: </p>
<pre><code>L 07/08/2013 - 19:25:40: "Marcus<47><STEAM_0:1:111><>" entered the game
</code></pre>
<p>So the <code>STEAM_ID</code> for the joining player would be <code>STEAM_0:1:111</code>, for the database I strip off the static prefix <code>STEAM_</code> and only add <code>0:1:111</code> to the <code>steam_id</code> field in the database to keep the size smaller.</p>
<p>Now a player can change his in-game nickname from let's say Marcus to sucraM. I thought about making a one-to-many relationship between the tables <code>players</code> and <code>aliases</code>, adding the nickname the player was first seen with to the <code>players</code> table as a primary nickname to easier keep track of the player (later that would be useful i.e. when a known player joins the server with a new nickname I could print a line "<code>new_nickname</code> is also known as <code>primary_nickname</code>" to tell everyone who they are actually dealing with) and using a foreign key field <code>player_id_fk</code> in the aliases-table to be able to add several aliases for one players.id.</p>
<p>The database structure I created looks like the following;</p>
<p><code>players</code> table:</p>
<pre><code>CREATE TABLE players (
id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
steam_id VARCHAR(15) UNIQUE,
name VARCHAR(15)
) ENGINE = 'InnoDB';
</code></pre>
<p><code>aliases</code> table:</p>
<pre><code>CREATE TABLE aliases (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
player_id_fk SMALLINT UNSIGNED,
name VARCHAR(31),
FOREIGN KEY (player_id_fk) REFERENCES players(id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE = 'InnoDB';
</code></pre>
<p>Populating the tables with dummy data:</p>
<pre><code>INSERT INTO players (id, steam_id, name) VALUES
(NULL, '0:1:111', 'Marcus'),
(NULL, '0:1:222', 'Benjamin');
INSERT INTO aliases (id, player_id_fk, name) VALUES
(NULL, (SELECT id FROM players WHERE steam_id = '0:1:111'), 'Marcus The Great'),
(NULL, (SELECT id FROM players WHERE steam_id = '0:1:111'), 'sucraM'),
(NULL, (SELECT id FROM players WHERE steam_id = '0:1:222'), 'Benjamin The Weirdo');
</code></pre>
<p>Finding a player by <code>steam_id</code> and return his primary nick and known <code>aliases</code>:</p>
<pre><code>SELECT players.steam_id, players.name, group_concat(aliases.name separator ', ') AS aliases
FROM players
INNER JOIN aliases
ON players.id = aliases.player_id_fk
WHERE players.steam_id = '0:1:111'
</code></pre>
<p>Hence I'm a novice to relational databases I have a few questions:</p>
<ol>
<li>Am I using one-to-many the right way?</li>
<li>Can the layout be improved in any form?</li>
<li><p>If I'm going to print all known player names and their aliases to a website I might have to split <code>aliases</code> (<code>group_concat() part in SELECT query</code>) by separator ", " - now if a player is using the alias/name "Hello, its me!" this will be a problem as the alias/primary nickname will be split into "Hello" and "its me!".</p>
<p>Of course I could use a separator that is very unlikely to used by any player in their nicknames but I consider that method pretty unclean. I'm sure there has to be a query which would print <code>steam_id</code>, primary nick (<code>players.name</code>) and all the players' <code>aliases</code> so I can just iterate through them, I just can't figure out how to achieve this.</p>
<p>Any suggestions? </p></li>
</ol>
|
[] |
[
{
"body": "<p>Your 3rd question is off-topic for the site, but I do believe that you are using the one-to-many relationships correctly.</p>\n\n<p>When you are finding a player by <code>steam_id</code> you don't actually need to select the <code>steam_id</code> unless you are going to use it for something in an application. This will speed up the query (probably not enough to be visible though). </p>\n\n<p>Another thing, and this is just a thought because I am not positive on how this works:</p>\n\n<p>In your <code>players</code> table you could change the primary key to be the Steam ID since that is always going to be unique and you are always going to give that as a value on the insertion of a record.</p>\n\n<p>On the same note, you can change the foreign key of the <code>aliases</code> table to be the Steam ID as well. </p>\n\n<p>Still add the Constraint of <code>NOT NULL</code>, <code>Primary Key</code> And <code>Foreign Key</code> as appropriate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T18:40:15.597",
"Id": "33475",
"ParentId": "28329",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T13:57:04.917",
"Id": "28329",
"Score": "7",
"Tags": [
"sql",
"mysql",
"parsing"
],
"Title": "Logfile parser for Team Fortress Classic video game"
}
|
28329
|
<p>I'm a C++ beginner and have made a simple class. But I'm not sure if this is well-written. It's basically just a <code>Date</code> class.</p>
<pre><code>#include <iostream>
using namespace std;
class Date{
int d, m, y; //Day, Month, Year
public:
Date(int dd = 1, int mm = 1, int yy = 1);
int addDay(const int &dd) { d += dd; }
int addMonth(const int &mm) { m += mm; }
int addYear(const int &yy) { y += yy; }
int day() const { return d; }
int month() const { return m; }
int year() const { return y; }
void display() const; //Print to screen
};
void Date::display() const {
cout << d << "." << m << "." << y << endl;
}
Date::Date(int dd, int mm, int yy){
d = dd;
m = mm;
y = yy;
}
</code></pre>
<p>For example, the arguments of <code>addDay(const int &dd);</code>. Is that good, or should it just be an integer without <code>const</code> and without reference? </p>
|
[] |
[
{
"body": "<p>For built-in types, there is no point in passing it as a <code>const&</code> - prefer a plain <code>int</code> (or a <code>const int</code>) instead.</p>\n\n<p>Other comments:</p>\n\n<ol>\n<li>Your <code>add-</code> functions are said to return <code>int</code> even though you don't have a <code>return</code> statement. I don't think that would or should even compile. Change them to <code>void</code>.</li>\n<li>Take the time to write out <code>day</code>, <code>month</code> and <code>year</code>. The extra seconds in typing is nothing compared to the readability gain.</li>\n<li>Are you sure you want a default date?</li>\n<li>Consider <a href=\"https://stackoverflow.com/questions/4421706/operator-overloading\">overloading <code>operator<<</code> to allow printing your class</a>.</li>\n<li>Consider changing your <code>display()</code> function into a <code>to_string</code> function instead, and have it return a <code>std::string</code>.</li>\n<li>Make your class easy to use correctly, and hard to use incorrectly. What if <code>month</code> is 12 and someone calls <code>addMonth()</code>? What is someone passes in June as <code>month</code>, but <code>31</code> as day? Is <code>day</code> day the day of the month, or day of the year? Adhere to the principle of least astonishment. Your class should behave the way users of the class expect it to.</li>\n<li>Don't pollute the global namespace with <code>using namespace std</code>.</li>\n<li>Split the code into a header and an implementation file. Even though you won't need it now, it's good practice. That makes point 7 even more crucial.</li>\n</ol>\n\n<p>You need to make some judgments to design a <code>Date</code> class properly. I won't give you any further suggestions, because it is a good exercise to think about it. Revise your code, and think about the pros and cons of various approaches. Apart from that and the points above, your code looks OK.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:00:03.733",
"Id": "44378",
"Score": "0",
"body": "That was fast. :-) I'll try not to repeat anything you've mentioned (if I find anything else)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:02:53.967",
"Id": "44379",
"Score": "0",
"body": "@Jamal I was just lucky, I guess :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:04:34.223",
"Id": "44380",
"Score": "0",
"body": "Indeed. I managed to answer one question alone yesterday, so that's good enough for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:17:39.670",
"Id": "44384",
"Score": "0",
"body": "Thank you. To point 3, why shouldn't I use defaults? And to point 5, should i return std::string or const char* ? What do programmers use the most or what would be more efficient ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:19:59.333",
"Id": "44386",
"Score": "1",
"body": "@NormalPeopleScareMe: I'm updating my answer regarding defaults. As for the other question, `std::string` is preferred in C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:20:34.240",
"Id": "44387",
"Score": "0",
"body": "I clarified point 5 in the answer. Use `std::string` -- it's more common and more practical to use, and can easily be converted to a C-style string if needed. Regarding defaults: How often do you think users of the class will want a date 2012 years ago?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:20:21.107",
"Id": "44398",
"Score": "0",
"body": "The thing is i cannot convert int to string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:50:32.157",
"Id": "44403",
"Score": "0",
"body": "@NormalPeopleScareMe: Yes you can, via `std::stringstream`. Example: `int num; std::stringstream ss; ss << num; std::string str = ss.str();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T07:29:34.907",
"Id": "44447",
"Score": "0",
"body": "I do agree with built-in types not being const reference but you could leave them as const. But that's a whole different discussion :-) (http://stackoverflow.com/questions/117293/use-of-const-for-function-parameters)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T07:34:18.360",
"Id": "44448",
"Score": "0",
"body": "@Firedragon Good point, I updated the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T15:54:09.470",
"Id": "44482",
"Score": "0",
"body": "@Firedragon I've been told always to use reference and const when possible. I'll check that topic later. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T15:57:05.413",
"Id": "44483",
"Score": "1",
"body": "@NormalPeopleScareMe Always use `const` when possible. Use references when it's the right thing to do. Sometimes you *want* a copy, for example -- then you shouldn't use references. For types that are similar or smaller in size to a pointer, use pass-by-value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:03:50.953",
"Id": "44485",
"Score": "0",
"body": "@Lstor Okay. But in this case where I just need the number of days to add, a reference would be fine. And since I don't change it or I don't want to it's const. Isn't that much more efficient than making a copy ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T19:43:42.093",
"Id": "44500",
"Score": "0",
"body": "No. When you are passing by reference, you send in the address of the original variable, i.e. you send in a pointer. That means you have to allocate stack space for that pointer and set its value to be the same as the address of the variable. This is pretty much the same as what you would do for an `int`, and the sizes are usually about the same. This means there is no reason to pass a reference. In addition, passing a reference *could* technically cost a bit more."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T17:58:51.337",
"Id": "28340",
"ParentId": "28339",
"Score": "10"
}
},
{
"body": "<p>@Lstor made many great points. I'll add a few things:</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">About <code>using namespace std</code></a>.</p></li>\n<li><p>Alongside @Lstor's point regarding writing out your data members, I would recommend initializing them on separate lines. Also, when you do rename your members as such, your accessors should be renamed as well. Otherwise, they will end up having the same name, which will cause errors.</p></li>\n<li><p>Pet-peeve here: using <code>int</code> when dealing with only positives. I would prefer <code>unsigned int</code> instead. You could even <code>typedef</code> them, but that's up to you.</p></li>\n<li><p>Your constructor should have an initializer list instead. So, this:</p>\n\n<pre><code>Date::Date(int dd, int mm, int yy){\n d = dd;\n m = mm;\n y = yy;\n}\n</code></pre>\n\n<p>would look like this:</p>\n\n<pre><code>Date::Date(int dd, int mm, int yy) : d(dd), m(mm), y(yy) {}\n</code></pre></li>\n<li><p>If you still want a default date, you would need a default constructor as well. The one above allows the user to set his/her own date. This one also has an initializer list, but without arguments:</p>\n\n<pre><code>// the year can default to anything, but I chose 2000 for my example\nDate::Date() : d(1), m(1), y(2000) {}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:33:54.440",
"Id": "44388",
"Score": "0",
"body": "So the default constructor would be the constructor from your example which I'll add to the existing one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:35:40.037",
"Id": "44389",
"Score": "0",
"body": "@NormalPeopleScareMe: yes, an additional one. You can have multiple constructors as long as their arguments (or lack of arguments) vary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:48:06.803",
"Id": "44390",
"Score": "0",
"body": "You can have a constructor with default arguments *and* an initializer list, too. `Date::Date(int d = 1) : day(d)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:51:58.227",
"Id": "44392",
"Score": "0",
"body": "@Lstor: Right. Is that preferred over what I mentioned, or does it not matter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:59:30.610",
"Id": "44393",
"Score": "0",
"body": "It depends. When you have a default value that makes sense, use defaults. If you don't, you should probably just do plain overloading, or maybe only keep the version that takes arguments. In any case, don't use overloading to simulate defaults, and vice versa. Java opted to drop default arguments altogether, whereas for example C# and Python also have them. Item 24 of *Effective C++* (2nd Ed.) discusses the issue further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T19:01:22.713",
"Id": "44394",
"Score": "0",
"body": "@Lstor: Ah, okay. I haven't even finished reading the first edition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T19:11:18.013",
"Id": "44395",
"Score": "0",
"body": "I mean *Effective C++*, not *More Effective C++*. It's been made in three versions/editions. I got the second edition when I bought my copy 13 years ago, so surely you have either the second or third? :-) The third edition came out in 2005. However, it seems that the relevant item is not included in the third edition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T19:13:24.320",
"Id": "44396",
"Score": "0",
"body": "@Lstor: Okay, that makes more sense. I have _Effective C++_, 3rd edition. I haven't had time yet to finish it, but I will."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T22:27:33.747",
"Id": "44416",
"Score": "0",
"body": "`Same thing, but a different format and is preferred.` is misleading. An initializer list and the constructor content are not the same thing. Elements are initialized (either explicitly, or implicitly if they're not in the list) and then the constructor is run."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T22:31:47.843",
"Id": "44417",
"Score": "0",
"body": "@Corbin: You're right. I was just thinking about the contents in general. I'll change it."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T18:10:55.880",
"Id": "28341",
"ParentId": "28339",
"Score": "5"
}
},
{
"body": "<p>If you're interested in bugs/missing functionality in addition to design issues, your <code>addDay()</code>, etc methods need to handle overflows. ex</p>\n\n<pre><code>Date foo = new Date(10, 7, 2013);\nfoo.addDay(30); //currently sets foo to July 40th, 2013.\n\nDate bar = new Date(10, 7, 2013);\nbar.addDay(-30); //currently sets bar to July -20th, 2013.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T19:49:22.197",
"Id": "28343",
"ParentId": "28339",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28340",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T17:47:12.667",
"Id": "28339",
"Score": "7",
"Tags": [
"c++",
"classes",
"beginner",
"datetime"
],
"Title": "Is this Date class well-written?"
}
|
28339
|
<p>Suppose I've got a JavaScript function that I'm treating like a class - that is, I want to make many instances of it:</p>
<pre><code>function Blerg() {
this._a = 5;
}
Blerg.prototype.getA = function() {
return this._a;
}
Blerg.prototype.setA = function(val) {
this._a = val;
}
</code></pre>
<p>This class has one attribute, <code>a</code>, which the constructor instantiates to a default value of <code>5</code>. It is accessed with the getter and setter.</p>
<p>Now suppose I have such a class but it has 30+ attributes (<code>a</code>, <code>b</code>, <code>c</code>, etc), and suppose like <code>a</code> that these all have unique default values, but also that it is <em>uncommon for them to be changed from the default.</em></p>
<p>Suppose also that I need to make 10,000 or more <code>Blerg</code> instances, and so a design goal is to save space.</p>
<p>I'm wondering if it is a good idea to put all of the <em>default values</em> for my 30+ attributes on the <code>prototype</code> of my class instead. That way, when I create 10,000+ instances of my class, none of them have <code>a</code>, <code>b</code>, <code>c</code>, etc attributes, but calling <code>getA()</code> will still return the correct default value.</p>
<p>So I present this modified <code>Blerg</code> function, <code>Blerg2</code>:</p>
<pre><code>function Blerg2() {
// nothing!
}
Blerg2.prototype._a = 5;
Blerg2.prototype.getA = function() {
return this._a;
}
Blerg2.prototype.setA = function(val) {
this._a = val;
}
</code></pre>
<p>Are there downsides to taking this approach?</p>
<hr />
<h3>Some notes</h3>
<p>The prototype way seems faster to create, see: <a href="http://jsperf.com/blergs" rel="noreferrer">http://jsperf.com/blergs</a></p>
<p>For that matter, the worst-case scenario does not look that bad: <a href="http://jsperf.com/blergs/2" rel="noreferrer">http://jsperf.com/blergs/2</a></p>
<p>And creating many of them using the code in the jsperf test (in its own html page) and adding:</p>
<pre><code>var a = [];
for (var i = 0; i < 400000; i++) {
a.push(new Blerg()); // or Blerg2
}
</code></pre>
<p>Suggests that the heap size for the objects in question is cut in half by using Blerg2.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:20:29.513",
"Id": "44399",
"Score": "0",
"body": "For reference, here is a quick help from v8: http://pastebin.com/dTk0eegF (this is the ASM generated for this code: http://pastebin.com/F59x1U15)"
}
] |
[
{
"body": "<p>related jsperf <a href=\"http://jsperf.com/12312412354\">http://jsperf.com/12312412354</a></p>\n\n<p>Well this is a really bad idea. Objects are always considered having different class if they don't have exactly the same set of properties in the same order. So\na function that accepts these objects will in best case be polymorphic and in worst case megamorphic all the while you are thinking\nyou are passing it same class of objects. This is fundamental to all JS engines although the specifics that follow focus on V8.</p>\n\n<p>Consider:</p>\n\n<pre><code>function monomorphic( a ) {\n return a.prop + a.prop;\n}\n\nvar obj = {prop: 3};\nwhile( true ) {\n monomorphic( obj );\n}\n</code></pre>\n\n<p>Now, since the passed object <code>a</code> always has the same class, we will get really good code:</p>\n\n<pre><code> ; load from stack to eax\n15633697 23 8b4508 mov eax,[ebp+0x8] \n ;; test that `a` is an object and not a small integer\n1563369A 26 f7c001000000 test eax,0x1 \n156336A0 32 0f8485000000 jz 171 (1563372B) ;;deoptimize if it is not\n ;; test that `a`'s class is as expected\n156336A6 38 8178ffb9f7902f cmp [eax+0xff],0x2f90f7b9\n156336AD 45 0f857d000000 jnz 176 (15633730) ;;deoptimize if it is not\n ;; load a.prop into ecx, as you can see it's like doing struct->field in C\n156336B3 51 8b480b mov ecx,[eax+0xb]\n ;; this will untag the tagged pointer so that integer arithmetic can be done to it\n156336B6 54 d1f9 sar ecx,1\n ;; perform a.prop + a.prop\n ;; note that if it was a.prop + a.prop2\n ;; then it wouldn't need to do all those checks again\n ;; so for one time check inside the function we can load all the properties\n ;; quickly\n156336B8 56 03c9 add ecx,ecx\n</code></pre>\n\n<p>Notice what happened here, V8 saw that we always pass the same class of object to the function\n<code>monomoprhic</code> and generated really tight code that assumes we will always get that class of object\nin the future as well.</p>\n\n<p>Now let's do:</p>\n\n<pre><code>function polymorphic( a ) {\n return a.prop + a.prop;\n}\n\nvar obj = {prop: 3};\nvar obj2 = {prop: 3, prop2: 4};\nwhile( true ) {\n polymorphic( Math.random() < 0.5 ? obj : obj2 );\n}\n</code></pre>\n\n<p>Now the function must consider 2 different classes of objects. The classes are different but similar enough\nthat the client code can stay as it is as both classes contain a field <code>prop</code>.</p>\n\n<p>Let's see:</p>\n\n<pre><code> ; load from stack to eax\n04C33E17 23 8b4508 mov eax,[ebp+0x8]\n ;; test that `a` is an object and not a small integer\n04C33E1A 26 f7c001000000 test eax,0x1\n04C33E20 32 0f8492000000 jz 184 (04C33EB8) ;; deoptimize if not\n ;; test that `a`'s class is one of the expected classes\n04C33E26 38 8178ffb9f7401c cmp [eax+0xff],0x1c40f7b9\n04C33E2D 45 0f840d000000 jz 64 (04C33E40) ;; if it is, skip the second check and go to the addition code\n ;; otherwise check that `a`'s class is the second one of the expected classes\n04C33E33 51 8178ff31f8401c cmp [eax+0xff],0x1c40f831\n04C33E3A 58 0f857d000000 jnz 189 (04C33EBD) ;; deoptimize if not\n ;; load a.prop into ecx\n ;; if you are still reading this you will probably notice that this\n ;; is actually relying on the fact that both classes declared the prop field\n ;; first\n04C33E40 64 8b480b mov ecx,[eax+0xb]\n ;; this will untag the tagged pointer so that integer arithmetic can be done to it\n04C33E43 67 d1f9 sar ecx,1\n ;; do the addition\n04C33E45 69 03c9 add ecx,ecx\n</code></pre>\n\n<p>Ok so the situation is still pretty good but here we are relying on the fact that properties are in same order\nand that there are only 2 different classes.</p>\n\n<p>Let's do the same in different order so that V8 can't use the same instruction (<code>mov ecx,[eax+0xb]</code>) for both objects:</p>\n\n<pre><code>function polymorphic( a ) {\n return a.prop + a.prop;\n}\n\nvar obj = {prop: 3};\nvar obj2 = {prop2: 4, prop: 3};\nwhile( true ) {\n polymorphic( Math.random() < 0.5 ? obj : obj2 );\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>06C33E84 36 8b4508 mov eax,[ebp+0x8]\n ;; small integer check\n06C33E87 39 f7c001000000 test eax,0x1\n06C33E8D 45 0f84d3000000 jz 262 (06C33F66)\n ;; class check 1\n06C33E93 51 8178ffb9f75037 cmp [eax+0xff],0x3750f7b9\n06C33E9A 58 7505 jnz 65 (06C33EA1)\n06C33E9C 60 8b480b mov ecx,[eax+0xb]\n06C33E9F 63 eb10 jmp 81 (06C33EB1)\n ;; class check 2\n06C33EA1 65 8178ff31f85037 cmp [eax+0xff],0x3750f831\n06C33EA8 72 0f85bd000000 jnz 267 (06C33F6B)\n06C33EAE 78 8b480f mov ecx,[eax+0xf]\n\n06C33EB1 81 f6c101 test_b cl,0x1\n06C33EB4 84 0f851e000000 jnz 120 (06C33ED8)\n06C33EBA 90 d1f9 sar ecx,1\n06C33EBC 92 89ca mov edx,ecx\n06C33EBE 94 03d1 add edx,ecx\n</code></pre>\n\n<p>Ok just as expected, just using different offsets depending on the class.</p>\n\n<p>So you can see where this is going, if you end up with 10 different classes then you will\njust get 30 instructions (instead of 3) whenever a function will need to lookup a property. Which is still\nmuch better than a hash table (100s of instructions?) lookup.</p>\n\n<p>Well no, turns out there is <a href=\"https://github.com/v8/v8/blob/e6848c0cd37a2e6dbcaff5f7e13df53ded0165a9/src/ic.cc#L1024\">a limit of 4 different classes</a>\nand then you go into megamorphic mode.</p>\n\n<p>So with this, we should see radically different code output if we use 5 or more different classes:</p>\n\n<pre><code>function megamorphic( a ) {\n return a.prop + a.prop;\n}\n\nvar objs = [\n {prop: 3},\n {prop3: 4, prop: 3, prop2: 4},\n {prop4: 4, prop2: 4, prop: 3, prop5: 6},\n {prop: 3, prop12: 6},\n {prop7: 15, prop30: 12, prop314: 4, prop34: 15, prop: 3}\n];\n\nwhile( true ) {\n var index = Math.random() * objs.length | 0;\n megamorphic( objs[index] );\n}\n</code></pre>\n\n<p>Indeed:</p>\n\n<pre><code>3D3342E7 39 8b5508 mov edx,[ebp+0x8]\n3D3342EA 42 b9f5e2a115 mov ecx,15A1E2F5\n3D3342EF 47 e84c6ffeff call LoadIC_Initialize (3D31B240)\n3D3342F4 52 8945ec mov [ebp+0xec],eax\n3D3342F7 55 8b75f0 mov esi,[ebp+0xf0]\n3D3342FA 58 8b5508 mov edx,[ebp+0x8]\n3D3342FD 61 b9f5e2a115 mov ecx,15A1E2F5\n3D334302 66 e8396ffeff call LoadIC_Initialize (3D31B240)\n3D334307 71 8b4dec mov ecx,[ebp+0xec]\n3D33430A 74 f6c101 test_b cl,0x1\n3D33430D 77 0f8527000000 jnz 122 (3D33433A)\n3D334313 83 d1f9 sar ecx,1\n3D334315 85 89c2 mov edx,eax\n3D334317 87 f6c201 test_b dl,0x1\n3D33431A 90 0f8546000000 jnz 166 (3D334366)\n3D334320 96 d1fa sar edx,1\n3D334322 98 03d1 add edx,ecx\n</code></pre>\n\n<p>That actually looks a lot like code that loads properties from objects that are in hash table mode. Is it fast? Unfortunately jsperf is down now\nso you have to run it yourself with code <a href=\"http://pastebin.com/TJqZDUHV\">here</a>:</p>\n\n<pre><code>Megamorphic 492\nMonomorphic 30\n</code></pre>\n\n<p>So the same function body ran 15 times faster because the object passed to it always had the same class. It is also hard to predict if you will actually save memory\nif all those 10000 objects allocate a different class for instance.</p>\n\n<p>It is also complicated to really look at all the downsides but having optional properties is one of those things that it is easy to say is very bad.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T14:16:21.543",
"Id": "44473",
"Score": "3",
"body": "+1. A more memory oriented estimation would have been good too but this is already very interesting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T11:22:26.563",
"Id": "44750",
"Score": "1",
"body": "@SimonSarris I left for a vacation after posting this and didn't have Internet access so I saw all your chat pings only now :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-20T12:46:45.300",
"Id": "128709",
"Score": "0",
"body": "Not sure I understand this. Why does putting default values on a prototype causes the instances to have a different set of properties? It seems to me they all have the same properties (i.e., those defined on the on the prototype). Or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-23T23:06:33.877",
"Id": "172248",
"Score": "0",
"body": "Oh @Norswap I think I understand. In the default case, where none of the default properties were overridden, I think the generated code would be efficient. But as soon as you override a default, that new property will be at a different offset. If many objects override the default, the new properties could be at a different offset for each object, therefore generating the horrible megamorphic code. It seems like in the case where more than ~4 objects plan to override defaults, it would be better to place those properties on the object instead of the prototype, so they are at the same offset."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T08:21:06.103",
"Id": "28360",
"ParentId": "28344",
"Score": "24"
}
}
] |
{
"AcceptedAnswerId": "28360",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:06:21.047",
"Id": "28344",
"Score": "17",
"Tags": [
"javascript",
"performance",
"classes",
"prototypal-class-design"
],
"Title": "Should I put default values of attributes on the prototype to save space?"
}
|
28344
|
<p>This was too slow for my computer:</p>
<pre><code>int f(unsigned int x)
{
if(x <= 1) return 1;
else return f(x-1)+f(x-2);
}
/* main */
int main()
{
for(int i = 0; i < 50; i++) cout << f(i) << endl;
return 0;
}
</code></pre>
<p>So I've made a faster implementation. It works, but is it well-written? Is there some way to improve it? </p>
<pre><code>void f(unsigned long now)
{
static int counter = 0;
static unsigned long last = 0, tmp = last;
if(counter++ == 50)
{
last = tmp = counter = 0;
return;
}
std::cout << last + now << std::endl;
tmp = last;
last = now;
f(now+tmp);
}
// calling f(1); in main
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:00:14.460",
"Id": "44405",
"Score": "0",
"body": "I just noticed that if I call this function again it will print numbers until the program crashes. Do I have to set the static variables back to zero?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:08:30.290",
"Id": "44408",
"Score": "0",
"body": "I can't say I'm too good with recursion, but [this](http://cis.stvincent.edu/carlsond/swdesign/recur/recur.html) link may help you with the algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:18:39.803",
"Id": "44410",
"Score": "1",
"body": "You do need to reset the `static` variables. They will retain their value across multiple function calls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T22:53:29.000",
"Id": "44418",
"Score": "1",
"body": "Your new code does something completely different. I would try making *incremental changes*. This doesn’t mean that you cannot redesign the code (you should!) but you should clarify upfront what the semantics of the code are actually supposed to be. A personal preference: don’t reimplement the function iteratively – stick with the recursive solution but try to make it more efficient. Hint: in order to achieve this you cannot return a single `int`, you need to return a pair of ints."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T11:03:19.520",
"Id": "44454",
"Score": "0",
"body": "Your implementation is wrong, it gives incorrect result for [1000000000 Fibonacci number](https://weblogs.java.net/blog/kabutz/archive/2012/02/24/fibonacci-1000000000-challenge?force=775)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T15:50:54.970",
"Id": "44481",
"Score": "0",
"body": "@cat_baxter I guess it's because long's limit is too low for that. Maybe a long long int would give the correct result?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:32:12.230",
"Id": "44488",
"Score": "1",
"body": "@NormalPeopleScareMe: That should work. You can also use `std::uint64_t` from the `cstdint` library."
}
] |
[
{
"body": "<p><strong>First of all:</strong> If you want execution speed, an iterative approach to fibonacci is faster. That said, implementing a recursive solution is a nice exercise.</p>\n\n<p><strong>Some other remarks:</strong></p>\n\n<ol>\n<li>Code that <em>does</em> something should not perform IO. Separate computations from UI. This will also allow you to output values only once, which is faster.</li>\n<li>Your function is very specialized. What if I want to calculate only <code>fib(5)</code>? Or up o <code>fib(65)</code>? Strive to write reusable components.</li>\n<li>Note that <code>std::endl</code> flushes the output buffer, which takes time. If you just want to output a newline, use <code>std::cout << last + now << '\\n'; instead.</code></li>\n<li><p>Instead of</p>\n\n<p><code>static unsigned long last = 0, tmp = last;</code></p>\n\n<p>write</p>\n\n<p><code>static unsigned long last = 0, tmp = 0;</code></p>\n\n<p>It's clearer, and you won't have to change anything in case you remove <code>last</code> at some point.</p></li>\n<li>I would pass state around, rather than use <code>static</code> variables.</li>\n</ol>\n\n<p>Maybe something like this:</p>\n\n<pre><code>// Helper function\nint fib_do(int max, int curr, int one_before, int two_before)\n{\n if (curr == max-1) return one_before+two_before;\n\n return fib_do(max, curr+1, one_before+two_before, one_before);\n}\n\nint fib(int n)\n{\n if (n <= 1) return 1;\n\n return fib_do(n, 1, 1, 0);\n}\n</code></pre>\n\n<p>However, this snippet (and your second version) is basically just the iterative solution implemented using recursion.</p>\n\n<p>Note that this snippet has not in any way been optimized for speed. However, it facilitates the <a href=\"http://en.wikipedia.org/wiki/Return_value_optimization\" rel=\"nofollow\">Return Value Optimization</a>.</p>\n\n<p>Finally: Consider using some form of caching to increase the speed of your recursive function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T08:43:28.760",
"Id": "44451",
"Score": "1",
"body": "“If you want execution speed, an iterative approach to fibonacci is faster” – If you make such claims, please back them up with evidence. I claim that a non-naive recursive implementation is on par with an explicit loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T11:25:34.353",
"Id": "44457",
"Score": "3",
"body": "Iterative solution is faster. Try to calculate the [1000000000 Fibonacci number](https://weblogs.java.net/blog/kabutz/archive/2012/02/24/fibonacci-1000000000-challenge?force=775) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T12:16:56.127",
"Id": "44466",
"Score": "0",
"body": "+1 Interesting approach (in relation to recursion). I also would've preferred the `last` and `tmp` on separate lines, but that's just a minor thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T23:29:48.207",
"Id": "44526",
"Score": "0",
"body": "@cat_baxter: a tail recursive function compiled with a compiler that has in effect tail recursion optimization does not use any more stack than whatever stack was allocated for its initial invocation (ignoring whatever stack is used by methods the function itself invokes) and effectively should compile to a loop in whatever \"lower level\" language it is compiling to. That link, though interesting, is not exactly relevant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T23:46:27.650",
"Id": "44527",
"Score": "0",
"body": "@cat_baxter: ...well, relevant to whether or not a tail recursive function is faster than an iterative approac, I should say."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T07:27:45.500",
"Id": "28359",
"ParentId": "28346",
"Score": "3"
}
},
{
"body": "<p>There's a few things that could be improved about the new function:</p>\n\n<ul>\n<li><p>Most obviously, its interface is awkward: when you call <code>f</code>, you have to pass 1 and it prints the first 50 Fibonacci numbers. The old function was better in that respect: you call it with an argument n and get back the n'th Fibonacci number.</p></li>\n<li><p>It uses an iterative algorithm, implemented recursively using a <a href=\"http://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow\">tail call</a>. That's common in functional languages, but I think in C++ a loop is simpler.</p></li>\n<li><p>It passes state from one invocation of the function to the next through static variables. That seems inelegant.</p></li>\n</ul>\n\n<p>Here's a straightforward iterative implementation of the algorithm:</p>\n\n<pre><code>// return the n'th Fibonacci number\nunsigned long fib(unsigned int n) {\n if (n == 0) return 0;\n unsigned long previous = 0;\n unsigned long current = 1;\n for (unsigned int i = 1; i < n; ++i) {\n unsigned long next = previous + current;\n previous = current;\n current = next;\n }\n return current;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:13:09.430",
"Id": "28375",
"ParentId": "28346",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28375",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:49:38.620",
"Id": "28346",
"Score": "2",
"Tags": [
"c++",
"recursion",
"complexity",
"fibonacci-sequence"
],
"Title": "Fibonacci sequence implementation"
}
|
28346
|
<p>the purpose of this class file is to design a Saving account that stores a saving account's annual interest rate and balance. I have not wrote the test program yet, seeing that I believe I made a few mistakes with my class file. Also, at the end of classfile, I hid a method because I didn't understand how to word that method to add the interest rate to the balance.</p>
<p>Here are some additional information that could help you understand where I was going.</p>
<pre><code>Name of class :SavingAccount Class
The Constructor should accept the amount of the savings account's starting balance.
Methods:
-Subtracting the amound of withdrawal.
-Adding the amound of a deposit.
-Adding the amount of monthly interest to the balance.
Other information:
- The annual rate is 5% (.05)
-monthly interest = Annual interest rate divided by 12.
- Getting the monthly interest rate added to balance: Add the monthly rate to the balance. With the new result, add to the balance.
</code></pre>
<p><strong>Class File</strong> </p>
<pre><code> public class SavingsAccount
{
private double balance;
private double startBalance;
private double AnnualRate = 0.5;
private double MonthlyInterest;
private double withdrawl;
private double NewWithdrawl;
private double deposit;
private double NewDeposit;
public SavingsAccount()
{
balance = 0.0;
}
public SavingsAccount(double startBalance)
{
balance = startBalance;
}
public double getAnnualRate()
{
return AnnualRate;
}
public double MonthlyInterest()
{
MonthlyInterest= AnnualRate/12;
return MonthlyInterest;
}
public double getWithdrawl()
{
NewWithdrawl = balance - withdrawl;
return NewWithdrawl;
}
public double deposit()
{
NewDeposit = balance + deposit;
return NewDeposit;
}
/* ( The objecttive is to "Add the amount of monthly interest to the balance", not sure where this was going)
public getMonthlyInterestRate()
{
MonthlyBalance = MonthlyInterest x balance;
NewMonthlyBalance = MonthlyBalance + balance;
return NewMonthlyBalance;
}
*/
}
</code></pre>
<p>Thanks for going through what I wrote, I hope I didn't make a huge mistake with my class file.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:46:23.803",
"Id": "44412",
"Score": "0",
"body": "use [Java naming convention](http://java.about.com/od/javasyntax/a/nameconventions.htm) and post full working code for reviewing."
}
] |
[
{
"body": "<ul>\n<li>First and most important remark : do not use <code>double</code> or <code>float</code> to represent money. Use <code>BigDecimal</code> instead. And make a <code>Money</code> class that combines the amount with the currency. <strong>edit</strong> : it's also possible to use long or int, if you always calculate in cents, this would make a <code>Money</code> class even more useful, to hide away that implementation detail. </li>\n<li>Think about rounding and precision. How many fractional digits can an annual rate have, how many can a monthly rate have...? How will you round if needed?</li>\n<li>Don't hard code the values of the rates. If there's anything banks like to change it is their rates. :)</li>\n<li>I would find it very odd if the date of the withdrawals and deposits did not matter in calculating the interests.</li>\n<li>I'm not sure how <code>NewWithdrawl</code> and <code>NewDeposit</code> are supposed to get their values, from the posted code. As is these fields don't seem to make much sense, it feels like they want to be parameters of methods yet to be defined.</li>\n<li><code>getWithdrawl()</code> <em>(sic)</em> seems to do the same sort of operation as <code>deposit()</code>, yet the former is named as a getter method (while it isn't one) and the latter is not. Preferably they'd be named consistently.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T06:22:23.263",
"Id": "44439",
"Score": "0",
"body": "Please note that only calculating in cents may not be enough in banking applications. Sometimes you have to calculate in tenth or hundredth of a cent (especially if you use `long` or `int`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T06:38:17.197",
"Id": "44441",
"Score": "0",
"body": "@UwePlonus hence the phrase : *if you always calculate in cents* :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T23:35:22.313",
"Id": "28353",
"ParentId": "28347",
"Score": "5"
}
},
{
"body": "<p>Please indent your code properly. Java normally uses a modified K&R style like this:</p>\n\n<pre><code>public class Whatever {\n public function int waitWhat() {\n return 42;\n }\n}\n</code></pre>\n\n<p>Also <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow\">read the Java Naming Conventions</a>.</p>\n\n<ul>\n<li>Classes are UpperCamelCase</li>\n<li>Functions and Variables are lowerCamelCase</li>\n</ul>\n\n<p>Consider using <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\" rel=\"nofollow\">JavaDoc</a> to document your code.</p>\n\n<hr>\n\n<p>Sometimes your functions are prefixed with \"get\" if they return something, sometimes not, make up your mind!</p>\n\n<hr>\n\n<p>You're using an odd method of caching values. On the one side you're caching values in private variables, on the other you always recalculate them.</p>\n\n<hr>\n\n<p>There are quite a few unused variables in there. Don't add variables because \"I might use them later on\", only add things you actually use <em>right now</em>.</p>\n\n<hr>\n\n<p>This is what a cleaned up version might look like. This misses problems like that annualRate can not be set from the outside, or that you should not use <code>double</code> for money, or that documentation is missing, or that safety-checks are missing...</p>\n\n<pre><code>public class SavingsAccount {\n\n private double balance = 0.0;\n private double annualRate = 0.5;\n\n public SavingsAccount() {\n }\n\n public SavingsAccount(double balance) {\n this.balance = balance;\n }\n\n public double deposit(double amount) {\n balance += amount;\n return balance;\n } \n\n public double getAnnualRate() {\n return annualRate;\n }\n\n public double getBalance() {\n return balance;\n }\n\n public double getMonthlyInterest() {\n return annualRate / 12;\n }\n\n public double withdraw(double amount) {\n // Don't forget safety-checks if the customer\n // is actually able to withdraw that amount!\n balance -= amount;\n return balance;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T09:46:19.877",
"Id": "28361",
"ParentId": "28347",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28361",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T20:54:52.627",
"Id": "28347",
"Score": "2",
"Tags": [
"java"
],
"Title": "Java Is my class file methods well written?"
}
|
28347
|
<p>I'm just wondering if this code is good against SQL injection attacks. I don't know how to check if is good. Also I would like to know if is good how I'm working or this is just bad practice?</p>
<pre><code><?php
if (isset($_POST['register'])) {
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$salt = "Not important";
$password_hash = crypt($password, "$2y$". $salt);
if (strlen($username) > 20) {
echo "Username is too big";
}elseif (strlen($password) > 32) {
echo "Password is too big";
}elseif (strlen($email) > 100) {
echo "E-Mail is too big";
}elseif(strlen($username) == 0 || strlen($password) == 0 || strlen($email) == 0){
echo "Fill every field";
}
else{
$sth_username = $dbh->prepare("SELECT username FROM user WHERE username = :username");
$sth_username->bindParam(":username", $username);
$sth_email = $dbh->prepare("SELECT email FROM user WHERE email = :email");
$sth_email->bindParam(":email", $email);
$sth_username->execute();
$sth_email->execute();
if ($result = $sth_username->fetch(PDO::FETCH_OBJ)) {
print $result->username . "The username is already is use";
}elseif ($result = $sth_email->fetch(PDO::FETCH_OBJ)){
print $result->email . "That e-mail is already in use";
}else{
$sth = $dbh->prepare("INSERT INTO user (username, password, email, salt) VALUES (:username, :password, :email, :salt)");
$sth->bindParam(":username", $username);
$sth->bindParam(":password", $password_hash);
$sth->bindParam(":email", $email);
$sth->bindParam(":salt", $salt);
$sth->execute();
$sth = $dbh->prepare("INSERT INTO stats (strength,agility,intelligence) VALUES (10,10,10)");
$sth->execute();
echo "You have been registered";
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:02:40.517",
"Id": "44406",
"Score": "1",
"body": "Looks good to me"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:05:05.573",
"Id": "44407",
"Score": "0",
"body": "Since you're using a Blowfish hash, make sure the format is correct."
}
] |
[
{
"body": "<p>Looks O.K. to me as well, as far as the SQL injection goes.</p>\n\n<p>However, I'd suggest checking the return value of <code>$sth->execute();</code>, so you capture possible errors (i.e., DB being down).</p>\n\n<p>You might also consider doing a case insensitive search for the existing usernames and e-mails, since \"person@gmail.com\" is the same address as \"Person@GMail.com\" and users \"Person\" and \"person\" are hard to distinguish.</p>\n\n<p>I think <code>empty($string)</code> is more advisable than <code>strlen($string) == 0</code>.</p>\n\n<p>Last, but not least, adding a \"retype your password\" field would be a good security against user mistyping what he wants for a password and then ending with a useless account (or having to use \"I forgot my password\" before the very first login).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T19:54:54.950",
"Id": "44600",
"Score": "0",
"body": "The people at UX.SE disagree with you on offering \"retype your password\" (http://ux.stackexchange.com/q/20953/16833)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T22:39:05.753",
"Id": "44615",
"Score": "0",
"body": "@Brian I don't agree with you. Yes, the \"retyping the password is bad, without a real explanation\" answer is the accepted one, and it got the most votes. However, the other answers and the comments throughout that thread are far from consensus, so I don't see this to be \"the people at UX.SE\" disagreeing (nor agreeing) with me, or among themselves."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T13:43:23.020",
"Id": "28369",
"ParentId": "28348",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28369",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:00:39.067",
"Id": "28348",
"Score": "4",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "Is this code protected against SQL injection attacks?"
}
|
28348
|
<p>Please take it easy on my as this is my first OOP web application I plan on converting it to some deeper degree but not sure yet.</p>
<p>The basic functionality is there I think, but I'm looking for some feedback on how I can improve this in terms of OOP and simplicity. Sorry for any simple mistakes only been doing php for a few months and its my first language :)</p>
<p>Many Thanks</p>
<pre><code><?php
class Image{
/*
*list of properties
*image filepath gets pasted in $imageFilepath
*/
public $imageFilepath = "";
public $imageTitle;
public $imageSize;
/*
*list of properties
*image filepath gets pasted in $imageFilepath
*/
public function __construct() {
echo 'Welcome to Dannys awesome Gallery';
}
/*
*function to get the image filepath, runs through the files the outputs then in an array
*
*/
public function getimage_Filepath() {
$image_files = get_files($imageFilepath);
if (count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file)
$index++;
}
return;
}
/*
*Outputs the file images found
*
*/
public function setimage_Filepath() {
echo $this->getimage_Filepath();
}
/*
*Generates the image name, from the actual filename
*
*/
public function getimage_title($imageTitle) {
//gets the image title using basename
$imageTitle = $this->imageFilepath;
basename($imageTitle);
return $imageTitle;
}
/*
*Outputs the image name
*
*/
public function setimage_title($imageTitle) {
//displays the image title
echo $this->imageTitle;
}
}
$image = new Image;
?>
</code></pre>
|
[] |
[
{
"body": "<p>The code below is good. I only changed the comments a bit to make them a bit clearer and more concise. However, \none glaring issue is that it seems you have your setters and getters mixed up. Note the <code>getimage_*()</code> \nand <code>setimage_*()</code> functions you have in your class. Usually, setter and getter functions do exactly that: \nthey set a value and get a value. What you seem to be doing is using the set* functions to get the \nvalue returned by another function. This is +wrong+. </p>\n\n<pre><code><?php\n\nclass Image{\n public $imageFilepath = \"\";\n public $imageTitle;\n public $imageSize;\n\n /**\n * Construct\n */\n public function __construct() {\n echo 'Welcome to Dannys awesome Gallery'; \n }\n\n /**\n * Get image filepath\n *\n * @return array\n */\n public function getimage_Filepath() {\n $image_files = get_files($imageFilepath);\n if (count($image_files)) {\n $index = 0;\n foreach($image_files as $index=>$file)\n $index++; \n }\n return;\n }\n\n\n /**\n * Output tile image found\n *\n * @return array\n */\n public function setimage_Filepath() {\n echo $this->getimage_Filepath();\n }\n\n\n /**\n * Generate image name derived from filename\n *\n * @return string\n */\n public function getimage_title($imageTitle) {\n //gets the image title using basename \n $imageTitle = $this->imageFilepath;\n basename($imageTitle);\n return $imageTitle;\n }\n\n /**\n * Output the image name\n *\n * @return string\n */\n public function setimage_title($imageTitle) {\n //displays the image title\n echo $this->imageTitle;\n }\n}\n?>\n</code></pre>\n\n<p>Now, let's get rid of the set* functions: </p>\n\n<pre><code><?php\n\nclass Image{\n public $imageFilepath = \"\";\n public $imageTitle;\n public $imageSize;\n\n /**\n * Construct\n */\n public function __construct() {\n echo 'Welcome to Dannys awesome Gallery'; \n }\n\n /**\n * Get image filepath\n *\n * @return array\n */\n public function getimage_Filepath() {\n $image_files = get_files($imageFilepath);\n if (count($image_files)) {\n $index = 0;\n foreach($image_files as $index=>$file)\n $index++; \n }\n return;\n }\n\n\n /**\n * Generate image name derived from filename\n *\n * @return string\n */\n public function getimage_title($imageTitle) {\n //gets the image title using basename \n $imageTitle = $this->imageFilepath;\n basename($imageTitle);\n return $imageTitle;\n }\n}\n?>\n</code></pre>\n\n<p>Great! Looking much better. Now, remember that your construct should be used to set variables or initialize\nfunctions that the object requires - NOT echoing something out (unless its an Exception, in which case you'd\nuse <code>throw new Exception('')</code>). So let's move the echo OUT of the class, initialize the <code>$imageFilepath</code> \nvariable:</p>\n\n<pre><code><?php\n\nclass Image{\n private $imageFilepath;\n private $imageTitle;\n private $imageSize;\n\n /**\n * Construct\n */\n public function __construct(string $imageFilepath) {\n if(empty($imageFilepath)){\n throw new Exception(\"Expecting image file path, nothing given.\");\n } else {\n $this->imageFilepath = $imageFilepath;\n }\n }\n\n /**\n * Get image filepath\n *\n * @return array\n */\n public function getImageFilepath() {\n return $this->imageFilepath;\n }\n\n /**\n * Get the files in a directory pointed by imageFilepath\n * \n * @return array\n */\n public function getFilesInFilepath(){\n $directoryContent = scandir($this->imageFilepath);\n foreach($directoryContent as $key => $value){\n $path = $this->imageFilepath . PATH_SEPARATOR . $value;\n if(is_file($path) && is_readable($path)){\n $files[] = $path;\n }\n }\n return $files;\n }\n\n\n /**\n * Generate image name derived from filename\n *\n * @return highlight_string(str) \n */\n public function getImageTitle(string $imageFile) {\n return basename($imageFile);\n }\n}\n\n// We initialize the object and set the imageFilepath at the same time\n$image = new Image(\"/home/jsanc623/Pictures/\");\n\n// We can get the image filepath\n$imageFilepath = $image->getImageFilepath();\n\n// We can get an array of all the files in a directory\n$filesInFilePath = $image->getFilesInFilepath();\n\n// We can then get the image titles for each image/\nforeach($filesInFilePath as file){\n $imageTitle[] = $image->getImageTitle($file);\n}\n\nprint_r($imageTitle)\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T08:40:43.270",
"Id": "44545",
"Score": "0",
"body": "This is brilliant! Dang I didn't realised I'd mixed the get/set things up, Its a good convention to follow though. Another quick question the contstruct checks to see if there is a filepath set, how Do I now put a filepath for it to use in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T09:03:43.757",
"Id": "44546",
"Score": "0",
"body": "This is brilliant! Dang I didn't realised I'd mixed the get/set things up, Its a good convention to follow though. I'll study this code carefully, the next goal for me to do is to make a thumbnail class and output a fixed width with a dynamic height, Think this is possible with some functions in php and the floor() function. - I've seen where to add the filepath, just thought it would need to be added before the construct or does it not matter where you put it in a piece of code like that? thanks again"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:17:06.230",
"Id": "44559",
"Score": "0",
"body": "Some remarks: class Image would make someone believe it is an Image you are pointing to, but in fact. you are pointing to an ImageFolder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:42:27.550",
"Id": "44578",
"Score": "0",
"body": "Taken on board thankyou for your input"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:57:47.820",
"Id": "44579",
"Score": "0",
"body": "Correct @Pinoniq - thanks for pointing that out! Class names should detail the class purpose / what the class works on or does. As for the construct and where the filepath goes - the class expects the filepath to be passed to it upon initialization, so basically when the class is instantiated via `$image = new Image(\"/home/jsanc623/Pictures/\");` - that path that is given is the filepath that is required. Also, yes dynamic height and fixed width is possible in PHP with either PHP GD or ImageMagick (with which you can do dynamic width or dynamic height by giving one or the other)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T18:42:48.410",
"Id": "44871",
"Score": "0",
"body": "I'm studying Imagick api at the moment and trying to figure out how I actually use it. Do I need to initialize a new class then pass the file to it as a param? Then once I've intialized it use Imagick::scaleImage passing the $file var to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T18:50:07.037",
"Id": "44873",
"Score": "0",
"body": "I've actually just found something that was helpful and wrote this small function jsanc, not sure if it will work though and how I pass the var that holds the image to it from the foreach loop. {public function setImageScale($outputimage, $w, $h) {\n $resize = new Imagick($outputimage);\n $resize->scaleImage(400,0); \n return $resize;\n }}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T14:17:56.877",
"Id": "44923",
"Score": "0",
"body": "That seems to do the work correctly. Remember that `$outputimage` is the *path* to the image - i.e: `/var/srv/test.jpg` - and you would just pass that into the function when you call it, i.e: `$Image->setImageScale('/var/srv/test.jpg', 400, 0)` or something."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T17:19:33.523",
"Id": "28377",
"ParentId": "28349",
"Score": "1"
}
},
{
"body": "<p>The following pieces of code are almost identical in functionality:</p>\n\n<pre><code>$image = new Image( '/path/to/image.png' );\n$path = $image->getImageFilepath();\n\n$image = new Image( '/path/to/image.png' );\n$path = $image->imageFilepath;\n</code></pre>\n\n<p>The first two lines employ <em>encapsulation</em>, but all four lines do not employ <em>information hiding</em>. Any class in the system can \"get\" the file path encapsulated by the <code>Image</code> class, which renders the lines functionally identical.</p>\n\n<p>To develop software using object-oriented programming techniques, think about classes in terms of <em>behaviours</em> (i.e., methods), rather than <em>attributes</em> (i.e., data).</p>\n\n<p>Why does any other code in the system need to know the image's file path? Chances are you can probably write instead:</p>\n\n<pre><code>$image = new Image( '/path/to/image.png' );\n$result = $image->isPath( '/page/to/image.png' );\n</code></pre>\n\n<p>This allows you to also write:</p>\n\n<pre><code>$result = $image->isFilename( 'image.png' );\n</code></pre>\n\n<p>Most people erroneously resort to <code>get</code> method accessors without thinking about the underlying functionality. More often than not, slapping a <code>get</code> method into a class is an incorrect and limiting approach that will lead to inflexible, duplicate code. In other words, public accessor methods (get/set) are a sign of a functional design (similar to C structures) rather than an object-oriented design.</p>\n\n<p>Pretend a method called \"getFileExtension\" exists that helps objects determine the type of image. All your objects that wanted to discern the type of image would have to call:</p>\n\n<pre><code>$extension = $image->getFileExtension();\n</code></pre>\n\n<p>Now what? All the objects would then have to check the file type:</p>\n\n<pre><code>if( $extension === \"png\" ) {\n // ... do something\n}\n</code></pre>\n\n<p>This introduces a bug, duplicate code, magic variables (what is \"png\" and do you have to check for both \"jpg\" and \"jpeg\"; what about \"jfif\" extensions?), does not inform the reader why the extension is being retrieved, and is inflexible. Consider a more sophisticated solution that determines the image type using its \"header\" (the first few bytes in the file). This reveals the code that should have been written in the first place:</p>\n\n<pre><code>$result = $image->isImageType( $IMAGE_PNG );\n</code></pre>\n\n<p>Now all the clients must determine the file type as follows:</p>\n\n<pre><code>if( $image->isImageType( $IMAGE_PNG ) ) {\n // ... do something\n}\n</code></pre>\n\n<p>It is trivial to see how the implementation could change from checking the <em>file extension</em> to checking the <em>file contents</em> without affecting any client. Not a single object that uses the <code>Image</code> class would have to change. If you wanted to support JPEG files, again, the clients need only ask:</p>\n\n<pre><code>if( $image->isImageType( $IMAGE_JPEG ) ) {\n // ... do something\n}\n</code></pre>\n\n<p>No need to scatter knowledge about \"jpeg\", \"jpg\", and \"JFIF\" extensions throughout the codebase. Such knowledge should be <em>encapsulated</em> in a single location (DRY principle) and the file name <em>hidden</em> from other classes.</p>\n\n<p>That's where the power of object-orientation resides.</p>\n\n<p>Yet hiding how the file type is determined is <em>still</em> not fully object-oriented. To be object-oriented, the code for the <code>Image</code> class should expose behaviours that clients require. Clients don't really require knowledge about the image type or its path (especially since the path is required to instantiate an <code>Image</code>). Chances are the clients would want to perform some kind of manipulation on the image. What are those manipulations? Some examples:</p>\n\n<ul>\n<li>Scale, shear, rotate</li>\n<li>Convert to black and white</li>\n<li>Convert file format</li>\n<li>Create a thumbnail</li>\n</ul>\n\n<p>Those are proper behaviours. A fully object-oriented <code>Image</code> class would be used as follows:</p>\n\n<pre><code>$image = new Image( '/path/to/file.png' );\n$image->scale( 0.5 );\n$image->rotate( 30 );\n$image->index( 2 );\n$image->thumbnail( '/path/to/thumbnail/file.jpg', 200, 200 ); // max width, height\n$image->save( '/path/to/file.jpg' );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T20:34:14.930",
"Id": "28588",
"ParentId": "28349",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28377",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-10T21:17:25.577",
"Id": "28349",
"Score": "3",
"Tags": [
"php",
"object-oriented"
],
"Title": "Photogallery First project in OOP review"
}
|
28349
|
<p>I've started reading <em>C++ Primer</em> a few weeks ago and there's an exercise that asks you to compare two arrays for equality. The code I made works, but is it good? What should I fix?</p>
<p>If the number of elements don't match, they're not equal. If the elements are different, they are not equal.</p>
<pre><code>#include <iostream>
using namespace std;
bool arrayComparer(int *a, size_t asize, int *b, size_t bsize){
if(asize != bsize){return false;}
for(size_t ite = 0; ite < asize; ++ite){
if(*(a+ite) != *(b+ite)){return false;}
}
return true;
}
int main()
{
int ar1[]{0,1,2,3,4,5,6,7,8,9},
*ptr1 = ar1,
ar2[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18},
*ptr2 = ar2;
size_t intSize = sizeof(int),
asize = sizeof(ar1) / intSize,
bsize = sizeof(ar2) / intSize;
cout << arrayComparer(ptr1,asize,ptr2,bsize) << endl;
return 0;
}
</code></pre>
<p>Since the number of elements may be different, I'm using pointers. I did not find a way to get the number of elements from the pointers, so I'm also passing the size to the function.</p>
<p>Comments are appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T04:37:35.267",
"Id": "44433",
"Score": "1",
"body": "I'm assuming you're doing this for academic reasons, but just in case: there's no need for your loop. You can just do `std::equal(ar1, ar1 + 10, ar2 + ar2 + 19).`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T05:19:31.310",
"Id": "44434",
"Score": "0",
"body": "@Corbin, wouldn't `ar1 == ar2` also work if they were both `std::array`s (and of equal size)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T06:13:34.477",
"Id": "44436",
"Score": "1",
"body": "@Jamal Yes. `std::array`'s `operator==` does indeed do an element wise comparison. I would prefer `std::equal` though because it would allow him to later change either of the types involved without having to change the comparsion (If he used `std::begin()` instead of `.begin()`). (Also, `std::array` is C++11 which he might not be used.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T01:15:39.673",
"Id": "44623",
"Score": "0",
"body": "@Corbin yes, I'm only doing it as an exercise. But thank you for pointing it out."
}
] |
[
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>.</p></li>\n<li><p>You don't need an explicit <code>return 0</code> at the end of <code>main()</code>. As reaching the end of <code>main()</code> already implies successful termination, the compiler will do the return for you.</p></li>\n<li><p>In C++, use <code>std::size_t</code> over <code>size_t</code>, the former being part of the <code>std</code> namespace.</p></li>\n<li><p>Consider having your function print <code>true</code> or <code>false</code> instead of 1 or 0. You could do this by putting <code>std::boolalpha</code> into the output stream before the function call.</p>\n\n<pre><code>cout << std::boolalpha << arrayComparer(ptr1,asize,ptr2,bsize) << endl;\n</code></pre></li>\n<li><p>There is no need for this:</p>\n\n<blockquote>\n<pre><code>std::size_t intSize = sizeof(int);\n</code></pre>\n</blockquote>\n\n<p>You can just use <code>sizeof(int)</code> for both size calculations, so that you can only have size variables that correspond to array sizes. Extra possible overhead is not a problem because <code>sizeof()</code> is actually an operator, not a function.</p></li>\n<li><p>If your compiler supports C++11, you can use an <a href=\"http://www.cplusplus.com/reference/array/array/\" rel=\"nofollow noreferrer\"><code>std::array</code></a> instead of C-style arrays. If not, use an <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a>. They both know their own sizes, and you'll no longer need your own pointers.</p>\n\n<p>Raw pointer use in C++ should generally be avoided whenever possible, and passing raw pointers can introduce ownership issues. Passing C-style arrays to functions is also bad because they will decay to pointers. If you <em>must</em> use them anyway, at least for this exercise, then perhaps you can declare <code>ptr1</code> and <code>ptr2</code> within <code>arrayComparer()</code> instead of passing them from <code>main()</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T01:00:42.913",
"Id": "28355",
"ParentId": "28354",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "28355",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T00:29:51.130",
"Id": "28354",
"Score": "6",
"Tags": [
"c++",
"array"
],
"Title": "Comparing two arrays"
}
|
28354
|
<p>It is usually inefficient to find bugs in a longer code. Unfortunately, after spending too much time in debugging my code, I realize that a good programming habit is important. Please give me some advice about codestyle, design... anything important to write high-quality code.</p>
<pre><code>import numpy as np
from numpy.random import standard_normal, chisquare, multivariate_normal, dirichlet, multinomial
from numpy.linalg import cholesky, inv
from math import sqrt
import math
class GibbsSampler(object):
"""Gibbs sampler for finite Gaussian mixture model
Given a set of hyperparameters and observations, run Gibbs sampler to estimate the parameters of the model
"""
def __init__(self, hyp_pi, mu0, kappa0, T0, nu0, y, prior_z):
"""Initialize the Gibbs sampler
@para hyp_pi: hyperparameter of pi
@para mu0, kappa0: parameter of Normal-Wishart distribution
@para T0, nu0: parameter of Normal-Wishart distribution
@para y: samples draw from Normal distributions
"""
self.hyp_pi = hyp_pi
self.mu0 = mu0
self.kappa0 = kappa0
self.T0 = T0
self.nu0 = nu0
self.y = y
self.prior_z = prior_z
def _clusters(self):
return len(self.hyp_pi)
def _dim(self):
"""
Dimension of the data
"""
return len(mu0)
def _numbers(self):
return len(self.y)
def estimate_clusters(self, iterations, burn_in, lag):
"""
"""
estimated_clusters = np.zeros(self._numbers(), float)
for iteration, z, pi, mu, sigma in self.run(iterations, burn_in, lag):
# print "Precision = %f" % self._estimate_precision(z)
count = [z.count(k) for k in range(self._clusters())]
print count
if iteration % 10 == 0:
print "iteration = %d" %iteration
def _estimate_precision(self, z):
numbers = self._numbers()
count = 0
for i in range(numbers):
if self.prior_z[i] == z[i]:
count += 1
return float(count)/float(numbers)
def run(self, iterations, burn_in, lag):
"""
Run the Gibbs sampler
"""
self._initialize_gibbs_sampler()
lag_counter = lag
iteration = 1
while iteration <= iterations:
self._iterate_gibbs_sampler()
if burn_in > 0:
burn_in -= 1
else:
if lag_counter > 0:
lag_counter -= 1
else:
lag_counter = lag
yield iteration, self.z, self.pi, self.mu, self.sigma
iteration += 1
def _initialize_gibbs_sampler(self):
"""
This sets the initial values of the parameters.
"""
clusters = self._clusters()
numbers = self._numbers()
self.mu = np.array([self._sampling_Normal_Wishart()[0] for _ in range(clusters)])
self.pi = dirichlet(hyp_pi, 1)[0]
self.sigma = np.array([self._sampling_Normal_Wishart()[1] for _ in range(clusters)])
self.z = np.array([self._multinomial_samples(pi) for _ in range(numbers)])
def _sampling_Normal_Wishart(self):
"""
Sampling mu and sigma from Normal-Wishart distribution.
"""
# Create the matrix A of the Bartlett decomposition from a p-variate Wishart distribution
d = self._dim()
chol = np.linalg.cholesky(self.T0)
if (self.nu0 <= 81+d) and (self.nu0 == round(self.nu0)):
X = np.dot(chol, np.random.normal(size = (d, self.nu0)))
else:
A = np.diag(np.sqrt(np.random.chisquare(self.nu0 - np.arange(0, d), size = d)))
A[np.tri(d, k=-1, dtype = bool)] = np.random.normal(size = (d*(d-1)/2.))
X = np.dot(chol, A)
inv_sigma = np.dot(X, X.T)
mu = np.random.multivariate_normal(self.mu0, np.linalg.inv(self.kappa0*inv_sigma))
return mu, np.linalg.inv(inv_sigma)
def _norm_pdf_multivariate(self, index, cluster):
"""
Calculate the probability density of multivariable normal distribution
"""
d = self._dim()
m = self.y[index] - self.mu[cluster]
part1 = np.dot(m, np.linalg.inv(self.sigma[cluster]))
part = np.dot(part1, m.T)
value = 1.0 / (math.pow(2.0*math.pi, d*0.5) * math.sqrt(np.linalg.det \
(self.sigma[cluster]))) * math.exp(-(0.5)*part)
return value
def _iterate_gibbs_sampler(self):
"""
Updates the values of the z, pi, mu, sigma.
"""
clusters = self._clusters()
# sampling the indicator variables
pos_z = []
for i in range(len(self.y)):
f_xi = np.array([self._norm_pdf_multivariate(i, k) for k in range(clusters)])
prob_zi = (self.pi * f_xi) / np.dot(self.pi, f_xi)
pos_zi = self._multinomial_samples(prob_zi)
pos_z.append(pos_zi)
# sampling new mixture weights
count_k = np.array([pos_z.count(k) for k in range(clusters)])
pos_pi = np.random.dirichlet(count_k + self.pi, 1)[0]
# sampling parameters for each cluster
pos_x = []
for k in range(clusters):
pos_xk = np.array([self.y[i] for i in range(len(pos_z)) if pos_z[i] == k ])
pos_x.append(pos_xk)
# calculate the posterior of multi-normal distribution
pos_mu = []
pos_sigma = []
for k in range(clusters):
if len(pos_x[k]) == 0: # No observations, no update.
pos_T0 = self.T0
pos_mu0 = self.mu0
pos_kappa0 = self.kappa0
pos_nu0 = self.nu0
else:
# Update the parameters of Normal-Wishart distribution.
# mean_k is the sample mean in k-th cluster.
# C is the sample covariance matrix.
# D is the true covariance matrix.
mean_k = np.mean(pos_x[k], axis=0)
C = np.zeros((len(mean_k), len(mean_k)))
for x_i in pos_x[k]:
C += (x_i - mean_k).reshape(len(mean_k), 1) * (x_i - mean_k)
pos_nu0 = self.nu0 + len(pos_x[k])
pos_kappa0 = self.kappa0 + len(pos_x[k])
D = float(self.kappa0 * len(pos_x[k])) / (self.kappa0 + len(pos_x[k])) * \
(mean_k - self.mu0).reshape(len(mean_k), 1) * (mean_k - self.mu0)
pos_T0 = np.linalg.inv(np.linalg.inv(self.T0) + C + D)
pos_mu0 = (self.kappa0*self.mu0 + len(pos_x[k])*mean_k) / (self.kappa0 + len(pos_x[k]))
# Update posterior parameters of Normal-Wishart distribution.
# Then draw the new parameters pos_mu and pos_sigma for each cluster.
self.mu0 = pos_mu0
self.kappa0 = pos_kappa0
self.T0 = pos_T0
self.nu0 = pos_nu0
pos_mu_k, pos_sigma_k = self._sampling_Normal_Wishart()
print pos_mu_k
pos_mu.append(pos_mu_k)
pos_sigma.append(pos_sigma_k)
# After all parameters updated, pass them to the initial values.
self.z = pos_z
self.pi = pos_pi
self.mu = pos_mu
self.sigma = pos_sigma
def _multinomial_samples(self, distributions):
return np.nonzero(multinomial(1, distributions))[0][0]
def multinomial_sample(distributions):
return np.nonzero(multinomial(1, distributions))[0][0]
def generate_observations(clusters, numbers, hyp_pi = None):
if hyp_pi == None:
hyp_pi = [1]*clusters
pi = dirichlet(hyp_pi, 1)[0]
mu = []
sigma = []
observations = []
prior_z = []
for i in range(clusters):
m, s = sampling_Normal_Wishart(mu0, kappa0, T0, nu0)
mu.append(m)
sigma.append(s)
for i in range(clusters):
cluster = multinomial_sample(pi)
obs = multivariate_normal(mu[cluster], sigma[cluster], k_num)
observations.extend(list(obs))
prior_z.extend([cluster]*k_num)
return observations, prior_z
def sampling_Normal_Wishart(mu0, kappa0, T0, nu0):
"""
Sampling cluster parameters from normal inverse Wishart distribution.
"""
d = len(mu0)
chol = np.linalg.cholesky(T0)
if (nu0 <= 81+d) and (nu0 == round(nu0)):
X = np.dot(chol, np.random.normal(size = (d, nu0)))
else:
A = np.diag(np.sqrt(np.random.chisquare(nu0 - np.arange(0, d), size = d)))
A[np.tri(d, k=-1, dtype = bool)] = np.random.normal(size = (d*(d-1)/2.))
X = np.dot(chol, A)
inv_sigma = np.dot(X, X.T)
mu = np.random.multivariate_normal(mu0, np.linalg.inv(kappa0*inv_sigma))
return mu, np.linalg.inv(inv_sigma)
if __name__ == "__main__":
# Generate the data set.
# Initialize the parameters for the model.
# d: dimension of the data.
# mu0, kappa0, T0, nu0 are the parameters of the Normal-Wishart distribution.
kappa0 = 4.0
d = 2
T0 = np.diag(np.ones(d))
mu0 = np.zeros(d)
nu0 = 14.0
clusters = 6
k_num = 50
hyp_pi = [1]*clusters
pi = dirichlet(hyp_pi, 1)[0]
y, prior_z = generate_observations(clusters, k_num, hyp_pi = None)
prior_count = [prior_z.count(k) for k in range(clusters)]
sampler = GibbsSampler(hyp_pi, mu0, kappa0, T0, nu0, y, prior_z)
sampler.estimate_clusters(200, 3, 0)
</code></pre>
|
[] |
[
{
"body": "<pre><code>import numpy as np\nfrom numpy.random import standard_normal, chisquare, multivariate_normal, dirichlet, multinomial\nfrom numpy.linalg import cholesky, inv\n</code></pre>\n\n<p>You are importing a lot of stuff here, and you aren't even using much of it. I guess not importing these names unless you refer to them a lot.</p>\n\n<pre><code>from math import sqrt\nimport math\n</code></pre>\n\n<p>When using numpy, you generally don't want stuff from math. You should use the numpy versions.</p>\n\n<pre><code>class GibbsSampler(object):\n \"\"\"Gibbs sampler for finite Gaussian mixture model\n\n Given a set of hyperparameters and observations, run Gibbs sampler to estimate the parameters of the model\n \"\"\"\n def __init__(self, hyp_pi, mu0, kappa0, T0, nu0, y, prior_z):\n\n \"\"\"Initialize the Gibbs sampler\n\n @para hyp_pi: hyperparameter of pi\n @para mu0, kappa0: parameter of Normal-Wishart distribution\n @para T0, nu0: parameter of Normal-Wishart distribution\n @para y: samples draw from Normal distributions\n \"\"\"\n</code></pre>\n\n<p>You don't have a description of prior_z. You also have a lot of parameters here. Four of them describe the Normal-Wishart distribution suggesting perhaps that should be its own class.</p>\n\n<pre><code> self.hyp_pi = hyp_pi\n self.mu0 = mu0\n self.kappa0 = kappa0\n self.T0 = T0\n self.nu0 = nu0\n self.y = y\n self.prior_z = prior_z\n\n def _clusters(self):\n return len(self.hyp_pi)\n</code></pre>\n\n<p>Rather than this, I suggest adding <code>self._clusters = len(self.hyp_pi)</code> to <code>__init__</code>. </p>\n\n<pre><code> def _dim(self):\n \"\"\"\n Dimension of the data\n \"\"\"\n return len(mu0)\n\n def _numbers(self):\n return len(self.y)\n\n def estimate_clusters(self, iterations, burn_in, lag):\n \"\"\"\n \"\"\"\n</code></pre>\n\n<p>Empty docstring, why?</p>\n\n<pre><code> estimated_clusters = np.zeros(self._numbers(), float)\n</code></pre>\n\n<p>You create this, but don't seem to do anything with it</p>\n\n<pre><code> for iteration, z, pi, mu, sigma in self.run(iterations, burn_in, lag):\n</code></pre>\n\n<p>That's a lot of elements in a tuple. your ignore most of them which raises questions</p>\n\n<pre><code> # print \"Precision = %f\" % self._estimate_precision(z)\n count = [z.count(k) for k in range(self._clusters())]\n print count\n</code></pre>\n\n<p>Could you use a collections.Counter here?</p>\n\n<pre><code> if iteration % 10 == 0:\n print \"iteration = %d\" %iteration\n</code></pre>\n\n<p>You are mixing output and logic. ITs better to have this class do the calculations, and the calling code print stuff.</p>\n\n<pre><code> def _estimate_precision(self, z):\n numbers = self._numbers()\n count = 0\n for i in range(numbers):\n if self.prior_z[i] == z[i]:\n count += 1\n</code></pre>\n\n<p>Use numpy's vector routines for this kind of thing. You should be doing something like:</p>\n\n<pre><code>count = (self.prior_z == z).sum()\n\n\n\n return float(count)/float(numbers)\n</code></pre>\n\n<p>Add <code>from __future__ import division</code> to the beginning of your script rather then explicitly forcing everything to float.</p>\n\n<pre><code> def run(self, iterations, burn_in, lag):\n \"\"\"\n Run the Gibbs sampler\n \"\"\"\n self._initialize_gibbs_sampler()\n</code></pre>\n\n<p>My general rule is that all initialization happens in a constructor. The gibbs sample should be initalized in the constructor.</p>\n\n<pre><code> lag_counter = lag\n iteration = 1\n while iteration <= iterations:\n self._iterate_gibbs_sampler()\n if burn_in > 0:\n burn_in -= 1\n else:\n if lag_counter > 0:\n lag_counter -= 1\n else:\n lag_counter = lag\n yield iteration, self.z, self.pi, self.mu, self.sigma\n iteration += 1\n</code></pre>\n\n<p>Your looping logic isn't very clear. I suggest something like:</p>\n\n<pre><code> for _ in xrange(burn_in):\n self._iterate_gibbs_sampler()\n\n for _ in xrange(burn_in, iterations, lag):\n for _ in xrange(lag):\n self._iterate_gibbs_sampler()\n yield stuff\n</code></pre>\n\n<p>I think that more clearly conveys what the code is doing.</p>\n\n<pre><code> def _initialize_gibbs_sampler(self):\n \"\"\"\n This sets the initial values of the parameters.\n \"\"\"\n clusters = self._clusters()\n numbers = self._numbers()\n self.mu = np.array([self._sampling_Normal_Wishart()[0] for _ in range(clusters)])\n self.pi = dirichlet(hyp_pi, 1)[0]\n self.sigma = np.array([self._sampling_Normal_Wishart()[1] for _ in range(clusters)])\n self.z = np.array([self._multinomial_samples(pi) for _ in range(numbers)])\n\n def _sampling_Normal_Wishart(self):\n \"\"\"\n Sampling mu and sigma from Normal-Wishart distribution.\n\n \"\"\"\n # Create the matrix A of the Bartlett decomposition from a p-variate Wishart distribution\n d = self._dim()\n chol = np.linalg.cholesky(self.T0)\n\n if (self.nu0 <= 81+d) and (self.nu0 == round(self.nu0)):\n X = np.dot(chol, np.random.normal(size = (d, self.nu0)))\n else:\n A = np.diag(np.sqrt(np.random.chisquare(self.nu0 - np.arange(0, d), size = d)))\n A[np.tri(d, k=-1, dtype = bool)] = np.random.normal(size = (d*(d-1)/2.))\n X = np.dot(chol, A)\n inv_sigma = np.dot(X, X.T)\n mu = np.random.multivariate_normal(self.mu0, np.linalg.inv(self.kappa0*inv_sigma))\n\n return mu, np.linalg.inv(inv_sigma)\n\n def _norm_pdf_multivariate(self, index, cluster):\n \"\"\"\n Calculate the probability density of multivariable normal distribution\n \"\"\"\n d = self._dim()\n m = self.y[index] - self.mu[cluster]\n part1 = np.dot(m, np.linalg.inv(self.sigma[cluster]))\n part = np.dot(part1, m.T)\n value = 1.0 / (math.pow(2.0*math.pi, d*0.5) * math.sqrt(np.linalg.det \\\n (self.sigma[cluster]))) * math.exp(-(0.5)*part)\n return value\n\n def _iterate_gibbs_sampler(self):\n \"\"\"\n Updates the values of the z, pi, mu, sigma.\n \"\"\"\n clusters = self._clusters()\n # sampling the indicator variables\n pos_z = []\n for i in range(len(self.y)):\n f_xi = np.array([self._norm_pdf_multivariate(i, k) for k in range(clusters)])\n</code></pre>\n\n<p>Do you need to create a python list and then convert to numpy? Can you vectorize that function?</p>\n\n<pre><code> prob_zi = (self.pi * f_xi) / np.dot(self.pi, f_xi)\n pos_zi = self._multinomial_samples(prob_zi)\n pos_z.append(pos_zi)\n</code></pre>\n\n<p>When using numpy, you probably shouldn't be appending into python lists. Rewrite to use numpy vectorization.</p>\n\n<pre><code> # sampling new mixture weights\n count_k = np.array([pos_z.count(k) for k in range(clusters)])\n pos_pi = np.random.dirichlet(count_k + self.pi, 1)[0]\n\n # sampling parameters for each cluster\n pos_x = []\n for k in range(clusters):\n pos_xk = np.array([self.y[i] for i in range(len(pos_z)) if pos_z[i] == k ])\n pos_x.append(pos_xk)\n # calculate the posterior of multi-normal distribution\n pos_mu = []\n pos_sigma = []\n for k in range(clusters):\n if len(pos_x[k]) == 0: # No observations, no update.\n pos_T0 = self.T0\n pos_mu0 = self.mu0\n pos_kappa0 = self.kappa0\n pos_nu0 = self.nu0\n else:\n # Update the parameters of Normal-Wishart distribution.\n # mean_k is the sample mean in k-th cluster.\n # C is the sample covariance matrix.\n # D is the true covariance matrix.\n mean_k = np.mean(pos_x[k], axis=0)\n C = np.zeros((len(mean_k), len(mean_k)))\n for x_i in pos_x[k]:\n C += (x_i - mean_k).reshape(len(mean_k), 1) * (x_i - mean_k)\n pos_nu0 = self.nu0 + len(pos_x[k])\n pos_kappa0 = self.kappa0 + len(pos_x[k])\n D = float(self.kappa0 * len(pos_x[k])) / (self.kappa0 + len(pos_x[k])) * \\\n (mean_k - self.mu0).reshape(len(mean_k), 1) * (mean_k - self.mu0)\n pos_T0 = np.linalg.inv(np.linalg.inv(self.T0) + C + D)\n pos_mu0 = (self.kappa0*self.mu0 + len(pos_x[k])*mean_k) / (self.kappa0 + len(pos_x[k]))\n</code></pre>\n\n<p>Lots and lots of formulas. Suggests that you can perhaps break some of it into functions to greater explicate the high level logic.</p>\n\n<pre><code> # Update posterior parameters of Normal-Wishart distribution.\n # Then draw the new parameters pos_mu and pos_sigma for each cluster.\n self.mu0 = pos_mu0\n self.kappa0 = pos_kappa0\n self.T0 = pos_T0\n self.nu0 = pos_nu0\n pos_mu_k, pos_sigma_k = self._sampling_Normal_Wishart()\n print pos_mu_k\n pos_mu.append(pos_mu_k)\n pos_sigma.append(pos_sigma_k)\n\n # After all parameters updated, pass them to the initial values.\n self.z = pos_z\n self.pi = pos_pi\n self.mu = pos_mu\n self.sigma = pos_sigma\n\n def _multinomial_samples(self, distributions):\n return np.nonzero(multinomial(1, distributions))[0][0]\n\ndef multinomial_sample(distributions):\n return np.nonzero(multinomial(1, distributions))[0][0]\n\ndef generate_observations(clusters, numbers, hyp_pi = None):\n if hyp_pi == None:\n hyp_pi = [1]*clusters\n pi = dirichlet(hyp_pi, 1)[0]\n mu = []\n sigma = []\n observations = []\n prior_z = []\n for i in range(clusters):\n m, s = sampling_Normal_Wishart(mu0, kappa0, T0, nu0)\n mu.append(m)\n sigma.append(s)\n for i in range(clusters):\n cluster = multinomial_sample(pi)\n obs = multivariate_normal(mu[cluster], sigma[cluster], k_num)\n observations.extend(list(obs))\n prior_z.extend([cluster]*k_num)\n return observations, prior_z\n\ndef sampling_Normal_Wishart(mu0, kappa0, T0, nu0):\n \"\"\"\n Sampling cluster parameters from normal inverse Wishart distribution.\n \"\"\"\n d = len(mu0)\n chol = np.linalg.cholesky(T0)\n\n if (nu0 <= 81+d) and (nu0 == round(nu0)):\n X = np.dot(chol, np.random.normal(size = (d, nu0)))\n else:\n A = np.diag(np.sqrt(np.random.chisquare(nu0 - np.arange(0, d), size = d)))\n A[np.tri(d, k=-1, dtype = bool)] = np.random.normal(size = (d*(d-1)/2.))\n X = np.dot(chol, A)\n inv_sigma = np.dot(X, X.T)\n mu = np.random.multivariate_normal(mu0, np.linalg.inv(kappa0*inv_sigma))\n return mu, np.linalg.inv(inv_sigma)\n</code></pre>\n\n<p>Is this duplicating the method in the class?</p>\n\n<pre><code>if __name__ == \"__main__\":\n # Generate the data set.\n # Initialize the parameters for the model.\n # d: dimension of the data.\n # mu0, kappa0, T0, nu0 are the parameters of the Normal-Wishart distribution.\n kappa0 = 4.0\n d = 2\n T0 = np.diag(np.ones(d))\n mu0 = np.zeros(d)\n nu0 = 14.0\n clusters = 6\n k_num = 50\n</code></pre>\n\n<p>Either these should be constants at the beginning of the file and in ALL_CAPS, or you should make them inside a function and thus not accessible as globals.</p>\n\n<pre><code> hyp_pi = [1]*clusters\n pi = dirichlet(hyp_pi, 1)[0]\n y, prior_z = generate_observations(clusters, k_num, hyp_pi = None)\n prior_count = [prior_z.count(k) for k in range(clusters)]\n sampler = GibbsSampler(hyp_pi, mu0, kappa0, T0, nu0, y, prior_z)\n sampler.estimate_clusters(200, 3, 0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T06:34:12.963",
"Id": "44440",
"Score": "0",
"body": "Thank you very much for helpful advice. You are my teacher!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T05:31:45.257",
"Id": "28358",
"ParentId": "28356",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "28358",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T02:56:03.157",
"Id": "28356",
"Score": "4",
"Tags": [
"python",
"optimization",
"numpy",
"statistics"
],
"Title": "Statistical samples and distributions"
}
|
28356
|
<p>I was learning a bit about about observers. Ruby has an <code>Observable</code> module, but I decided to make my own with a few tweaks.</p>
<p>The first important feature is that this module calls one <strong>or more</strong> observer methods when the observed object's state is changed. When you add an observer, <strong>you also have to specify the method that will be called</strong> (by using a symbol). You can add the same observer <em>again</em> specifying yet another method (so if you add an observer twice (two different methods), when the object's state changes, both methods will be called).</p>
<p><a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/observer/rdoc/Observable.html" rel="nofollow">Ruby's Observable module</a> seems to call the <code>#update</code> method on the observer. I prefer to choose the method to be called, so I did that change.</p>
<p>The freedom to associate multiple methods to the same observer (so it is called multiple times per state change) is something I'm unsure if it is useful in any way, though. What do you think about that?</p>
<p>The second important feature is the ability to choose which instance variables (using symbols) will be passed to the observer when it is notified of a state change. This way, when the observer is notified, it won't have to manually read the object's instance variables, since such variables will be passed as arguments to its method.</p>
<pre><code>module Observable
def add_observer(observer,method,*instance_variables)
@observers ||= {}
@observers[observer] ||= []
entry = [method,instance_variables]
@observers[observer] << entry unless @observers[observer].include?(entry)
end
def remove_observer(observer)
return unless @observers
@observers.delete(observer)
end
def state_changed
return unless @observers
@observers.each do |observer,entries|
entries.each do |entry|
variables = []
entry[1].each do |symbol|
variables << instance_variable_get("@#{symbol}")
end
observer.send(entry[0],*variables)
end
end
end
def count_observers
return @observers.size
end
alias_method :changed , :state_changed
end
</code></pre>
<p>Example:</p>
<pre><code>observableObject.add_observer(self,:somethingChanged,:instanceVar1,:instanceVar2)
</code></pre>
<p>When <code>observableObject</code>'s state changes, <code>self</code>'s method <code>#somethingChanged</code> will be called. And two instance variables from <code>observableObject</code> (<code>instanceVar1</code> and <code>instanceVar2</code>) will be passed to the method.</p>
<p>What do you think of this implementation? I like the fact that it seems to be more flexible (being able to choose which method to be called and, optionally, what instance variables to pass).</p>
|
[] |
[
{
"body": "<p>A few notes on making this look more like idiomatic Ruby:</p>\n\n<ol>\n<li><p>There's no need to use <code>return unless @observers</code> in <em>every method</em>. You initialize <code>@observers</code> to a known value, which will never be falsy; there is no harm at all in assuming it will still be set later.</p></li>\n<li><p>Any time you initialize an empty array, iterate a collection and (for each item) append something to the array, you're missing out on a <code>map</code>.</p>\n\n<p>Instead of this...</p>\n\n<pre><code>variables = []\nentry[1].each do |symbol|\n variables << instance_variable_get(\"@#{symbol}\")\nend\nobserver.send(entry[0],*variables)\n</code></pre>\n\n<p>...use this:</p>\n\n<pre><code>variables = entry[1].map { |symbol| instance_variable_get(\"@#{symbol}\") }\nobserver.send(entry[0],*variables)\n</code></pre></li>\n<li><p>The last statement in a method is the return value; get rid of your explicit <code>returns</code>:</p>\n\n<pre><code>def count_observers\n @observers.size\nend\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T04:09:47.240",
"Id": "44534",
"Score": "0",
"body": "For number 1, if I remove the return in the \"state_changed\" method, I would get an 'undefined .each method' error if the subject never had observers (because @observers would be nil)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:54:25.487",
"Id": "44563",
"Score": "0",
"body": "You're right, for some reason I was reading the `add_observer` method as the constructor and assuming `@observers` would always be set."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T13:29:36.870",
"Id": "28368",
"ParentId": "28357",
"Score": "1"
}
},
{
"body": "<p>I'm a bit late, but I just stumbled on this now. I'm also sorry if I risk ruining the fun by questioning the usefulness.</p>\n\n<p>I first would like to point out that from ruby 1.9.1 you can also choose the function that will be called by passing it to <a href=\"http://ruby-doc.org/stdlib-1.9.1/libdoc/observer/rdoc/Observable.html#method-i-add_observer\" rel=\"nofollow\"><code>add_observer</code></a>.</p>\n\n<p>As for passing instance variables, I personally prefer to keep it simple by passing <code>self</code> so that the external observers can use the object interface as usual to come and get the information they need. Basically it keeps things a little bit more decoupled. You wouldn't have a very specific signature in your observable object for a specific listener, just general infrastructure allowing outside code to obtain certain information. </p>\n\n<p>One thing the observer module from the standard library does not provide however is the possibility to have more specific events than just \"I've changed\". A \"standard\" method of solving this does exists though, it's called <a href=\"https://qt-project.org/doc/qt-4.8/signalsandslots.html\" rel=\"nofollow\">signals and slots</a>. They exist in QT and Boost for c++. Signals and slots have already been ported to ruby by both <a href=\"http://techbase.kde.org/Development/Languages/Ruby\" rel=\"nofollow\">QtRuby</a> and <a href=\"https://github.com/llambeau/sigslot\" rel=\"nofollow\">sigslot</a>.</p>\n\n<p>All in all, I don't find it worth manually implementing this given what already exists...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-05T14:43:53.520",
"Id": "52517",
"ParentId": "28357",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28368",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T04:56:59.713",
"Id": "28357",
"Score": "0",
"Tags": [
"ruby",
"design-patterns",
"modules"
],
"Title": "A flexible Ruby Observable module"
}
|
28357
|
<p>I've been thinking about making Javascript Prototypes that represent HTML elements.
For example a form prototype with build in ajax requests and form element prototypes. Or a list with list item prototypes. </p>
<p>I think that the biggest benefit of this approach is that it reduces repetitive code.</p>
<p>Here is an <a href="http://jsfiddle.net/8mEUZ/" rel="nofollow">example</a> of what I have in mind.</p>
<pre><code>var LightParticle = function() {
this.setWidth(10);
this.setHeight(10);
this.setTop(0);
this.setLeft(0);
this.setPosition("absolute");
this.setBackground("white");
this.setClassName("LightParticle");
};
LightParticle.prototype = {
setWidth : function(width) {
this.width = width;
},
getWidth : function() {
return this.width;
},
setHeight : function(height) {
this.height = height;
},
getHeight : function() {
return this.height;
},
setTop : function(top) {
this.top = top;
},
getTop : function() {
return this.top;
},
setLeft : function(left) {
this.left = left;
},
getLeft : function() {
return this.left;
},
setBackground : function(background) {
this.background = background;
},
getBackground : function() {
return this.background;
},
setClassName : function(className) {
this.className = className;
},
getClassName : function() {
return this.className;
},
setElement : function(element) {
this.element = element;
},
getElement : function(element) {
return this.element;
},
setPosition : function(position) {
this.position = position;
},
getPosition : function(position) {
return this.position;
},
setSize : function(size) {
this.setWidth(size);
this.setHeight(size);
},
getStyle : function() {
return {
position: this.getPosition(),
width : this.getWidth(),
height : this.getHeight(),
top : this.getTop(),
left: this.getLeft(),
background: this.getBackground()
}
},
getView : function() {
var element = $("<div></div>");
element
.addClass(this.getClassName())
.css(this.getStyle());
this.setElement(element);
return element;
},
pulsate : function (speed) {
var height = this.getHeight();
var width = this.getWidth();
var top = this.getTop();
var left = this.getLeft();
if(this.getElement().height() == height) {
height = height * 4;
width = width * 4;
top = top - (height/2);
left = left - (width/2);
}
$(this.getElement()).animate({
"height":height,
"width": width,
"top": top,
"left":left
}, speed);
var that = this;
setTimeout(function(){
that.pulsate(speed);
}, speed);
}
}
function addRandomParticle() {
try {
var particle = new LightParticle();
var seed = Math.floor(Math.random() * 70) + 1;
particle.setBackground("#" + Math.floor((Math.abs(Math.sin(seed) * 16777215)) % 16777215).toString(16));
particle.setSize(Math.floor(Math.random() * 70) + 10);
particle.setTop(Math.floor(Math.random() * $(window).height()));
particle.setLeft(Math.floor(Math.random() * $(window).width()));
$('#canvas').append(particle.getView());
particle.pulsate(Math.floor(Math.random() * 2000) + 500);
} catch(error) {
console.log(error.message);
}
}
$(document).ready(function() {
try {
for(var i = 0; i < 100; i++) {
addRandomParticle();
}
} catch(error) {
console.log(error.message);
}
});
</code></pre>
<p>So far I'm not satisfied with the getters and setters since they have no datatype validation.</p>
<p>Does anyone have any idea how I can improve this? Or does someone know a completely better approach to reduce javascript code/events? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T12:15:30.937",
"Id": "44465",
"Score": "0",
"body": "How does this \"reduce repetitive code to a minimum\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T12:29:54.163",
"Id": "44467",
"Score": "1",
"body": "Not really related to your question, but why so many try/catch? It's javascript, not java. Exceptions are really exceptional."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T12:46:09.453",
"Id": "44468",
"Score": "0",
"body": "The setters and getters also look more like the verbosity of java than like a dry framework."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T23:57:10.827",
"Id": "44530",
"Score": "0",
"body": "Since you're using jQuery already, how about replacing that entire class with `var particle = $(\"<div></div>\").addClass(\"LightParticle\").css({position: \"absolute\", width: \"10px\", height: \"10px\", background: \"white\"});` - from there, animate it however you like. E.g. using jquery's `animate()`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:33:14.297",
"Id": "44570",
"Score": "0",
"body": "@dystroy I agree on that, however I really wanjt to validate the incoming datatypes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:36:00.450",
"Id": "44571",
"Score": "0",
"body": "@Flambino Constructing the particle isn't the problem. The repetitive events are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T23:18:33.293",
"Id": "44619",
"Score": "2",
"body": "@Sem Oh, I understand that, but 70% of your code right now is constructing the particle. If you want to avoid repetition, then don't duplicate jQuery's functionality. Besides, a jQuery obj already \"represents an HTML element\" (or several, of course). Build on top of that, wrap things in functions, etc.. For a more direct HTML-to-obj connection, look at Prototype JS, which extends prototypes (which is nasty, although the resulting syntax is neat, IMHO)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T05:52:28.243",
"Id": "44720",
"Score": "0",
"body": "@Flambino Alright, i'll make a better example soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T21:21:28.997",
"Id": "84238",
"Score": "0",
"body": "But...light particles have no width and height."
}
] |
[
{
"body": "<p>As dystroy mentioned, the setters and getters are really not JavaScript style, neither are the many <code>try/catch</code> statements in your functions.</p>\n\n<p>However, if you insist on having all these getters and setters, you should create a utility function that generates a getter/setter for you. Since you have default values for most properties in your <code>LightParticle</code> I was thinking something along the lines of this : </p>\n\n<pre><code>function addGetterSetter( o , property , defaultValue ){\n var postFix = property[0].toUpperCase() + property.slice(1),\n getter = 'get' + postFix,\n setter = 'set' + postFix;\n o[getter] = function(){\n return this[property] || defaultValue;\n }\n o[setter] = function( value ){\n this[property] = value;\n return this;\n } \n} \n</code></pre>\n\n<p>And then you would</p>\n\n<pre><code>var LightParticle = function() {},\n prototype = LightParticle.prototype;\n\naddGetterSetter( prototype , width , 10 );\naddGetterSetter( prototype , height , 10 );\naddGetterSetter( prototype , top , 0 );\naddGetterSetter( prototype , left , 0 );\naddGetterSetter( prototype , position, 'absolute' );\naddGetterSetter( prototype , background, 'white' );\naddGetterSetter( prototype , className , 'LightParticle' );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:23:35.827",
"Id": "48010",
"ParentId": "28365",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "48010",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T12:02:50.780",
"Id": "28365",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Javascript Prototypes that represent HTML elements"
}
|
28365
|
<p>I've got the following code to monitor the network usage on a network interface. I'm mainly looking for feedback on the design, but if you see any code improvements please let me know! This is also the first time I've actually added 'official' documentation so tell me if I'm forgetting something.
For those that feel more comfortable browsing github: you can find the code <a href="https://github.com/Vannevelj/NetworkInspector/tree/master/NetworkInspector">here</a>.</p>
<p><strong>Statistics:</strong></p>
<pre><code>public interface IStatistics {
string NetworkInterface { get; }
float DataSent { get; }
float DataReceived { get; }
float UploadSpeed { get; }
float DownloadSpeed { get; }
Queue<float> LatestDownTransfers { get; }
Queue<float> LatestUpTransfers { get; }
}
public class Statistics : IStatistics {
public Statistics(string name) {
NetworkInterface = name;
LatestDownTransfers = new Queue<float>(3);
LatestUpTransfers = new Queue<float>(3);
}
// <summary>
// Holds the name of the selected network interface
// </summary>
public string NetworkInterface { get; set; }
// <summary>
// Contains the data sent in the most recent time interval
// </summary>
public float DataSent { get; set; }
// <summary>
// Contains the data received in the most recent time interval
// </summary>
public float DataReceived { get; set; }
// <summary>
// Returns the upload speed in KiloBytes / Second
// </summary>
public float UploadSpeed {
get { return LatestUpTransfers.Sum() / LatestUpTransfers.Count / 1028 / StatisticsFactory.MULTIPLIER; }
}
// <summary>
// Returns the download speed in KiloBytes / Second
// </summary>
public float DownloadSpeed {
get { return LatestDownTransfers.Sum() / LatestDownTransfers.Count / 1028 / StatisticsFactory.MULTIPLIER; }
}
// <summary>
// Contains the data received in the three most recent time intervals
// </summary>
public Queue<float> LatestDownTransfers { get; set; }
// <summary>
// Contains the data sent in the three most recent time intervals
// </summary>
public Queue<float> LatestUpTransfers { get; set; }
}
</code></pre>
<p><strong>Statistics Factory:</strong></p>
<pre><code>public static class StatisticsFactory {
private static Queue<float> _latestDownTransfers = new Queue<float>();
private static Queue<float> _latestUpTransfers = new Queue<float>();
private static Statistics stats;
public const int MULTIPLIER = 25;
// <summary>
// Creates a new statistic and uses the latest transferrates from the previous stats
// </summary>
public static Statistics CreateStatistics(string interfaceName) {
stats = new Statistics(interfaceName) {
LatestDownTransfers = _latestDownTransfers,
LatestUpTransfers = _latestUpTransfers
};
return stats;
}
// <summary>
// Adds a value to the current running statistics summary's upload list
// </summary>
public static void AddSentData(float d) {
stats.DataSent = d;
if (_latestUpTransfers.Count == 3) {
_latestUpTransfers.Dequeue();
}
_latestUpTransfers.Enqueue(d);
stats.LatestUpTransfers = _latestUpTransfers;
}
// <summary>
// Adds a value to the current running statistics summary's download list
// </summary>
public static void AddReceivedData(float d) {
stats.DataReceived = d;
if (_latestDownTransfers.Count == 3) {
_latestDownTransfers.Dequeue();
}
_latestDownTransfers.Enqueue(d);
stats.LatestDownTransfers = _latestDownTransfers;
}
}
</code></pre>
<p><strong>Utilities:</strong></p>
<pre><code>public static class Utilities {
static Utilities() {
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
}
// <summary>
// Returns statistics about the given network interface
// </summary>
public static IStatistics GetNetworkStatistics(string interfaceName) {
var stats = StatisticsFactory.CreateStatistics(interfaceName);
var dataSentCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", interfaceName);
var dataReceivedCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", interfaceName);
float sendSum = 0;
float receiveSum = 0;
for (var index = 0; index < StatisticsFactory.MULTIPLIER; index++) {
sendSum += dataSentCounter.NextValue();
receiveSum += dataReceivedCounter.NextValue();
}
if (sendSum > 0 || receiveSum > 0) {
StatisticsFactory.AddReceivedData(receiveSum);
StatisticsFactory.AddSentData(sendSum);
}
return stats;
}
// <summary>
// Returns a list of all available network interfaces
// </summary>
public static IList<string> GetNetworkInterfaces() {
return new PerformanceCounterCategory("Network Interface").GetInstanceNames().ToList();
}
}
</code></pre>
<p><strong>Program:</strong></p>
<pre><code>public class Program {
private static void Main(string[] args) {
var instances = Utilities.GetNetworkInterfaces();
Console.WriteLine("All available network interfaces:\n");
for (var i = 0; i < instances.Count; i++) {
Console.WriteLine(i + ": " + instances[i]);
}
var choice = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Selected network interface:\n" + instances[choice] + "\n\n");
while (true) {
var stats = Utilities.GetNetworkStatistics(instances[choice]);
Console.WriteLine("Download speed: " + stats.DownloadSpeed + " KBytes/s");
Console.WriteLine("Upload speed: " + stats.UploadSpeed + " KBytes/s");
Console.WriteLine("--------------------------------------------------------------\n\n");
Thread.Sleep(1000);
}
}
}
</code></pre>
<p>A few remarks:</p>
<p>The current download/upload speed is determined by calculating the mean of the three latest time intervals. In one interval, the data transmitted according to the <code>PerformanceCounter</code> is checked 25 times to get a pretty accurate result. Have I approached this the right way?</p>
<p>Second of all: the factory is using a static list to store the data of the latest statistics across statistic instances. This makes sure I keep the previous data, even though I create a new object. It works, but it feels dirty. Thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T15:34:23.127",
"Id": "44479",
"Score": "0",
"body": "Is there a reason why everything is Static?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T15:43:24.140",
"Id": "44480",
"Score": "0",
"body": "I personally feel like static methods make a lot of sense for utility classes, certainly because there will be only one interface tracked at a time. And as far as I've seen a factory is usually statically implemented as well. Would you approach this differently?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:47:41.340",
"Id": "44489",
"Score": "0",
"body": "To me, static classes are reminiscent of procedural programming, and even worse, emulate VB6 with the global methods and variables. I also find in some instances they interfere with unit testing, both as a change of state problem, but they also restrict the ability to test a specific section of code because you are tying that code to the static method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T22:54:37.003",
"Id": "44948",
"Score": "0",
"body": "How are you unit testing/isolation testing this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T22:58:46.670",
"Id": "44949",
"Score": "0",
"body": "I'm not actually: the entire concept of network programming and decapsulation of packets is new to me so I had to figure out what could work along the way. Now that I have found what works I'll look into writing unit tests for future reference (I haven't got experience with mocking network data). Any suggestions? I've been thinking about my design and I will probably remove the static methods and use objects instead."
}
] |
[
{
"body": "<p><strong>Style</strong></p>\n\n<ol>\n<li><code>IStatistics</code> is a bit of a generic name (although I guess if you put it in a sensible namespace it might be ok). I'd consider renaming it to something like <code>INetworkStatistics</code>.</li>\n<li>From looking at the code it is not obvious what units the upload and download speeds are (apart from one comment). Consider abstracting it behind a <code>TransferSpeed</code> class from which you can get any sensible transfer speed (e.g. KB/sec, MB/sec, MB/min, ...) or at least put the unit in the property name.</li>\n</ol>\n\n<p><strong>Design</strong></p>\n\n<ol>\n<li><p>Your interface <code>IStatistics</code> exposes some internals which should not be of any interest to the user, namely <code>DataSent</code>, <code>DataReceived</code> and <code>LatestDownTransfers</code>, <code>LatestUpTransfers</code>. I'd say the user only cares about the fact that he can get the up/download rate and add new data points. So your interface should look like this:</p>\n\n<pre><code>public interface INetworkStatistics \n{\n string NetworkInterface { get; }\n float UploadSpeed { get; }\n float DownloadSpeed { get; }\n void AddSentData(float data);\n void AddReceivedData(float data);\n}\n</code></pre>\n\n<p>You can then implement the <code>Add</code> methods as you implemented them in your factory class.</p></li>\n<li><p>Rename your utility function <code>GetNetworkStatistics</code> into <code>UpdateNetworkStatistics</code> and pass it as parameter an <code>IStatistics</code> instance to record the data points for:</p>\n\n<pre><code>public static void UpdateNetworkStatistics(IStatistics stats)\n{\n var dataSentCounter = new PerformanceCounter(\"Network Interface\", \"Bytes Sent/sec\", stats.NetworkInterface);\n var dataReceivedCounter = new PerformanceCounter(\"Network Interface\", \"Bytes Received/sec\", stats.NetworkInterface);\n\n float sendSum = 0;\n float receiveSum = 0;\n\n for (var index = 0; index < Statistics.MULTIPLIER; index++)\n {\n sendSum += dataSentCounter.NextValue();\n receiveSum += dataReceivedCounter.NextValue();\n }\n\n if (sendSum > 0 || receiveSum > 0)\n {\n stats.AddReceivedData(receiveSum);\n stats.AddSentData(sendSum);\n }\n}\n</code></pre>\n\n<p>The <code>while(true)</code> loop in your main program would now become:</p>\n\n<pre><code>stats = new Statistics(instances[choice]);\nwhile (true) \n{\n Utilities.UpdateNetworkStatistics(stats);\n ...\n</code></pre></li>\n<li>Lo and behold you can now delete the <code>StatisticsFactory</code> class. It serves no purpose other than making it near impossible to get statistics for more than one interface at a time and interfere with unit testing big time.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T09:55:56.553",
"Id": "36005",
"ParentId": "28367",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "36005",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T13:00:59.977",
"Id": "28367",
"Score": "6",
"Tags": [
"c#",
"networking"
],
"Title": "Basic network utilisation display"
}
|
28367
|
<p>I've built a small library for comparing objects based on their members <a href="https://github.com/alabax/YetAnotherEqualityComparer" rel="nofollow noreferrer">here</a> (<a href="https://stackoverflow.com/questions/17558135/is-there-a-way-to-reduce-amount-of-boilerplate-code-in-equals-and-gethashcode">related SO question</a>).</p>
<p>There's a need to compute hash function in order to conform to <code>IEqualityComparer<T></code> interface. In my case this function has to be computed based on the hash functions of members. So the main problem is how to compose them.</p>
<p>I use the following approach currently:</p>
<pre><code>public int GetHashCode(T obj)
{
VerifyHaveMembersSetup();
if (TypeTester<T>.IsNull(obj))
{
return 0;
}
if (getHashCodeBehavior == GetHashCodeBehavior.Cache && cachedHashCode.HasValue)
{
return cachedHashCode.Value;
}
int hashCode = 0;
for (int i = 0; i < memberSetups.Count; ++i)
{
int leftShift = i % 32;
int rightShift = 32 - leftShift;
int memberHashCode = memberSetups[i].GetMemberHashCode(obj);
hashCode = hashCode ^ ((memberHashCode << leftShift) | (memberHashCode >> rightShift));
}
if (getHashCodeBehavior == GetHashCodeBehavior.ImmutableCheck
&& cachedHashCode.HasValue && cachedHashCode.Value != hashCode)
{
throw new InvalidOperationException("Hash code value changed");
}
cachedHashCode = hashCode;
return hashCode;
}
</code></pre>
<ol>
<li><p>Are there any problems with this code?</p></li>
<li><p><a href="https://stackoverflow.com/a/263416/484050">I don't like the way many people implement composite functions</a>. With multiplication and addition, significant bits are shifted away and are lost.</p></li>
</ol>
<p>That's why I use bitshift operators <code><<</code> and <code>>></code>. Still I'm not completely sure how good would be a hash function generated such way. Especially when it's computed over small collection of <code>memberSetups</code> of <code>bool</code>s for example (since <code>bool</code> has only 2 hash values in .NET: 1 and 0).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:00:22.937",
"Id": "44484",
"Score": "0",
"body": "\"with multiplications and additions significant bits are shifted away and are lost.\" I'm not buying that argument. The very nature of hashing throws away information, but keeps it within a particular space (in our .NET world, it's a 32-bit signed integer). Read the pages linked to from that page (http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx, https://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx?Redirected=true and http://www.amazon.com/dp/0321356683/?tag=stackoverfl08-20). I think you'll find Skeet's implementation solid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T18:16:34.723",
"Id": "44493",
"Score": "0",
"body": "Okay I was wrong. 23 used in multiplication there has lowest bit of 1 (the number is odd) that's why it will not be shifting everything out completely."
}
] |
[
{
"body": "<p>If I'm not wrong, your hashcode starts using the most significant bit only when <code>memberHashCode << leftShift</code> is using it. This may very well never be the case, if memberSetups.Count is low, and the hashcode of the object you're using is not perfect. For example, ints or bool.</p>\n\n<p>As so, in the worst cases, your hashes are only spread a bit better than your inputs over al the integers, which is not 100% satisfying. Maybe instead of <code>++i</code>in the loop, you could go with <code>i+=32/memberSetups.Count</code>to fasten the process of using the most significant bits (even if that's still not perfect).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T16:03:39.680",
"Id": "28374",
"ParentId": "28372",
"Score": "0"
}
},
{
"body": "<p>Shifting the values before xor:ing them is somewhat better than the worst thinkable ways of combining the hash codes, but it's not very good. You will easily get combinations that cancel each other out, so you get hash codes with a distribution heavily skewed towards zero.</p>\n\n<p>Multiplying values by a prime number on the other hand gives a pretty good distribution. Back in the day it was actually used to produce random numbers, partly because of how it spreads the values reasonably even over the number range.</p>\n\n<p>A method that would give an even better distribution would be to use an advanced hashing algorithm like MD5 or CRC32, but the drawback would be that they are a lot slower. You would lose much of the advantage of using a hash code in the first place.</p>\n\n<p>All in all, multiplying by a prime number gives a very good distribution in relation to the processing time needed. It's a compromise well suited for the <code>GetHashCode</code> method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T22:53:44.583",
"Id": "44617",
"Score": "0",
"body": "Why are prime numbers so important? Why is it better than just odd numbers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T12:54:42.637",
"Id": "44649",
"Score": "0",
"body": "@Mike: I don't know the mathematics behind that, but Derrick Henry Lehmer did. Here is a start for further reading: https://en.wikipedia.org/wiki/Lehmer_random_number_generator"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:21:38.503",
"Id": "28416",
"ParentId": "28372",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T15:15:27.283",
"Id": "28372",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Composite GetHashCode function"
}
|
28372
|
<p>I am learning about timing analysis in Python. I used <code>time</code> module before it was pointed out that <code>timeit</code> module would be better for timing analysis.</p>
<p>My main focus on timing analysis is for conducting many test cases on 2 variations of the same function. In this example code I used 2 variations of function for reversing a number.</p>
<p>Can the timing analysis be done in a better way? Is the method scalable for many test cases?</p>
<pre><code>def reverse_num(num):
'''returns the reverse of an integer '''
if num < 0:
return - int(str(-num)[::-1])
else:
return int(str(num)[::-1])
def reverse_num2(num):
rev = 0
while num > 0:
rev *= 10
rev += num % 10
num /= 10
return rev
if __name__ == "__main__":
from timeit import Timer
def test(f):
for i in xrange(1000):
f(i)
print Timer(lambda: test(reverse_num)).timeit(number = 100)
print Timer(lambda: test(reverse_num2)).timeit(number = 100)
</code></pre>
<hr>
<p>I am posting sample test runs for my usage of <code>timeit</code> module for timing for the following code. I wrote it for <a href="https://codereview.stackexchange.com/questions/28398/sort-a-list-in-python">this question</a>.</p>
<pre><code>def mysort(words):
mylist1 = sorted([i for i in words if i[:1] == "s"])
mylist2 = sorted([i for i in words if i[:1] != "s"])
list = mylist1 + mylist2
return list
def mysort3(words):
ans = []
p = ans.append
q = words.remove
words.sort()
for i in words[:]:
if i[0] == 's':
p(i)
q(i)
return ans + words
def mysort4(words):
ans1 = []
ans2 = []
p = ans1.append
q = ans2.append
for i in words:
if i[0] == 's':
p(i)
else:
q(i)
ans1.sort()
ans2.sort()
return ans1 + ans2
def mysort6(words):
return ( sorted([i for i in words if i[:1] == "s"]) +
sorted([i for i in words if i[:1] != "s"])
)
if __name__ == "__main__":
from timeit import Timer
def test(f):
f(['a','b','c','abcd','s','se', 'ee', 'as'])
print Timer(lambda: test(mysort)).timeit(number = 10000)
print Timer(lambda: test(mysort3)).timeit(number = 10000)
print Timer(lambda: test(mysort4)).timeit(number = 10000)
print Timer(lambda: test(mysort6)).timeit(number = 10000)
</code></pre>
<p>The timing results are</p>
<blockquote>
<pre><code>>>> ================================ RESTART ================================
>>>
0.0643831414457
0.0445699517515
0.0446611241927
0.0616633662243
>>> ================================ RESTART ================================
>>>
0.0625827896417
0.045101588386
0.0443568108447
0.0607123363607
>>> ================================ RESTART ================================
>>>
0.0647336488305
0.0596154305912
0.0445711673841
0.0614101094434
>>> ================================ RESTART ================================
>>>
0.0689924148581
0.0502542495475
0.0443466805735
0.0903267660811
>>> ================================ RESTART ================================
>>>
0.0695374234506
0.0579001730656
0.0443790974415
0.0835670386907
>>> ================================ RESTART ================================
>>>
0.0675612101379
0.05079925814
0.044170413854
0.0681050030978
</code></pre>
</blockquote>
<p>As you can see that the results vary each time. I understand that the times are small but that is the whole purpose of <code>number = 10000</code> in <code>timeit</code> to measure consistently by doing timing many times and finding average or the best.</p>
<p>In most runs the 2nd function takes more time than 3rd function but sometimes it doesn't. The 4th function takes more time than 1st function in some cases and sometimes less.</p>
<p>I think it is correct according to usage but why these variable results? Is this the proper way of doing timing or not? I am really confused about this.</p>
<hr>
<p>After some discussion in the chat room and some more thinking I came up with for testing functions that have integer inputs. Additional nested functions can be defined for more tests and the repetitions can be made more. It may take some time but it gives good results as far as I can see. Simple function calls need to be added for variations of the same function.</p>
<pre><code>def testing():
from timeit import Timer
import random
def tests(f, times):
def test1(f):
f(random.randint(1, 1000))
def test2(f):
f(random.randint(100000, 1000000))
print(f.__name__)
print(Timer(lambda: test1(f)).timeit(number = times))
print(Timer(lambda: test2(f)).timeit(number = times//10))
print()
tests(reverse_num, 10000)
tests(reverse_num2, 10000)
</code></pre>
<p><hr>
<strong>Please note that</strong> I started using Python 3 while I was still discussing the question. I won't be using anything specific to Python 3 so all codes can be run on Python 2. Anyone wanting to run new codes will just need to change the <code>print</code> statements. Nothing else.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T11:47:45.120",
"Id": "44920",
"Score": "0",
"body": "\"My usage of timeit module gave variable results on every run.\" How many tests/how long runs were they? What was the relative difference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T14:20:43.100",
"Id": "44924",
"Score": "0",
"body": "Updated the question."
}
] |
[
{
"body": "<p>Software timing benchmarks are notoriously noisy because your computer isn't a very good controlled experimental platform.</p>\n\n<ul>\n<li>Some algorithms are nondeterministic. For instance, some quicksort implementations choose a random pivot element.</li>\n<li>While you're running your benchmarks, your python process may get preempted by other running applications, operating system threads, etc.</li>\n<li>Even if your process got the same amount of CPU during every run, the timing may be different because a different mix of applications is running so your processor's memory caches have different hit/miss patterns.</li>\n<li><a href=\"http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/\" rel=\"nofollow\">Some runs may get better branch prediction than others</a> (again, due to the mix of other processes running). This will cause more pipeline stalls.</li>\n</ul>\n\n<p>I would suspect that the effects I've given are given in order of decreasing strength (except that I believe Python's sort algorithm is deterministic, so the first effect is not a factor here). I also suspect that I've just scratched the surface.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>OK, for reversing a number, suppose that your typical input will be 5 digits then you can use this.</p>\n\n<pre><code>if __name__ == \"__main__\":\n from timeit import Timer\n import random\n def test(f):\n f(random.randint(10000,99999))\n\n print Timer(lambda: test(reverse_num)).timeit(number = 10000000)\n print Timer(lambda: test(reverse_num2)).timeit(number = 10000000)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T06:52:37.083",
"Id": "44963",
"Score": "0",
"body": "Thanks for answering. I thought it was never going to be answered by anyone. Just one thing. If I comment could you please reply? You never replied to any of my comments on your [last answer](http://codereview.stackexchange.com/a/28305/26426)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T06:55:50.160",
"Id": "44966",
"Score": "0",
"body": "Does this mean there is no hope of any proper timing analysis for finding better implementations of an algorithm? Large difference are obviously noticeable but I wanted to know about timing of many test cases. How can I find which one is better at test cases? How do I test small functions? How does anyone do proper timing for various test cases? How do people find that this function works better for small values and that function works for large values? I think this much questions will be able to explain my confusion. If not, please reply I'll try to elaborate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T07:39:01.733",
"Id": "44968",
"Score": "0",
"body": "I think that \"no hope\" is a bit strong. If your benchmarks are so close that sometimes they cross one another, you can probably conclude that neither approach is significantly more efficient than the other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T07:41:46.917",
"Id": "44969",
"Score": "0",
"body": "As for small functions, it helps to run the function many times, as you do. To determine how different algorithms do on small vs large inputs, the usual practice is to come up with a random function that produces small values, and test against many different small inputs, and then come up with a random function that produces large values, and test against many different large values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T07:55:43.907",
"Id": "44974",
"Score": "0",
"body": "Can you come into this [chat room](http://chat.stackexchange.com/rooms/9695/discussion-about-timing-in-python)? Otherwise the comments will be deleted due to long discussions."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T05:43:31.110",
"Id": "28629",
"ParentId": "28373",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "28629",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T15:35:22.270",
"Id": "28373",
"Score": "8",
"Tags": [
"python",
"optimization",
"unit-testing",
"timer"
],
"Title": "Timing analysis of many test cases in Python"
}
|
28373
|
<p>I'm an advanced C# programmer learning F#. As an exercise I'm porting a function that calculates the check digit of a US ABA (routing) number. Here are 2 C# implementations:</p>
<pre><code>int CalcCheckDigit(string rt)
{
var s = new[]{3,7,1,3,7,1,3,7}
.Zip(rt, (m,d) => m * int.Parse(d.ToString()))
.Sum();
return (int)Math.Ceiling(s / 10.0) * 10 - s;
}
int CalcCheckDigitOldSchool(string rt)
{
int[] mults = new[]{3,7,1,3,7,1,3,7};
int s = 0;
for (int i = 0; i < mults.Length; i++)
{
int digit = int.Parse(rt[i].ToString());
s += digit * mults[i];
}
double nextMultOfTen = Math.Ceiling(s / 10.0) * 10;
return (int)nextMultOfTen - s;
}
</code></pre>
<p>And here's my crack at it with F#:</p>
<pre><code>let calcCheckDigit rt =
let s =
rt
|> Seq.zip [3;7;1;3;7;1;3;7]
|> Seq.map (fun (a,b) -> a * int(string b))
|> Seq.sum |> float
int (ceil (s / 10.0) * 10.0 - s)
</code></pre>
<p>How might the F# version be improved?</p>
|
[] |
[
{
"body": "<p>This isn't really F# specific because you could do the same thing in your C# code, but converting each character to a string so you can parse it as an integer seems inefficient to me. I'd be inclined to use <a href=\"http://msdn.microsoft.com/en-us/library/e7k33ktz.aspx\" rel=\"noreferrer\">Char.GetNumericValue</a> instead.</p>\n\n<p>Also, you could eliminate a step in your method chain by using <a href=\"http://msdn.microsoft.com/en-us/library/ee340271.aspx\" rel=\"noreferrer\">Seq.sumBy</a> instead of Seq.map + Seq.sum.</p>\n\n<p>I might write your code like this:</p>\n\n<pre><code>open System\n\nlet calcCheckDigit rt =\n let s = \n rt\n |> Seq.map (Char.GetNumericValue >> int)\n |> Seq.zip [3;7;1;3;7;1;3;7]\n |> Seq.sumBy (fun (a,b) -> a * b)\n |> float\n (s / 10.0 |> ceil) * 10.0 - s |> int\n</code></pre>\n\n<p>In my opinion, separating out the \"convert a character to an integer\" from the multiplication makes it easier to read. I'm using the function-composition operator to join together the <code>Char.GetNumericValue</code> and <code>int</code> functions in sequence, and then passing the resulting combined function into <code>Seq.map</code>.</p>\n\n<p>On the last line, it's a little ambiguous just what value is being passed into <code>ceil</code>. It would be easy for someone unfamiliar with the code to assume that the result of the entire expression <code>(s / 10.0) * 10.0 - s</code> is being passed to <code>ceil</code>. I would be inclined to write that as I did above (obviously) but if you don't like that use of the pipe operator then I think this would also be a little more clear: <code>int ((ceil (s / 10.0)) * 10.0 - s)</code>. Personally I'm not a fan of lots of nested parens, but to each their own.</p>\n\n<p>(Before I edited this post, I mistakenly assumed exactly what I just mentioned, and so I wrote <code>(s / 10.0) * 10.0 - s |> ceil |> int</code>. Then I realized it wouldn't produce the same output as the C# version.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T00:40:56.340",
"Id": "44532",
"Score": "0",
"body": "I would be careful about `char.GetNumericValue()`, because it accepts characters like ½ or Ⅻ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T05:06:40.097",
"Id": "44535",
"Score": "0",
"body": "Well I would hope that before one calls a function that calculates the check digit of a US ABA (routing) number, one would validate that the user input is all integers..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T22:21:16.213",
"Id": "28387",
"ParentId": "28378",
"Score": "7"
}
},
{
"body": "<p>I like Joel Mueller's answer the best, but here is my alternative solution that is similar to your second C# sample and would probably be more efficient than map*zip*sum:</p>\n\n<pre><code>let calcCheckDigit (rt : string) =\n let lookup = [| 3.;7.;1.;3.;7.;1.; 3.; 7. |]\n let s = Array.sum [| for i in 0 .. rt.Length-1 -> lookup.[i] * (float << string) rt.[i] |]\n int ((ceil (s / 10.0)) * 10.0 - s)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T23:35:13.040",
"Id": "35107",
"ParentId": "28378",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T18:46:19.393",
"Id": "28378",
"Score": "6",
"Tags": [
"c#",
"f#"
],
"Title": "Learning F# - Porting C# Function to F#"
}
|
28378
|
<p>Before I get started I have spent much time searching for the answer. It seems the most referenced way is here, <a href="http://www.developer.com/print.php/3794146" rel="nofollow">http://www.developer.com/print.php/3794146</a>. I am not quite understanding how to optimize. See below.</p>
<pre><code>public void CalculateStdDev()
{
arrayItemCount = 0; // integer
average = 0; // double
double itemsSum = 0;
double[] values = new double[DS.Tables[0].Rows.Count];
double[] deviations = new double[DS.Tables[0].Rows.Count];
double[] squareDeviations = new double[DS.Tables[0].Rows.Count];
double squareDeviationsSum = 0;
double squareDeviationsAverage = 0;
stdDeviation = 0; // double
for (int i = 0; i < DS.Tables[0].Rows.Count; i++)
{
if (DS.Tables[0].Rows[i].ItemArray.GetValue(1).ToString() != "")
{
values[arrayItemCount] = Convert.ToDouble(DS.Tables[0].Rows[i].ItemArray.GetValue(1));
itemsSum += Convert.ToDouble(DS.Tables[0].Rows[i].ItemArray.GetValue(1));
arrayItemCount += 1;
}
}
average = itemsSum / arrayItemCount;
for (int i = 0; i < arrayItemCount; i++)
{
deviations[i] = Math.Abs(values[i] - average);
squareDeviations[i] = deviations[i] * deviations[i];
squareDeviationsSum += squareDeviations[i];
}
squareDeviationsAverage = squareDeviationsSum / Convert.ToDouble(arrayItemCount - 1);
stdDeviation = Math.Round(Convert.ToDouble(Math.Sqrt(squareDeviationsAverage)), 3);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T19:20:54.810",
"Id": "44499",
"Score": "0",
"body": "This question shows a pretty simple way, provided you first create a IEnumerable<double> from your values. http://stackoverflow.com/a/3141731/736079"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T19:56:23.770",
"Id": "44501",
"Score": "0",
"body": "Or this: http://stackoverflow.com/a/6252351/736079"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:29:41.170",
"Id": "44511",
"Score": "0",
"body": "Thanks Jesse,\nwas able to remove 12 lines of original code using the first link you provided."
}
] |
[
{
"body": "<p>If the method calculate standard desviation, it should return the value, not assign a global variable or instance variable.</p>\n\n<p>Regards, </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T06:31:15.683",
"Id": "28399",
"ParentId": "28379",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T19:11:26.293",
"Id": "28379",
"Score": "1",
"Tags": [
"c#",
"optimization",
"algorithm"
],
"Title": "How can I simplify the following code that calculates standard deviation"
}
|
28379
|
<p>I created a <code>Queue</code> object when <a href="https://stackoverflow.com/a/17528961/561731">answering</a> <a href="https://stackoverflow.com/q/17528749/561731">this question</a> and I was wondering if it could do with some improvement.</p>
<p>Here is the current code:</p>
<pre><code>var Queue = (function () {
Queue.prototype.autorun = true;
Queue.prototype.running = false;
Queue.prototype.queue = [];
function Queue(autorun) {
if (typeof autorun !== "undefined") {
this.autorun = autorun;
}
this.queue = []; //initialize the queue
};
Queue.prototype.add = function (callback) {
var _this = this;
//add callback to the queue
this.queue.push(function () {
var finished = callback();
if (typeof finished === "undefined" || finished) {
// if callback returns `false`, then you have to
// call `next` somewhere in the callback
_this.dequeue();
}
});
if (this.autorun && !this.running) {
// if nothing is running, then start the engines!
this.dequeue();
}
return this; // for chaining fun!
};
Queue.prototype.dequeue = function () {
this.running = false;
//get the first element off the queue
var shift = this.queue.shift();
if (shift) {
this.running = true;
shift();
}
return shift;
};
Queue.prototype.next = Queue.prototype.dequeue;
return Queue;
})();
</code></pre>
<p>Is there anything that I can expand on or improve in this Object? <br/>
Should anything be changed?</p>
|
[] |
[
{
"body": "<p>Overall, the code is quite simple. That's a good thing already.</p>\n\n<p>Some things can be improved though:</p>\n\n<ul>\n<li><p>Always create the <code>autorun</code> property. It will help your compiler. See <a href=\"https://codereview.stackexchange.com/questions/28344/should-i-put-default-values-of-attributes-on-the-prototype-to-save-space\">here</a> for more details. Besides, it's simpler to read. Just go with this:</p>\n\n<pre><code>function Queue(autorun) {\n this.autorun = autorun;\n}\n</code></pre></li>\n</ul>\n\n<p>On another note, adding the properties on the prototype is just as bad, read the link I already showed to understand why.</p>\n\n<ul>\n<li>Maybe it's only me, but the first lines are disturbing because they're before the \"class\" declaration. So it looks like they belong to the external object, while they actually belong to the hoisted function.</li>\n<li>You don't need <code>typeof variable === \"undefined\"</code>. <code>variable === undefined</code> is enough because you know for sure the identifier exists.</li>\n<li><code>var shift = this.queue.shift();</code> w-w-w-what's this variable name?! You probably mean <code>var first ...</code>. Use descriptive variable names.</li>\n<li>I'm not sure you want to return <code>shift</code> in <code>dequeue</code>. Don't you mean <code>this</code>? Chaining is fun!</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:14:09.957",
"Id": "44503",
"Score": "0",
"body": "1 -- Well I want the option for a user **not** to pass in the `autorun` option (so by default it will be true). \n\n2 -- And the variables on the prototype are hoisted to the function call within the scope -- At least I believe that they are.\n\n3 -- Yes, My variable naming is terrible\n\n4 -- CHAINING IS **FUN** \n\n2.5 --- I find the speed of `typeof` vs the other route is minimal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:15:50.180",
"Id": "44504",
"Score": "0",
"body": "@Neal 1. It's ok, the property will just be `undefined`. But at least the generated class (by the compiler) will be the same no matter how you instantiate the object. 2. They are. But it's just wrong on a readability level. Principle of least surprise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:19:03.137",
"Id": "44505",
"Score": "0",
"body": "If the property is undefined then my check if `autorun` is true will fail in the `add` function so the queue will never autorun unless you explicitly tell it to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:20:56.997",
"Id": "44506",
"Score": "0",
"body": "@Neal if you don't pass anything, it will be `undefined`. If you pass `true`, it will be `true`. So your `add` function will work just as well. Or is there something else I'm not getting?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:21:26.990",
"Id": "44507",
"Score": "0",
"body": "Yes but `if(undefined){/*will never get here*/}` --> Which I do not want. I want, be default for the queue to **automatically** run."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:24:47.467",
"Id": "44508",
"Score": "0",
"body": "@Neal that's not what your code currently does though. Right now, it will be `undefined` by default, and something else if you pass it something else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:28:25.830",
"Id": "44510",
"Score": "0",
"body": "Right now if you pass **nothing** then autorun will be `true`. Which is what I wanted, and what is does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:32:55.530",
"Id": "44512",
"Score": "1",
"body": "OH I SEE ITS BECAUSE OF THE PROTOTYPE. Oh god, change this. See how much you had to say to convince me how the code actually works? You just had the best proof that your code is definitely not readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:34:42.990",
"Id": "44513",
"Score": "0",
"body": "You could change `autorun` to `manualrun`, reversing the sense. Then you could just do `this.manualrun = !!manualrun` in the constructor and dispense with the property on the prototype. And you'd have to change the check for `this.autorun` in `.add`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:36:28.233",
"Id": "44514",
"Score": "0",
"body": "Or you could just handle this logic in the constructor and set `autorun` to the right value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:38:34.540",
"Id": "44515",
"Score": "0",
"body": "Sure. I guess it depends on whether you want a default parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T21:45:48.400",
"Id": "44517",
"Score": "0",
"body": "@FlorianMargaine nothing to do with prototype... I want people to be able to do `new Queue;` without explicitly having to say `new Queue(true);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T22:02:06.390",
"Id": "44518",
"Score": "0",
"body": "I am changing the `queue` variable in the class out of the prototype."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:10:52.170",
"Id": "28381",
"ParentId": "28380",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T19:58:05.297",
"Id": "28380",
"Score": "4",
"Tags": [
"javascript",
"queue"
],
"Title": "Javascript Queue Object"
}
|
28380
|
<p>I wrote this class to ensure that anything done in any of my worker threads can be displayed on the GUI via events, but I ran into non-thread-safe problems.</p>
<p>This class should take an action or a function with one or no params, i.e. the event delegate.</p>
<p>Is this code actually thread-safe, and, how could it be improved upon (simplifying the 4 bodies into two or one)?</p>
<p>The class is defined as:</p>
<pre><code>private class ThreadSafeCall
{
public void Call(Action action)
{
try
{
ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
if (invokable != null && invokable.InvokeRequired == true)
{
invokable.Invoke(action, null);
}
else
{
action();
}
}
catch (Exception)
{
}
}
public void Call(Action<object> action, object param)
{
try
{
ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
if (invokable != null && invokable.InvokeRequired == true)
{
invokable.Invoke(action, new object[] { param });
}
else
{
action(param);
}
}
catch (Exception)
{
}
}
public object Call(Func<object> action)
{
try
{
ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
if (invokable != null && invokable.InvokeRequired == true)
{
return invokable.Invoke(action, null);
}
else
{
return action();
}
}
catch (Exception)
{
}
return null;
}
public object Call(Func<object, object> action, object param)
{
try
{
ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
if (invokable != null && invokable.InvokeRequired == true)
{
return invokable.Invoke(action, new object[] { param });
}
else
{
return action(param);
}
}
catch (Exception)
{
}
return null;
}
}
</code></pre>
<p>It is used:</p>
<pre><code>(new ThreadSafeCall()).Call(() => { onCompleteHandle(); });
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T22:04:33.923",
"Id": "44519",
"Score": "7",
"body": "`catch (Exception)\n {\n\n }` is a bad, bad idea."
}
] |
[
{
"body": "<p>Your specific usage seems to be thread-safe. But it's relying on implementation details (about lambdas), which you shouldn't do. It's also <strong>extremely</strong> easy to get it wrong.</p>\n\n<p>I believe the only way it will work is if you're closing over <code>this</code>, but not any other variables and that <code>this</code> is a type that properly implements <code>ISynchronizeInvoke</code> (like a WinForms form or control). This means that it won't work if:</p>\n\n<ul>\n<li>you're calling it from a <code>static</code> method</li>\n<li>you're only calling a <code>static</code> method from inside the lambda</li>\n<li>you're closing over some local variable or parameter</li>\n<li>you're calling it from another class</li>\n</ul>\n\n<p>Because of that, I would never use code like this.</p>\n\n<p>I think that you should just use <code>Invoke()</code> directly, something like:</p>\n\n<pre><code>Invoke(new Action(onCompleteHandle));\n</code></pre>\n\n<p>If you don't like that you need to specify the delegate type, you could write a couple of simple extension methods like:</p>\n\n<pre><code>public static void Invoke(this ISynchronizeInvoke target, Action action)\n{\n target.Invoke(action, null);\n}\n</code></pre>\n\n<p>and then use it like this (that <code>this</code> is required):</p>\n\n<pre><code>this.Invoke(onCompleteHandle);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T23:45:14.483",
"Id": "28389",
"ParentId": "28384",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T21:42:03.277",
"Id": "28384",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"thread-safety"
],
"Title": "Invoking worker threads"
}
|
28384
|
<p>I started learning my first functional programming language (Haskell) yesterday and I have been working on a lexer for an expression evaluator. The lexer is now basically feature complete, but I'm not sure what I can do to improve the code.</p>
<pre><code>import Data.Char
import Data.List
data TokenType = Identifier |
RealNumberLiteral |
PlusSign |
MinusSign |
Asterisk |
ForwardSlash |
Caret |
LeftParenthesis |
RightParenthesis
deriving (Show)
data Token = Token TokenType String
deriving (Show)
read_token :: String -> Token
read_token [] = error "Unexpectedly reached the end of the source code while reading a token."
read_token source_code@(next_character:_)
| isSpace next_character = read_token (dropWhile isSpace source_code)
| isAlpha next_character = Token Identifier (takeWhile isAlpha source_code)
| isDigit next_character = let token_lexeme = (takeWhile (\x -> isDigit x || x == '.') source_code)
in let period_count = length (filter (=='.') token_lexeme)
in Token RealNumberLiteral (if period_count <= 1
then token_lexeme
else error "There can only be one period in a real number literal.")
| next_character == '+' = Token PlusSign "+"
| next_character == '-' = Token MinusSign "-"
| next_character == '*' = Token Asterisk "*"
| next_character == '/' = Token ForwardSlash "/"
| next_character == '^' = Token Caret "^"
| next_character == '(' = Token LeftParenthesis "("
| next_character == ')' = Token RightParenthesis ")"
| otherwise = error ("Encountered an unexpected character (" ++ [next_character] ++ ") while reading a token.")
append_read_tokens :: [Token] -> String -> [Token]
append_read_tokens tokens source_code
| null source_code = tokens
| isSpace (head source_code) = append_read_tokens tokens (dropWhile isSpace source_code)
| otherwise = let next_token@(Token next_token_type next_token_lexeme) = read_token source_code
in append_read_tokens (tokens ++ [next_token]) (drop (length next_token_lexeme) source_code)
tokenize :: String -> [Token]
tokenize [] = []
tokenize source_code = append_read_tokens [] source_code
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>No need of <code>TokenType</code>: <code>data Token = Identifier String | RealNumberLiteral String | PlusSign ...</code></p></li>\n<li><p>No need of nested <code>let</code> statements, see <a href=\"http://learnyouahaskell.com/syntax-in-functions#let-it-be\" rel=\"nofollow\">http://learnyouahaskell.com/syntax-in-functions#let-it-be</a></p></li>\n<li><p>camelCase naming is preferred everywhere.</p></li>\n<li><p>generally it is more efficient to aggregate lists using cons (<code>:</code> operator), and <code>reverse</code> at the end, if needed. It is about <code>tokens ++ [next_token]</code> fragment.</p></li>\n<li><p><code>read_token</code> could return a tuple of token and the rest string, no need to <code>drop (length next_token_lexeme) source_code</code> after that.</p></li>\n</ul>\n\n<p>Note, I didn't inspect code logic at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T04:22:49.930",
"Id": "28538",
"ParentId": "28385",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28538",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T22:06:35.757",
"Id": "28385",
"Score": "2",
"Tags": [
"parsing",
"haskell"
],
"Title": "Lexer for expression evaluator"
}
|
28385
|
<p>This is my Fibonacci generator:</p>
<pre><code>package main
import "fmt"
func main() {
for i, j := 0, 1; j < 100; i, j = i+j,i {
fmt.Println(i)
}
}
</code></pre>
<p>It's working, but I don't know how I can improve it, so I'd like more expert approaches to solving it.</p>
|
[] |
[
{
"body": "<p>Your code is quite nice, and can't really be improved. However, let's put the “generator” back into the code.</p>\n\n<p>Go has <em>channels</em> which can be used to write elegant generators/iterators. We spawn of a goroutine that fills the channel with the fibonacci sequence. The main thread then takes as many fibonacci numbers as it needs.</p>\n\n<p>So let's write a function <code>fib_generator</code> that returns a channel to the fibonacci sequence:</p>\n\n<pre><code>func fib_generator() chan int {\n c := make(chan int)\n\n go func() { \n for i, j := 0, 1; ; i, j = i+j,i {\n c <- i\n }\n }()\n\n return c\n}\n</code></pre>\n\n<p>We return a <code>chan int</code>. Here, we use an unbuffered channel. You may want to introduce a bit of buffering, e.g. <code>make(chan int, 7)</code>.</p>\n\n<p>Next, we spawn a goroutine. This contains your code, but instead of printing the numbers, we fill the channel with them. Note that the generator does not have a termination condition.</p>\n\n<p>The unusual syntax</p>\n\n<pre><code>go func() { ... }()\n</code></pre>\n\n<p>is the standard way to start a goroutine. Because the function literal is a closure over the channel <code>c</code>, we can run multiple generators concurrently.</p>\n\n<p>Our <code>main</code> will look like</p>\n\n<pre><code>func main() {\n c := fib_generator()\n for n := 0; n < 12 ; n++ {\n fmt.Println(<- c)\n }\n}\n</code></pre>\n\n<p>That is, we create a new generator, and then pull the first 12 values from the channel. We cannot write <code>for i := range c { ... }</code>, because the fibonacci generator does not terminate.</p>\n\n<p>As I said, we can have multiple generators concurrently:</p>\n\n<pre><code>func main() {\n c1 := fib_generator()\n c2 := fib_generator()\n\n // read first 12 numbers from 1st channel\n for n := 0; n < 10 ; n++ { fmt.Print(\" \", <- c1) }\n fmt.Println()\n\n // read first 12 numbers from 2nd channel. The same.\n for n := 0; n < 10 ; n++ { fmt.Print(\" \", <- c2) }\n fmt.Println()\n\n // read next 5 numbers from 1st channel.\n for n := 0; n < 5 ; n++ { fmt.Print(\" \", <- c1) }\n fmt.Println()\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code> 0 1 1 2 3 5 8 13 21 34\n 0 1 1 2 3 5 8 13 21 34\n 55 89 144 233 377\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:33:52.693",
"Id": "75283",
"Score": "1",
"body": "That is elegant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T13:12:23.287",
"Id": "86859",
"Score": "0",
"body": "I think the most elegant solution would be to use select on the created fibonacci channels and either append the latest generated fibonacci number to particular slice or print it per channel on which it was received. @amon 's example above is imho seemingly concurrent as particular ```fmt.Print()``` functions will be blocking until the number is generated so the particular generator loops will be done sequentially one after another."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T13:42:59.300",
"Id": "86861",
"Score": "0",
"body": "@gyre Yes, but do note that generating the next number is so cheap that there is no blocking to seriously consider. Anyway, I was not trying to achieve true parallelism here, but only to show a way to easily handle infinite streams with Go. Coroutines are a natural choice for implementing a [generator](https://en.wikipedia.org/wiki/Generator_(computer_science)) abstraction. As a result the control flow is in fact concurrent (whenever an item is consumed, control is transferred to the generator), but it does not execute in parallel – these are different things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T15:26:55.157",
"Id": "86867",
"Score": "0",
"body": "I totally agree with you. And I'm sorry if my comment made you feel otherwise! I just wanted to make sure that whoever reads this answer has a bigger picture - thanks to your answer to my comment all should be clear now. As for concurrency vs. parallelism we could spend ages about arguing what means what. I tend to agree with Rob Pike's interpretation which he explained in one of his excellent [talks](http://vimeo.com/49718712)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-20T01:26:18.527",
"Id": "328939",
"Score": "0",
"body": "me: wtf, how does go not have a concept of generators/iterables? How do you generate an infinite sequence?! Outrageous! (does googling finds this) ... ok, that's cool."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T23:15:03.940",
"Id": "28445",
"ParentId": "28386",
"Score": "19"
}
},
{
"body": "<p>Your Fibonacci generator works (and looks) great but only for values below 2147483647 (i.e. 2<sup>31</sup>-1).</p>\n\n<p>To work with larger numbers, we can use the math/big package:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n F1 := big.NewInt(0)\n F2 := big.NewInt(1)\n for {\n F1.Add(F1, F2)\n F1, F2 = F2, F1\n\n // print to standard output\n fmt.Printf(\"%v\\n\", F1)\n }\n}\n</code></pre>\n\n<p><a href=\"https://play.golang.org/p/KZPgRYVJsL\" rel=\"nofollow noreferrer\">Run in Playground</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-05T16:30:56.870",
"Id": "345892",
"Score": "1",
"body": "Does it make sense to explain that [2,147,483,647](https://en.wikipedia.org/wiki/2,147,483,647) is the 8th Mersenne prime number, and the maximum positive value for 32-bit signed binary integers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-07T01:42:50.137",
"Id": "346146",
"Score": "0",
"body": "Yes, great _addition_!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-05T07:36:56.190",
"Id": "182049",
"ParentId": "28386",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28445",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T22:16:32.657",
"Id": "28386",
"Score": "10",
"Tags": [
"mathematics",
"go",
"fibonacci-sequence"
],
"Title": "Fibonacci generator with Golang"
}
|
28386
|
<p>I am planing to create a small game using C#, so I've decided to create a small logic for that game. I immediately opened Visual studio and started to create some classes to hold on the player's data, so I came up with something like this. However, I don't know whether or not there is better ways to achieve such thing rather than this.</p>
<p><strong>The Player class</strong></p>
<pre><code>public class Player
{
/// <summary>
/// Player name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Buildings the player already have...
/// </summary>
public Building[] Buildings { get; set; }
/// <summary>
/// Player money.
/// </summary>
public int Money { get; set; }
}
</code></pre>
<p><strong>The Building class</strong></p>
<pre><code>public class Building
{
/// <summary>
/// The building type, Academy, Barracks, Tower, GlassHall... etc
/// </summary>
public BuildingType Type { get; set; }
/// <summary>
/// Requirements for that building.
/// </summary>
public Building[] Requirements { get; set; }
/// <summary>
/// Needed money for that building.
/// </summary>
public int NeededMoney { get; set; }
/// <summary>
/// The buildings level... should be updated after the building is already built.
/// </summary>
public int Level { get; set; }
}
</code></pre>
<p><strong>The Building types</strong></p>
<pre><code>public enum BuildingType
{
Academy,
Barracks,
Tower,
GlassHall
}
</code></pre>
<p><strong>Main()</strong></p>
<pre><code>static void Main()
{
var player = new Player
{
Name = "SweetPlayer...",
Money = 50000,
//Buildings the player already has...
Buildings = new[]
{
new Building {Level = 5, Type = BuildingType.GlassHall},
new Building {Level = 5, Type = BuildingType.Barracks},
new Building {Level = 5, Type = BuildingType.Tower}
}
};
var buildingTobuild = new Building
{
Level = 1,
NeededMoney = 40000,
Type = BuildingType.Tower,
//Buildings the player needs in order to establish this building...
Requirements = new[]
{
new Building {Level = 5, Type = BuildingType.GlassHall},
new Building {Level = 5, Type = BuildingType.Academy},
new Building {Level = 5, Type = BuildingType.Barracks}
}
};
//Check whether the player has enough money.
if (player.Money >= buildingTobuild.NeededMoney)
{
//We have enough money for the building so let's check if the player meets the requirements...
var neededBuildings = new ArrayList();
foreach (var requirement in buildingTobuild.Requirements)
{
//The player already has this requirement... so continue...
if (player.Buildings.ToList().Find(element => element.Type == requirement.Type && element.Level >= requirement.Level) != null)
continue;
neededBuildings.Add(requirement);
}
//if the list contains more the 0 elements so the player does not meet the requirements... Print the required things for the building.
if (neededBuildings.Count > 0)
{
//a small counter to print the number of the element.
int counter = 0;
Console.WriteLine("Sorry you need those buildings in order to build the \"{0}\" : ", buildingTobuild.Type);
Console.WriteLine();
foreach (var neededBuilding in neededBuildings)
{
Console.WriteLine("{0} - {1}", counter, ((Building) neededBuilding).Type);
counter++;
}
}
else
{
player.Money = player.Money - buildingTobuild.NeededMoney;
Console.WriteLine("Successfully built the \"{0}\" your money now = {1}", buildingTobuild.Type ,player.Money);
}
}
else
{
Console.WriteLine("Sorry the \"{0}\" needs {1} money to be built... You need {2} more", buildingTobuild.Type, buildingTobuild.NeededMoney, buildingTobuild.NeededMoney - player.Money);
}
Console.Read();
}
</code></pre>
<p>I have commented everything out for you to know what is going on.</p>
|
[] |
[
{
"body": "<p>It's hard to review code like this, because it's very obvious it's not “real” code. But I'll try:</p>\n\n<ol>\n<li><p>All your “classes” are basically just C structs. You should probably add some constructors and make some of the setters <code>private</code>. You should also move some of the logic from <code>Main()</code> to instance methods on those classes.</p></li>\n<li><p>It feels wrong that you need to have a <code>Building</code> to know how much it costs and what its requirements are. It might make sense to have two separate classes for that, e.g. <code>BuildingBlueprint</code> and <code>Building</code>, or something like that, especially if you can have more than one building of the same type in the game.</p></li>\n<li><p>Array is a type that's natural for computers, but it often doesn't make much sense to have in your object model. If you want a mutable collection, use <code>IList<T></code> (or at least <code>List<T></code>). If you want a collection that can't be changed from the outside, use <code>IEnumerable<T></code> (or <code>IReadOnlyList<T></code>).</p></li>\n<li><p>If you continue working on this, you'll probably need specific behavior for each kind of <code>Building</code>. Be prepared to use derived classes for that.</p></li>\n<li><p>Don't use <code>ArrayList</code>, it's there just for backwards compatibility with .Net 1.0. Use <code>List<T></code> (in your case <code>List<Building></code>) instead.</p></li>\n<li><p>The loop could be written using LINQ as something like:</p>\n\n<pre><code>var neededBuildings = buildingTobuild.Requirements.Where(\n required => !player.Buildings.Any(\n built => built.Type == required.Type && built.Level >= required.Level))\n .ToList();\n</code></pre>\n\n<p>This is still O(n^2), but that probably doesn't matter.</p>\n\n<p>In any case, you should use better variable names, something specific like <code>built</code> is much better than the overly general <code>element</code>.</p></li>\n<li><p>Instead of using <code>foreach</code> with a counter, I think a <code>for</code> loop is usually better.</p></li>\n<li><p>You usually shouldn't print the value of an <code>enum</code> (like <code>GlassHall</code>) directly to the user, you should instead print it using normal English rules (like <code>Glass hall</code>).</p></li>\n<li><p>If you want to subtract some value from a property, you can use <code>-=</code>.</p></li>\n<li><p>If you separated your code into smaller methods (possibly on your classes, see #1), you could use early return to avoid deep nesting and code that's difficult to follow. E.g.:</p>\n\n<pre><code>if (player.Money < buildingTobuild.NeededMoney)\n{\n Console.WriteLine(\"Sorry, the \\\"{0}\\\" needs {1} money to be built.\", …);\n return;\n}\n\n// for the rest of the method, you know there is enough money\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T00:35:37.530",
"Id": "44531",
"Score": "0",
"body": "Well that was a well detailed answer... thank you very much and i will take all of your advices into account."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T08:18:30.173",
"Id": "44544",
"Score": "0",
"body": "A further refactoring on no 6, would be implementing equality for `Building`s. `var neededBuildings = new HashSet(buildingTobuild.Requirements).Except(player.Buildings)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T09:56:39.187",
"Id": "44551",
"Score": "0",
"body": "@abuzittingillifirca I don't think that makes sense here. You need buildings with the same *or higher* level. And that's not an equivalence relation, so a `HashSet` wouldn't work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:38:03.817",
"Id": "44572",
"Score": "0",
"body": "@svick Right. I only realized it's a `>=` instead of a `==` after you pointed it out. Then: `var neededBuildings = buildingTobuild.Requirements.Where(required => player.GetBuiltLevel(required.Type) < required.Level)`. Which suggests `Player.Buildings` and `Building.Requirements` should be `Dictionary<BuildingType, int>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T20:03:18.363",
"Id": "44601",
"Score": "0",
"body": "@abuzittingillifirca Yeah, that's not a bad idea."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T00:21:19.800",
"Id": "28390",
"ParentId": "28388",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "28390",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T22:57:06.657",
"Id": "28388",
"Score": "1",
"Tags": [
"c#",
"game"
],
"Title": "Small building game logic"
}
|
28388
|
<p>I've built a basic image slide show with jQuery, nothing particularly fancy, but there a few specific things I wanted it to do and I managed it - I just don't think I did it the best way possible. Hoping to get some pointers on where I can improve it.</p>
<p>So the basic visual structure is:</p>
<pre><code>_____________________________________________________
|___Link 1___|___Link 2___|___Link 3___|___Link 4___|
| |
| |
| Big Image relating to active link |
| ___________________|
| | Little text |
|_______________________________|___box overlayed___|
______________ ______________ _____________
| Related | | RT2 | | RT3 |
| topic 1 | | | | |
|____________| |____________| |___________|
</code></pre>
<p>There are four 'Big Images', and 4 sets of related topics (4 x 3 related topics). Each image and set of related topics are attached to one of the links. So, attached to each link, is a 'slide set' containing one image, text overlay, and three related topics.</p>
<p>Also note that the links are the sites main navigation.</p>
<p>Its functionality is:</p>
<ol>
<li>Starting from link 1, cycle through link 2, 3 and 4 and back to 1, infinitely, displaying each slide set for 45 seconds.</li>
<li>If the user hovers over a link, change to it's corresponding slide set, and continue the slideshow from there.</li>
</ol>
<p>So now that you now what it looks like and what it's supposed to do, let me explain how I've structured it in my HTML:</p>
<p>I've kept the main navigation links completely separate from the rest of the slideshow, to ensure it displays even if there's a browser issue ruining the slideshow.</p>
<pre><code><ul class="navbar">
<li class="navlink selected" title="link1">Link 1</li>
<li class="navlink" title="link2">Link 2</li>
<li class="navlink" title="link3">Link 3</li>
<li class="navlink" title="link4">Link 4</li>
</ul>
</code></pre>
<p>The rest of the slideshow is contained within a separate parent element. There are four structures identical to this <strong>except that</strong> only one <code>.slideset</code> will have the class <code>.current</code> at any one time <strong>and</strong> each <code>.slideset</code> has an <code>ID</code> identical to it's corresponding links title and content.</p>
<p>I chose to keep each slide contained within its own parent element, that way, only the parent element needs to be changed.</p>
<pre><code><div class="slideset current" id="link1">
<div class="slideshow">
<div class="slidetext">
</div>
</div>
<ul class="slidedetails">
<li class="three">
<h2 class="valuetitle ctrtext">
Related Topic 1
</h2>
<p class="valuetext dt">
Lorem to da Ipsum
</p>
</li>
<li class="three">
<h2 class="valuetitle ctrtext">
Related Topic 2
</h2>
<p class="valuetext dt">
Lorem to da Ipsum
</p>
</li>
<li class="three">
<h2 class="valuetitle ctrtext">
Related Topic 3
</h2>
<p class="valuetext dt">
Lorem to da Ipsum
</p>
</li>
</div>
</code></pre>
<p>The 'Big Image' is applied as a background-image to the <code>.slideshow</code> div.</p>
<p>Now for the magic:</p>
<pre><code>$(document).ready(
//Set the frame rate of the slideshow and call the function
setInterval(changeSlide, 45000)
);
function changeSlide(){
/* remove the class that shows the current link as the active slide */
$(".navlink").removeClass("selected");
/* create an array containing the names of each link */
allSlides = ["link1", "link2", "link3", "link4"]
/* find out which slide is currently showing and store it in currentSlide variable */
currentSlide = $(".slideset").closest(".current");
/* get the ID of the slide that's currently showing and store it in variable compare */
compare = $(currentSlide).attr("id");
/* compare the current slide with the array to find out which one it is, and then set the next slide target as a variable named nextSlide */
if(compare === allSlides[0])
{
nextSlide = 1
}
else if(compare === allSlides[1])
{
nextSlide = 2
}
else if(compare === allSlides[2])
{
nextSlide = 3
}
else if(compare === allSlides[3])
{
nextSlide = 0
}
/* find the right slide based on number from if statement, set it as target variable */
target = allSlides[nextSlide]
/* add # to create a string of the ID of the target slide and set it as variable nextTarget */
nextTarget = ("#" + target)
/* define function for changing the slide */
slideTransition = function(){
/* Hide current slides */
$(".slideset").removeClass("current")
.hide();
/* Show the next slides */
$(nextTarget).fadeIn("fast")
.addClass("current");
};
/* create string of target link that needs to change */
var navchange = $(".navlink" + "[title=" + "'" + target + "'" + "]");
/* add highlight to new current link */
$(navchange).addClass("selected");
/* change the slide! */
slideTransition()
}
$(".navbar").on("mouseenter" || "click", ".navlink", function (){
//change the current link to be front tab
$(".navlink").removeClass("selected");
$(this).addClass("selected");
//Find the title of the link currently being hovered on
var hoveredlink = $(this).attr("title");
//add the selector # and concatenate
var targetslides = ("#" + hoveredlink).toString();
//get the classes of the link in focus
var grabtarget = $(targetslides).attr("class");
//Parse to a string for comparison
var isitONalready = grabtarget.toString();
console.log(isitONalready)
//Possible variations returned as grabtarget
itISonalready = "slideset current"
itISonalready2 = "slideset .current"
itISonalready3 = ".slideset .current"
//If it's already visible
if (isitONalready === itISonalready || isitONalready === itISonalready2 || isitONalready === itISonalready3){
console.log("It is on already")
return;
}
//If it isn't visible
else if (isitONalready !== itISonalready && isitONalready !== itISonalready2 && isitONalready !== itISonalready3){
//Fade out current slides
$(".slideset").removeClass("current")
.hide();
//find the slides we want to show
correctslides = $(".slideset").closest(targetslides);
//show the slides
$(correctslides).addClass("current")
.fadeIn("fast");
}
});
</code></pre>
<p>The part that actually changes the slide is as simple as adding the <code>.current</code> class. The <code>.slideset</code> class is set to <code>display:none;</code>, and the <code>.current</code> class has <code>display:block;</code> to override and show the element.</p>
<p>Can you suggest improvements, please? I'm sure this is not the most effective or beautiful way to achieve this.</p>
<p>To view it in action click <a href="https://www.hillsonlogistics.co.uk/" rel="nofollow">here</a>.</p>
<p>Please comment to let me know if I've left anything out. I figure you don't need the CSS, but I can provide it if necessary.</p>
|
[] |
[
{
"body": "<p>You have to think more in terms of <strong>arrays</strong></p>\n\n<p>This:</p>\n\n<pre><code> if(compare === allSlides[0])\n {\n nextSlide = 1\n }\n else if(compare === allSlides[1])\n {\n nextSlide = 2\n }\n else if(compare === allSlides[2])\n {\n nextSlide = 3\n }\n else if(compare === allSlides[3])\n {\n nextSlide = 0\n }\n</code></pre>\n\n<p>Is wrong, it should be something like</p>\n\n<pre><code>for( var i = 0 ; i < allSlides.length ; i++ )\n{\n if( compare === allSlides[i] )\n {\n nextSlide = i + 1;\n }\n}\n</code></pre>\n\n<p>Of course, now you have the problem that the last slide will point to nothing.. </p>\n\n<pre><code>for( var i = 0 ; i < allSlides.length ; i++ )\n{\n if( compare === allSlides[i] )\n {\n nextSlide = ( i == allSlides.length - 1 ) ? 0 : i+1;\n }\n}\n</code></pre>\n\n<p>Also, you have to check out your <strong>indenting</strong>, comments should be indented with the code, the code inside <code>slideTransition</code> should be indented as well. Now that I read your code again, there seems to be no point at all in capturing those 2 statements in <code>slideTransition</code>, just execute them in the main function.</p>\n\n<p>Some more thinking in terms of <strong>arrays</strong> is needed here:</p>\n\n<pre><code>//Possible variations returned as grabtarget\nitISonalready = \"slideset current\"\nitISonalready2 = \"slideset .current\"\nitISonalready3 = \".slideset .current\"\n\n//If it's already visible\nif (isitONalready === itISonalready || isitONalready === itISonalready2 || isitONalready === itISonalready3){\n console.log(\"It is on already\")\n return;\n} \n</code></pre>\n\n<p>I would hate to see this code once you have 7 slides ;P</p>\n\n<p>Finally, there are 2 more items that jshint.com found for me:</p>\n\n<ul>\n<li>You are inconsistent in applying semicolons</li>\n<li>You are declaring a ton of variables with <code>var</code> <- very bad</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:42:43.143",
"Id": "47169",
"ParentId": "28391",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "47169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T00:33:34.767",
"Id": "28391",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"optimization",
"html"
],
"Title": "Custom slide show script"
}
|
28391
|
<p>I am supposed to be creating a doubly circular linked list, but I am now have problems creating the actual linked list. Is there a problem with the classes? Also, for the assignment, the list is suppose to be a template class, but now I just want to get the code to work. </p>
<pre><code>#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
using namespace std;
//template <class Object>
//template <class Object>
class Node
{
//friend ostream& operator<<(ostream& os, const Node&c);
public:
Node( int d=0);
void print(){
cout<<this->data<<endl;
}
//private:
Node* next;
Node* prev;
int data;
friend class LinkList;
};
Node::Node(int d):data(d)
{
}
//template <class Object>
class LinkList
{
void create();
public:
//LinkList();
LinkList():head(NULL),tail(NULL),current(NULL)
{create();}
int base;
//LinkList(const LinkList & rhs, const LinkList & lhs);
~LinkList(){delete current;}
const Node& front() const;//element at current
const Node& back() const;//element following current
void move();
void insert (const Node & a);//add after current
void remove (const Node &a);
void print();
private:
Node* current;//current
Node* head;
Node* tail;
};
void LinkList::print()
{
Node *nodePt =head->next;
while(nodePt != head)
{
cout<<"print function"<<endl;
cout<<nodePt->data<<endl;
nodePt=nodePt->next;
}
}
//element at current
void LinkList::create()
{
current = head = tail = new Node(0);
current->next = current->prev = current;
}
const Node& LinkList::back()const
{
return *current;
}
//element after current
const Node& LinkList::front() const
{
return *current ->next;
}
void LinkList::move()
{
current = current ->next;
}
//insert after current
void LinkList :: insert(const Node& a)
{
Node* newNode= new Node();
newNode->prev=current;
newNode->next=current->next;
newNode->prev->next=newNode;
newNode->next->prev=newNode;
current=newNode;
}
void LinkList::remove(const Node& a)
{
Node* oldNode;
oldNode=current;
oldNode->prev->next=oldNode->next;
oldNode->next->prev=oldNode->prev;
delete oldNode;
}
//main file
#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
#include "LinkedList.h"
using namespace std;
int main()
{
int n;
cout<<"How many Nodes would you like to create"<<endl;
cin>>n;
LinkList list1 ;
list1.print();
for(int loop = 0;loop < n;++loop)
{
list1.insert(loop);
}
list1.print();
}
</code></pre>
|
[] |
[
{
"body": "<p>You have done the correct thing by putting a sentinel element into the list.<br>\nThis makes adding/removing and generally manipulating the list trivial because you don't need to handle NULL links in the list. </p>\n\n<p>But you have done it using a two phase create. </p>\n\n<ol>\n<li>You have to construct your list.</li>\n<li>You have to call create to initialize it.</li>\n</ol>\n\n<p>This is a very bad idea. Your object should be fully constructed at the end of the constructor. That way users can not incorrectly initialize your class.</p>\n\n<p>There is also a bug in your create. You create a node but you don;t link it to anything:</p>\n\n<pre><code>void LinkList::create()\n{\n Node start(0); // This node is destroyed at the end of the function.\n}\n</code></pre>\n\n<p>What you should be doing is:</p>\n\n<pre><code>LinkedList::LinkedList()\n : current(new Node(0, NULL, NULL))\n // , head(current) You don't actually need head/tail\n // , tail(current) since it is circular these are beside each other.\n{\n current->prev = current;\n cureent->next = current;\n}\n</code></pre>\n\n<p>Also your code can delete the sentinel and thus cause all sorts of problems. You should not allow the deletion of the sentinel and your other functions should check for a list with just a sentinel in them (this is the empty list).</p>\n\n<p>Why are you giving back references to the <code>Node</code>? This is an internal implementation detail. Return a reference to the value (or throw an exception if the list is empty). By returning a node you are binding your self to use a specific implementation (take a leaf out of the standard library and just return a reference to the value).</p>\n\n<pre><code>const Node& LinkList::back()const\n</code></pre>\n\n<p>Same comment again:</p>\n\n<pre><code>const Node& LinkList::front() const\n</code></pre>\n\n<p>Not sure I have seen this functionality in a list before. It seems to allow you to move the head around inside the list.</p>\n\n<pre><code>void LinkList::move()\n</code></pre>\n\n<p>So this is why you have to return the node above?</p>\n\n<pre><code>void LinkList :: insert(const Node& a)\n</code></pre>\n\n<p>I would rather have insert_front/insert_back/insert_at functionality.</p>\n\n<p>Remove has some issues:</p>\n\n<pre><code>void LinkList::remove(const Node& a)\n</code></pre>\n\n<p>Two problems:</p>\n\n<ol>\n<li>You don't update current (so it points at the deleted node).</li>\n<li>You allow the sentinel to be deleted.<br>\nIf you delete the last node the easy insertion/deletion breaks down.</li>\n</ol>\n\n<p>This is what I would do:</p>\n\n<pre><code>class LL\n{\n struct Node {\n int value;\n Node* next;\n Node* prev;\n Node() // Sentinel\n : next(this)\n , prev(this)\n {}\n Node(int val, Node* prev, Node* next)\n : value(val)\n , next(next)\n , prev(prev)\n {\n prev->next = this;\n next->prev = this;\n }\n ~Node()\n {\n prev->next = next;\n next->prev = prev;\n }\n };\n Node* current;\n LL()\n : current(new Node)\n {}\n ~LL()\n {\n while(!empty())\n {\n delete current->next;\n }\n delete current;\n }\n bool empty() const { return current == current->next;}\n void insert_front()\n {\n new Node(current, current->next);\n }\n void insert_back()\n {\n new Node(current->prev, current);\n }\n void delete_front()\n {\n if (!empty())\n delete current->next;\n }\n void delete_back()\n {\n if (!empty())\n delete current->prev;\n }\n int& front()\n {\n if (empty()) {throw empty_exception();}\n return current->next->value;\n }\n int& back()\n {\n if (empty()) {throw empty_exception();}\n return current->prev->value;\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-11T10:30:16.133",
"Id": "264223",
"Score": "0",
"body": "@YoungHyunYoo: Have a look at: http://codereview.stackexchange.com/a/126007/507"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T01:40:19.880",
"Id": "28393",
"ParentId": "28392",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T01:06:38.053",
"Id": "28392",
"Score": "1",
"Tags": [
"c++",
"linked-list",
"circular-list"
],
"Title": "Doubly circular link list implementation"
}
|
28392
|
<p>This is my interface, all of my transport concrete classes will be implementing this interface.</p>
<pre><code>interface ITransport
{
void Travel()
}
</code></pre>
<p>These are my existing implementation class:</p>
<pre><code>class Horse : ITransport
{
public Horse()
{
}
public void Travel()
{
Console.Writeline("I am travelling on a horse");
}
}
class Camel : ITransport
{
public Camel()
{
}
public void Travel()
{
Console.Writeline("I am travelling on a Camel");
}
}
class Ship : ITransport
{
public Ship()
{
}
public void Travel()
{
Console.Writeline("I am travelling on a Ship");
}
}
</code></pre>
<p>This is my Factory class I create instance of my transport classes from this factory class.</p>
<pre><code>class TransportFactory
{
public TransportFactory()
{
}
ITransport ProvideTransport(string transportType)
{
switch(transportType)
{
case "Camel": return Camel; break;
case "Horse": return Horse; break;
case "Ship": return Ship; break;
}
}
}
</code></pre>
<p>This is my creational class meaning I configure my client classes or consumer classes through this class:</p>
<pre><code>class ConfigurationBuilder
{
ITransport camel;
ITransport ship;
ITransport horse;
public ConfigurationBuilder()
{
TransportFactory tFactory = new TransportFactory();
horse = tFactory.ProvideTransport("horse");
camel = tFactory.ProvideTransport("camel");
ship = tFactory.ProvideTransport("ship");
}
Human ConfigureHuman()
{
return new Human(camel, ship, horse);
}
}
</code></pre>
<p>This is my client code the actual caller of these transport class:</p>
<pre><code>class Human
{
ITransport camel;
ITransport ship;
ITransport horse;
public Human(ITransport camel, ITransport ship, ITransport horse)
{
this.camel = camel;
this.ship = ship;
this.horse = horse;
}
void Travel()
{
//TransportFactory tFactory = new TransportFactory();
if(ground =="plain")
{
horse.Travel();
}
if(ground =="desert")
{
camel.Travel();
}
if(ground =="sea")
{
ship.Travel();
}
}
}
</code></pre>
<p>Now <strong>my question is</strong>
What will happen when I have a new means of traveling: such as Plane for Air and then Rocket for Space etc.</p>
<p>My Constructor will change and will keep on changing as more and more means of traveling keep on adding throughout application life time. Is this the correct design or is there a better way.</p>
<p>As for the question is considered I couldn't come up with intuitive words to explain my problem :)</p>
<p><strong>Update:</strong>
Commented TransportFactory out of Human class</p>
<p><strong>Update2:</strong></p>
<p>I guess I now understood how it will be done. I will be needing two factories now.TransportFactory which is already implemented above, the second one will be HumanFactory which will create a human but also has additional responsibility of calling travel method of appropriate ITransport.</p>
<pre><code>public class HumanFactory
{
ITransport camel;
ITransport ship;
ITransport horse;
Human _human;
Dictionary<string, ITransport> _availableTransports;
event Action<Human, string> transportRequested;
public HumanFactory(TransportFactory tFactory)
{
horse = tFactory.ProvideTransport(TransportTypes.Horse);
camel = tFactory.ProvideTransport(TransportTypes.Camel);
ship = tFactory.ProvideTransport(TransportTypes.Ship);
}
public Human ConfigureHuman()
{
if (_availableTransports == null)
{
_availableTransports = new Dictionary<string, ITransport>();
_availableTransports.Add(GroundTypes.Desert.ToString(), camel);
_availableTransports.Add(GroundTypes.Sea.ToString(), ship);
_availableTransports.Add(GroundTypes.Plains.ToString(), horse);
}
transportRequested += new Action<Human, string>(_human_transportRequested);
_human = new Human(transportRequested);
return _human;
}
void _human_transportRequested(Human human, string groundType)
{
if (_availableTransports.ContainsKey(groundType))
{
ITransport suitableTransport = _availableTransports[groundType];
suitableTransport.Travel();
}
else
{
//code for handling below conditions goes here
//I don't know what to do for this type of plain?
}
}
}
</code></pre>
<p>Here is the Human class now:</p>
<pre><code>public class Human
{
Action<Human, string> _transportRequested;
public Human(Action<Human, string> transportRequested)
{
_transportRequested = transportRequested;
}
public void Travel()
{
if (_transportRequested != null)
{
var ev = _transportRequested;
ev.Invoke(this, GroundTypes.Plains.ToString());
}
}
}
</code></pre>
<p>We will call the Human class now as:</p>
<pre><code>TransportFactory tFactory=new TransportFactory();
HumanFactory humanFactory = new HumanFactory(tFactory);
Human human = humanFactory.ConfigureHuman();
human.Travel();
</code></pre>
<p>One More thing: I guess I should be having a lock in the HumanFactory class in _human_transportRequested method? In case there is a multithreaded scenario.
I guess now my code is following Law of Demeter :)</p>
<p>Special Thanks to Nik( for that marvelous solution) and Gleb( for those wonderful videos)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T08:07:47.367",
"Id": "44543",
"Score": "2",
"body": "You should indent your code properly. That makes it more pleasant to read, and increases the chances of a good answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:13:32.780",
"Id": "44557",
"Score": "0",
"body": "`return Camel` This won't compile, did you mean `return new Camel()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:07:04.757",
"Id": "44567",
"Score": "0",
"body": "@svick Yes it should be return new camel. Sorry, was in a hurry just write it in a notepad :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:11:17.553",
"Id": "44575",
"Score": "0",
"body": "I would suggest you name your interface `ITransportable`, following a bit of a naming convention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T20:05:16.920",
"Id": "44602",
"Score": "0",
"body": "@Abbas That wouldn't make much sense. A ship is not something that can transported, it's something that transports other things. So I think `ITransport` is a good name here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T21:16:43.970",
"Id": "44606",
"Score": "0",
"body": "@svick You're right, `ITransportProvider` then! :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T02:58:32.347",
"Id": "44633",
"Score": "0",
"body": "Sorry, didn't find any time yesterday, I was actually going to intent the code today, but looks like some one else has already done that :)"
}
] |
[
{
"body": "<p>I assume that this is just an example and I don't need to tell you that you should use <code>enum</code>s instead of <code>string</code>s, remove <code>break</code>s after <code>return</code>s, indent your code, etc. :) So, to answer your question: I think you should refactor your <code>Human</code> class:</p>\n\n<pre><code>class Human\n{\n private readonly TransportFactory _tFactory;\n\n public Human(TransportFactory tFactory)\n {\n if (tFactory == null) \n {\n throw new ArgumentNullException(\"tFactory\");\n }\n _tFactory = tFactory;\n }\n\n void Travel(string ground)\n { \n var transport = _tFactory.ProvideTransport(ground);\n transport.Travel();\n }\n}\n\nclass TransportFactory\n{\n ITransport ProvideTransport(string groundType)\n {\n switch(groundType)\n {\n case \"desert\":\n return new Camel();\n case \"plain\":\n return new Horse();\n case \"sea\":\n return new Ship();\n default:\n return new ArmsAndLegs();\n }\n }\n}\n</code></pre>\n\n<p>You will still need to modify factory method when you add new transport though. This can be avoided by using reflection.</p>\n\n<p><strong>Edit:</strong> here is another example:</p>\n\n<pre><code>class Human\n{\n public event Action<Human, ПкщгтвЕнзуы> TransportRequested;\n\n void Travel(GroundTypes ground)\n { \n var ev = TransportRequested;\n if (ev != null)\n {\n ev(this, ground);\n }\n }\n}\n\ninterface ITransport\n{\n void Transport(object cargo);\n}\n\n\nclass TravelAgency\n{\n private readonly TransportFactory _tFactory;\n\n public TravelAgency(TransportFactory tFactory)\n {\n if (tFactory == null) \n {\n throw new ArgumentNullException(\"tFactory\");\n }\n _tFactory = tFactory;\n }\n\n //this method at some point subscribes to TransportRequested event\n private void OnTransportRequested(Human human, GroundTypes ground)\n {\n var transport = _tFactory.ProvideTransport(ground);\n transport.Transport(human);\n }\n}\n</code></pre>\n\n<p><strong>Edit2</strong></p>\n\n<p>Subscription using your TransportFactory logic:</p>\n\n<pre><code>public class HumanFactory\n{\n Dictionary<GroundTypes, ITransport> _availableTransports;\n\n public HumanFactory(TransportFactory tFactory)\n {\n _availableTransports = new Dictionary<string, ITransport>();\n _availableTransports.Add(GroundTypes.Desert, tFactory.ProvideTransport(TransportTypes.Horse));\n _availableTransports.Add(GroundTypes.Sea, tFactory.ProvideTransport(TransportTypes.Camel));\n _availableTransports.Add(GroundTypes.Plains, tFactory.ProvideTransport(TransportTypes.Ship));\n }\n\n public Human CreateHuman()\n {\n var h = new Human();\n h.TransportRequested += OnHumanTransportRequested;\n return h;\n }\n\n //you can incapsulate this logic in some other object\n //you should also consider implementing Events Aggregator\n //or those subscriptions might become quite complicated as their number increases\n void OnHumanTransportRequested(Human human, GroundTypes groundType)\n {\n if (_availableTransports.ContainsKey(groundType))\n {\n ITransport suitableTransport = _availableTransports[groundType];\n suitableTransport.Travel();\n }\n else\n {\n //code for handling below conditions goes here\n //I don't know what to do for this type of plain?\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:11:05.447",
"Id": "44568",
"Score": "0",
"body": "Actually I was trying to avoid passing factory in the constructor as I was following [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter). Is there some other way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:28:52.290",
"Id": "44569",
"Score": "0",
"body": "@shankbond, well, your initial code contains factory reference in `Human` class, so i thought its not a problem for you. :) But it can be removed, sure. To do so, you should delegate this logic to higher level. The easiest way do it is to rise an event (`public event Action<Human, string> RequestTransport;`, for example) in your `Travel(string ground)` method and do the handling in the object which has the knowledge about factories (`Society`? :)). You can also use `EventsAggregator` pattern for easier event handling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:40:40.100",
"Id": "44573",
"Score": "0",
"body": "I've added a somewhat simplified example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:20:14.237",
"Id": "44576",
"Score": "1",
"body": "I'd also mark those constructor-injected, assigned to member variables as `readonly` to signify intent as well as check them for `null` before assignment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T17:23:27.323",
"Id": "44595",
"Score": "0",
"body": "@JesseC.Slicer, good point. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T03:20:00.517",
"Id": "44635",
"Score": "0",
"body": "@Nik I tried to understand Your second implementation, may be 2 or 3 times but still I cannot understand it. Could You please elaborate it more.From what I understood is: main method(or client) will first call Human, human is passed travel agency, travel agency is passed transport factory. So does this means that transport factory has the intelligence of which transport to give on what type of ground? Please elaborate it as this will help me understand it better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T03:27:51.417",
"Id": "44636",
"Score": "0",
"body": "@Nik some of my business logic has been gone in factory? who is registering the event? How will client perform this operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T16:57:26.470",
"Id": "44653",
"Score": "0",
"body": "@Nik I have updated my question with what I understood from Your answer, kindly comment whether it is correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T05:53:55.850",
"Id": "44721",
"Score": "0",
"body": "@shankbond you can do the subscription in HumanFactory (this is getting funny:) ), you got it right. I see nothing wrong with factory knowing which transport type suits which ground type. At least it makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:08:59.660",
"Id": "44722",
"Score": "0",
"body": "@shankbond edited my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T08:06:25.377",
"Id": "44742",
"Score": "0",
"body": "@Nik Though Your answer is clearly what I asked so I mark it as answer, but now it is creeping with new problems(what if there are lot of methods in the ITransport interface) I should be having lot of event handlers in my Factory class. Isn't it a maintenance Nightmare? I cannot ask this question here in this thread. So, I have posted it as a [seperate question](http://stackoverflow.com/questions/17641643/constructor-injection-class-dependent-on-different-type-of-objects)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T08:31:16.557",
"Id": "28405",
"ParentId": "28396",
"Score": "3"
}
},
{
"body": "<p>At first there are a lot of random \"new\" operators. It is best to compose application on it entry point like:</p>\n\n<pre><code> public class Program \n {\n public static void Main()\n {\n IDictionary<GroundType, ITransport> transports = new Dictionary<GroundType, ITransport> \n {\n { GroundType.Plain, new Horse() },\n { GroundType.Desert, new Camel() },\n { GroundType.Sea, new Ship() }\n };\n\n\n TransportFactory transportFactory = new TransportFactory(transports);\n\n Human hero = new Human(transportFactory);\n hero.Travel();\n }\n}\n\n public class Human\n {\n private readonly TransportFactory _transportFactory;\n\n private GroundType _ground;\n\n public Human(TransportFactory transportFactory)\n {\n _transportFactory = transportFactory;\n }\n\n public void Travel()\n {\n var transport = _transportFactory.GetTransport(_ground);\n transport.Travel();\n }\n }\n\n public class TransportFactory\n {\n private readonly IDictionary<GroundType, ITransport> _transports;\n\n public TransportFactory(IDictionary<GroundType, ITransport> transports)\n {\n _transports = transports;\n }\n\n // virtual will allow to override this method with test stub\\mock\n public virtual ITransport GetTransport(GroundType groundType)\n {\n ITransport transport;\n if (!_transports.TryGetValue(groundType, out transport)) {\n // this way we can find any issues earlier \n throw new NotSupportedException(\"The current ground of type '{0}' is not supported\");\n }\n\n return transport;\n }\n }\n</code></pre>\n\n<p>The full DI Composition Root might look after some time:</p>\n\n<pre><code>public static void Main()\n{\n IDictionary<GroundType, ITransport> transports = new Dictionary<GroundType, ITransport> \n {\n { GroundType.Plain, new Horse() },\n { GroundType.Desert, new Camel() },\n { GroundType.Sea, new Ship() }\n };\n\n\n TransportFactory transportFactory = new TransportFactory(transports);\n\n Human hero = CreateHuman(transportFactory);\n Human enemy = CreateHuman(transportFactory);\n\n Continent continent = Continent.LoadFromResource(DefaultContinent);\n continent.Place(hero, new Vector3(0, 0, 0));\n continent.Place(enemy, new Vector3(110, 30, 0));\n\n Continent demonicContinent = Continent.LoadFromResource(DemonicContinent);\n\n World world = new World(new List<Continent> { continent, demonicContinent });\n Game game = new Game(world, new DefaultRulesProvider());\n game.Start();\n}\n</code></pre>\n\n<p>I also suggest to read Mark Seemann's \"Dependency Injection in .NET\" book.</p>\n\n<p><a href=\"http://www.youtube.com/watch?v=RlfLCWKxHJ0&list=PLED6CA927B41FF5BD&index=3\" rel=\"nofollow\">There are also a lot of talks about testability, DI, and OOP by Misco Hevery</a> - I would have watch them 4 years earlier!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T06:27:36.000",
"Id": "44641",
"Score": "1",
"body": "I think You should get +1000( unfortunately I don't have that right to up-vote You) for those awesome links Misco rocks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T06:31:46.487",
"Id": "44642",
"Score": "0",
"body": "Don't You think that 'var transport = _transportFactory.GetTransport(_ground);\n transport.Travel();'(It is in Human class Travel method) is violating Law of Demeter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T08:10:25.030",
"Id": "44744",
"Score": "0",
"body": "Probably in this specific example Human is not an ITransport himself. The more real world example might be AggregateLogger when it implements ILogger interface, and just iterates through each attached logger: `public void Info() { foreach (var logger in _loggers) {logger.Info();}};`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T11:54:48.997",
"Id": "44818",
"Score": "0",
"body": "I must agree - factory inside Human class is over-complicated. It is better to inject list of Transports directly into human constructor in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T15:20:08.890",
"Id": "44837",
"Score": "0",
"body": "do I violate Law of Demeter or Dependency Injection in any case if I pass a list / dictionary of dependencies into the constructor?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T10:07:47.727",
"Id": "45030",
"Score": "0",
"body": "From Wiki: \nLaw of Demeter for functions requires that a method **m** of an object **O** may only invoke the methods of the following kinds of objects:\n1) **O** itself\n2) **m**'s parameters\n3) Any objects created/instantiated **within m**\n**O**'s direct component objects (i.e. only `_transportFactory.Get`, and not this crazy: `_transportFactory.ServerWcfClient.GetGonfiguration().SqlConnection.Close()`,\n4) A global variable, accessible by **O**, in the scope of **m**\n\nSo neither passing list or dictionary does not violate law of demeter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-24T22:06:57.497",
"Id": "142237",
"Score": "0",
"body": "I will take my comment back, and won't pass dictionaty of dependencies. Better to use Factory\nhttp://stackoverflow.com/a/1945023/2377370"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T15:07:37.360",
"Id": "28420",
"ParentId": "28396",
"Score": "1"
}
},
{
"body": "<p>Sticking to your example, I came up with the following:</p>\n\n<p>1) Interface for Transports</p>\n\n<pre><code>interface Transport\n{\n void Travel();\n bool isSuitableForGround(Ground ground);\n}\n</code></pre>\n\n<p>2) Possible implementation</p>\n\n<pre><code>class Horse:Transport\n{\n HashSet<Ground> suitableGrounds = new HashSet<Ground> { Ground.Plain };\n public bool isSuitableForGround(Ground ground)\n { \n return suitableGrounds.Contains(ground);\n }\n\n public void Travel()\n {\n\n }\n}\n</code></pre>\n\n<p>So. The Horse knows best, upon which grounds it would walk.</p>\n\n<p>3) The Factory should know nothing of the abilities of what it delivers except the type. The ground which a transport is suitable for is up to the transport itself. It knows best. </p>\n\n<pre><code>class TransportationsFactory\n{\n Dictionary<Type, TransportFactory> transporters=new Dictionary<Type,TransportFactory>();\n\n public Transport GetTransportType<T>(){\n if (transporters.ContainsKey(typeof(T)) == false) throw new Exception();\n return transporters[typeof(T)].produce();\n }\n\n public TransportationsFactory(){\n transporters.Add(typeof(Horse),new HorseBreeder());\n }\n\n}\n</code></pre>\n\n<p>If you want a Horse, you get a Horse by</p>\n\n<pre><code>transportationsFactory.GetTransportType<Horse>()\n</code></pre>\n\n<p>4) The implementation of a human looks like the following:</p>\n\n<pre><code>class Human\n{\n List<Transport> transports = new List<Transport>();\n\n public void TravelOn(Ground ground){\n try\n {\n Transport possibleTransports = transports.Where(t => t.isSuitableForGround(ground)).First();\n possibleTransports.Travel();\n }\n catch (InvalidOperationException ex) { \n //Do something useful\n }\n\n }\n\n public Human(IEnumerable<Transport> transports){\n this.transports = transports.ToList();\n }\n}\n</code></pre>\n\n<p>Of course you could choose another strategy to get a suitable transport. For the sake of the example I chose the strategy to get the first one able to do the job.</p>\n\n<p>Since you asked for constructor injection, I implemented it this way, taking a collection of transports. I would prefer setter injection.</p>\n\n<p>If there is the need to travel on a (different) ground, the human asks its collection of transports, whether one of it is capable of doing the job - so the human too has not to have any knowledge at all what is good for what job.</p>\n\n<p>If you ever come up with a car, you add it to your factory and ask your factory for that. And the car knows best, for what grounds it is made for.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T07:04:25.697",
"Id": "28433",
"ParentId": "28396",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28405",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T03:47:40.007",
"Id": "28396",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"dependency-injection"
],
"Title": "Constructor Injection, new dependency and its impact on code"
}
|
28396
|
<p>I'm trying to make a MultiClient Chat Application in which the chat is implemented in the client window. I've tried server and client code for the same. I've got two problems:
<strong><em>A.</em></strong> I believe the code should work but, server to client connections are just fine but information isn't transferred between clients.
<strong><em>B.</em></strong> I need a way to implement private one-to-one chat in case of more than two clients, I've used a class to store the information of the Socket object returned for each connection being established, but I can't figure out how to implement it.</p>
<p>The <strong><em>server code</em></strong> is:</p>
<pre><code>import java.io.*;
import java.net.*;
class ClientInfo {
Socket socket;
String name;
public ClientInfo(Socket socket, String name) {
this.socket = socket;
this.name = name;
}
}
public class server {
private ObjectInputStream input[] = null;
private ObjectOutputStream output[] = null;
private String value = null;
private static ServerSocket server;
private Socket connection = null;
private static int i = -1;
public static void main(String args[]) {
try {
server = new ServerSocket(1500, 100);
while (true) {
System.out.println("Waiting for connection from client");
Socket connection = server.accept();
i++;
System.out.println("Connection received from " + (i + 1) + " source(s)");
//System.out.println(i);
new ClientInfo(connection, "Client no:" + (i + 1));
innerChat inc = new server().new innerChat(connection);
}
} catch (Exception e) {
System.out.println("Error in public static void main! >>>" + e);
}
}// end of main!!!
class innerChat implements Runnable {
private Socket connection = null;
public innerChat(Socket connection) {
this.connection = connection;
Thread t;
t = new Thread(this);
t.start();
}
public void run() {
try {
output[i] = new ObjectOutputStream(connection.getOutputStream());
output[i].flush();
input[i] = new ObjectInputStream(connection.getInputStream());
} catch (Exception e) {
}
}
}
}
</code></pre>
<p>And the <strong><em>client code</em></strong> is</p>
<pre><code>import java.net.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.*;
import java.awt.event.*;
public class ChatappClient {
private static int port = 1500;
JFrame window = new JFrame("Chat");
JButton sendBox = new JButton("Send");
JTextField inputMsg = new JTextField(35);
JTextArea outputMsg = new JTextArea(10, 35);
private ObjectInputStream input;
private ObjectOutputStream output;
public static void main(String[] args) throws Exception {
ChatappClient c = new ChatappClient();
c.window.setVisible(true);
c.window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.run();
}
public ChatappClient() {
inputMsg.setSize(40, 20);
sendBox.setSize(5, 10);
outputMsg.setSize(35, 50);
inputMsg.setEditable(true);
outputMsg.setEditable(false);
window.getContentPane().add(inputMsg, "South");
window.getContentPane().add(outputMsg, "East");
window.getContentPane().add(sendBox, "West");
window.pack();
sendBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
output.writeObject(inputMsg.getText());
outputMsg.append("\n" + "Client>>>" + inputMsg.getText());
output.flush();
} catch (IOException ie) {
outputMsg.append("Error encountered! " + ie);
}
inputMsg.setText("");
}
});
inputMsg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
output.writeObject(inputMsg.getText());
outputMsg.append("\n" + "Client>>>" + inputMsg.getText());
output.flush();
} catch (IOException ie) {
outputMsg.append("Error encountered! " + ie);
}
inputMsg.setText("");
}
});
}
private void run() throws IOException {
Socket clientSocket = new Socket("127.0.0.1", port);
output = new ObjectOutputStream(clientSocket.getOutputStream());
output.flush();
input = new ObjectInputStream(clientSocket.getInputStream());
outputMsg.append("I/O Success");
String value = null;
while (true) {
try {
value = (String) input.readObject();
} catch (Exception e) {
}
outputMsg.append(value + "\n");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:32:59.640",
"Id": "44561",
"Score": "1",
"body": "First of all, try to follow the Java conventions: Class names must start with uppercase. Another problem I see your server is receiving connections but it's doing nothing with them. It must read any client message end then send it to the rest of the clients"
}
] |
[
{
"body": "<p>Currently your <code>innerChat</code> <code>Runnable</code> gets the <code>InputStream</code> and <code>OutputStream</code> but doesn't do anything with them.</p>\n\n<p>The client also simply writes <code>String</code>s to its <code>OutputStream</code>, however it would be more convenient to send instances of a custom Message class, that, aside from the textual message, holds information for the intended recipient e.g. :</p>\n\n<ul>\n<li>a specific room member (personal message)</li>\n<li>a room (public message in the room)</li>\n<li>the server (a command)</li>\n<li>...</li>\n</ul>\n\n<p>The server can then decide what to do with each type of message.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T17:21:41.657",
"Id": "44654",
"Score": "0",
"body": "Thanks for pointing that out. I made the necessary changes and I'm working on the client side right now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T15:25:05.127",
"Id": "28439",
"ParentId": "28397",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T04:20:27.760",
"Id": "28397",
"Score": "-1",
"Tags": [
"java",
"multithreading",
"swing",
"socket"
],
"Title": "Stuck with Multi-Client Chat Application"
}
|
28397
|
<p>My aim is to sort a list of strings where words have to be sorted alphabetically. Words starting with <code>s</code> should be at the start of the list (they should be sorted as well), followed by the other words.</p>
<p>The below function does that for me.</p>
<pre><code>def mysort(words):
mylist1 = sorted([i for i in words if i[:1] == "s"])
mylist2 = sorted([i for i in words if i[:1] != "s"])
list = mylist1 + mylist2
return list
</code></pre>
<p>I am looking for better ways to achieve this, or if anyone can find any issues with the code above.</p>
|
[] |
[
{
"body": "<p>For this snippet, I would have probably written the more compact:</p>\n\n<pre><code>def mysort(words):\n return (sorted([i for i in words if i[0] == \"s\"]) +\n sorted([i for i in words if i[0] != \"s\"]))\n</code></pre>\n\n<p>(You're not supposed to align code like this in Python, but I tend to do it anyway.) Note that I wrote <code>i[0]</code> and not <code>i[:1]</code> - I think the former is clearer. Using <code>str.startswith()</code> is even better.</p>\n\n<p>Also, it is generally considered bad practice to use <code>list</code> as a variable name.</p>\n\n<p>However, your algorithm iterates the list at least three times: Once to look for the words starting with <code>s</code>, once to look for the words <em>not</em> starting with <code>s</code> and then finally <code>O(n log n)</code> times more to sort the two lists. If necessary, you can improve the algorithm to do just one pass before sorting, by populating both lists simultaneously:</p>\n\n<pre><code>def prefix_priority_sort(words, special_prefix = \"s\"):\n begins_with_special = []\n not_begin_with_special = []\n\n for word in words:\n if word.startswith(special_prefix):\n begins_with_special.append(word)\n else:\n not_begin_with_special.append(word)\n\n return sorted(begins_with_special) + sorted(not_begin_with_special)\n</code></pre>\n\n<p>However, the best way is to define your own comparator and pass it to the sorting function, like <code>mariosangiorgio</code> suggests. In Python 3, you need to pass in a <em>key</em> function, <a href=\"http://docs.python.org/3.1/library/functions.html#sorted\" rel=\"nofollow\">see the docs for details</a>, or <a href=\"http://python3porting.com/preparing.html#keycmp-section\" rel=\"nofollow\">this article</a>.</p>\n\n<p>Depending on execution speed requirements, list sizes, available memory and so on, you <em>might</em> want to pre-allocate memory for the lists using <code>[None] * size</code>. In your case it is probably premature optimization, though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:04:16.123",
"Id": "44583",
"Score": "5",
"body": "Note that `i[0]` will fail for empty strings, while `i[:1]` will not. Agreed that `startswith` is best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:48:22.693",
"Id": "44587",
"Score": "0",
"body": "Your `mysort` needs another pair of parentheses, or a backslash before the newline."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T16:48:37.153",
"Id": "44591",
"Score": "0",
"body": "@tobias_k Ah, good point!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T00:53:50.330",
"Id": "44793",
"Score": "0",
"body": "What makes you say you're not supposed to align code like that? [PEP-8](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) does it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T07:33:03.253",
"Id": "28402",
"ParentId": "28398",
"Score": "4"
}
},
{
"body": "<p>Lastor already said what I was going to point out so I am not going to repeat that. I'll just add some other things.</p>\n\n<p>I tried timing your solution with a bunch of other solutions I came up with. Among these the one with best time-memory combination should be the function <code>mysort3</code> as it gave me best timing in nearly all cases. I am still looking about <a href=\"https://codereview.stackexchange.com/questions/28373/is-this-the-proper-way-of-doing-timing-analysis-of-many-test-cases-in-python-or\">proper timing</a> in Python. You can try putting in different test cases in the function <code>tests</code> to test the timing for yourself. </p>\n\n<pre><code>def mysort(words):\n mylist1 = sorted([i for i in words if i[:1] == \"s\"])\n mylist2 = sorted([i for i in words if i[:1] != \"s\"])\n list = mylist1 + mylist2\n return list\n\ndef mysort3(words):\n ans = []\n p = ans.append\n q = words.remove\n words.sort()\n for i in words[:]:\n if i[0] == 's':\n p(i)\n q(i)\n return ans + words\n\ndef mysort4(words):\n ans1 = []\n ans2 = []\n p = ans1.append\n q = ans2.append\n for i in words:\n if i[0] == 's':\n p(i)\n else:\n q(i)\n ans1.sort()\n ans2.sort()\n return ans1 + ans2\n\ndef mysort6(words):\n return ( sorted([i for i in words if i[:1] == \"s\"]) +\n sorted([i for i in words if i[:1] != \"s\"])\n )\n\nif __name__ == \"__main__\":\n from timeit import Timer\n def test(f):\n f(['a','b','c','abcd','s','se', 'ee', 'as'])\n\n print Timer(lambda: test(mysort)).timeit(number = 10000)\n print Timer(lambda: test(mysort3)).timeit(number = 10000)\n print Timer(lambda: test(mysort4)).timeit(number = 10000)\n print Timer(lambda: test(mysort6)).timeit(number = 10000)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T07:45:58.533",
"Id": "28403",
"ParentId": "28398",
"Score": "1"
}
},
{
"body": "<p>If you want to sort the list according to your own criterion probably the best choice is to write your own comparator.</p>\n\n<p>A comparator function takes as parameters two values and has to return -1 if the first one is the smaller, 0 if they are equal and +1 if the second is the bigger.</p>\n\n<p>In your case you should first check wether one of the two parameters starts with 's'. If it does manage it properly, otherwise fall back to standard string ordering.</p>\n\n<p>This will turn your code in a single call to the sort function plus the definition of the comparison function.</p>\n\n<p>If you want an example of how comparators can be implemented have a look at the answers of <a href=\"https://stackoverflow.com/questions/12749398/using-a-comparator-function-to-sort\">this StackOVerflow Q&A</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:24:58.377",
"Id": "44584",
"Score": "0",
"body": "Are you sure? IMO `sorted` along the `key` argument is on a higher level of abstraction than defining a comparator thus should be generally preferred. http://en.wikipedia.org/wiki/Schwartzian_transform"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T16:50:54.790",
"Id": "44593",
"Score": "0",
"body": "@tokland Python 2 takes a *comparator* function, Python 3 takes a *key* function, if that's what you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T18:08:00.503",
"Id": "44596",
"Score": "0",
"body": "AFAIK `sort` (in-place) has always taken a comparator function and `sorted` (not in-place) a key function, but I am not 100% sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T18:16:24.483",
"Id": "44597",
"Score": "0",
"body": "@tokland Ah, you are more or less right regarding `sorted`. In Python 2.7, it takes a comparator function *and* a key function: http://docs.python.org/2.7/library/functions.html?highlight=sorted#sorted"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T07:46:49.787",
"Id": "28404",
"ParentId": "28398",
"Score": "1"
}
},
{
"body": "<p>Some notes about your code:</p>\n\n<ul>\n<li><p><code>sorted([i for i in words if i[:1] == \"s\"])</code>: No need to generate an intermediate list, drop those <code>[</code> <code>]</code> and you'll get a lazy generator expression instead.</p></li>\n<li><p><code>mylist1</code>. This <code>my</code> prefix looks pretty bad. Do other languages use them?</p></li>\n<li><p><code>list</code>: Red flag. Don't overshadow a built-in (at least not one so important) with a variable.</p></li>\n<li><p><code>return list</code>. You can directly write <code>return mylist1 + mylist2</code>, no gain in naming the value you're about to return (the name of the function should inform about that).</p></li>\n<li><p><code>i[:1] == \"s\"</code> -> <code>i.startswith(\"s\")</code>.</p></li>\n</ul>\n\n<p>Now what I'd write. Using <a href=\"http://docs.python.org/2/library/functions.html#sorted\" rel=\"nofollow\">sorted</a> with the argument <code>key</code> (<a href=\"http://en.wikipedia.org/wiki/Schwartzian_transform\" rel=\"nofollow\">Schwartzian transform</a>) and taking advantage of the <a href=\"http://en.wikipedia.org/wiki/Lexicographical_order\" rel=\"nofollow\">lexicographical order</a> defined by tuples:</p>\n\n<pre><code>def mysort(words):\n return sorted(words, key=lambda word: (0 if word.startswith(\"s\") else 1, word))\n</code></pre>\n\n<p>If you are familiar with the fact that <code>False < True</code>, it can be simplified a bit more:</p>\n\n<pre><code>sorted(words, key=lambda word: (not word.startswith(\"s\"), word))\n</code></pre>\n\n<p>Here's another way using the abstraction <code>partition</code>:</p>\n\n<pre><code>words_with_s, other_words = partition(words, lambda word: word.startswith(\"s\"))\nsorted(words_with_s) + sorted(other_words)\n</code></pre>\n\n<p>Writing <code>partition</code> is left as an exercise for the reader :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:00:34.030",
"Id": "44580",
"Score": "0",
"body": "Dang, I was just writing up the same thing! +1 :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:01:15.923",
"Id": "44581",
"Score": "0",
"body": "@tobias_k: sorry ;-) I was a bit suprised no one had proposed something similar yet, this is pretty standard stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:02:16.180",
"Id": "44582",
"Score": "1",
"body": "No problem, but two times the same answer within 2 minutes for a 8 hours old question... how probable is this?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:56:20.453",
"Id": "28418",
"ParentId": "28398",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "28418",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T05:46:42.197",
"Id": "28398",
"Score": "2",
"Tags": [
"python",
"sorting"
],
"Title": "Sort a list in Python"
}
|
28398
|
<p>The following are an example of methods supported by a proprietary device:</p>
<pre><code>Monitor
ControlTemp
PutPeakInfo
GetPeakInfo
</code></pre>
<p>I have a class that builds the packets for the above corresponding methods:</p>
<pre><code>GetMonitorPacket
GetControlTempPacket
GetPutPeakInfo
</code></pre>
<p>Example:</p>
<pre><code>public byte[] GetMonitorPacket(int ddcNum)
{
byte[] monitorPacket = new byte[MONITOR_PACKET_BYTE_COUNT];
Buffer.BlockCopy(START_HEADER_BYTES, 0, monitorPacket, 0, START_HEADER_BYTES.Count());
monitorPacket[2] = (byte) ddcNum;
monitorPacket[3] = 0x01;
byte checksum = 0;
foreach (var b in monitorPacket)
{
checksum = (byte) (((ushort) checksum + (ushort) b) & 0xff);
}
checksum = (byte) (checksum ^ 0x55);
monitorPacket[4] = checksum;
return monitorPacket;
}
</code></pre>
<p>All they do is return the bytes in proper format, which then will be sent to the proprietary device via TCP to call the methods. Now I'm screwed on my naming convention for <code>GetPeakInfo</code> method. </p>
<ol>
<li>How do I name this? What about <code>GetGetPeakInfoPacket</code> (two gets for a method name)?</li>
<li>Do I break the naming convention here as an exception case and drop one of the gets?</li>
<li>Do I use some other naming convention?</li>
</ol>
<p>Actually, <code>GetPutPeakInfo</code> sounds a little bit weird too, but at least there's no duplication.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:30:12.607",
"Id": "44560",
"Score": "0",
"body": "For example, Microsoft doesn't seem to care. \"How do we call method, which returns `MethodInfo` for property getter? `PropertyInfo.GetGetMethod()`, no problem.\" In your case, i like `Create` prefix. But, iguess, its a matter of taste."
}
] |
[
{
"body": "<p>How about using <code>Generate</code> as prefix?</p>\n\n<pre><code>GenerateMonitorPacket\nGenerateControlTempPacket\nGeneratePutPeakInfoPacket\nGenerateGetPeakInfoPacket\n</code></pre>\n\n<p>Alternatively, you can also create a separate class for each type of packet generator. You've only shown the code to create the packet for <code>Monitor</code>, so I don't know how complex the code for the other packets is, but separating these four methods into their own class might be logical and beneficial in the long run. If you create separate classes, you put the name of the packet (Monitor, ControlTemp, PutPeakInfo and GetPeakInfo) in the class name.</p>\n\n<pre><code>public class MonitorPacketGenerator\n{\n public byte[] Generate(int ddcNum) { ... }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T07:56:46.777",
"Id": "44541",
"Score": "0",
"body": "Best I could've come up myself so far. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T07:22:25.690",
"Id": "28401",
"ParentId": "28400",
"Score": "6"
}
},
{
"body": "<blockquote>\n <p>I have a class that <strong>builds</strong> the packet</p>\n</blockquote>\n\n<p>Then why don't you call your methods <code>Build*</code>, e.g. <code>BuildMonitorPacket</code>?</p>\n\n<p>I think such naming is also clearer, because “build” says more clearly what does the method do, “get” is too general. (For example, it would make sense if a “get” method returned the same result every time, but not so much for a “build” method.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:20:50.420",
"Id": "28411",
"ParentId": "28400",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28401",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T07:00:18.960",
"Id": "28400",
"Score": "1",
"Tags": [
"c#",
"tcp"
],
"Title": "Getting a monitor packet"
}
|
28400
|
<p>I'm only two weeks into learning Java and just finished creating my first program. I have a feeling I've added unnecessary things, but not sure. I'd like someone to take a look at it and let me know if there are ways to simplify or approach the code. Basically, I'm just trying to create a simple GPA calculator.</p>
<pre><code>import java.util.Scanner;
class GpaCalculator {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
char c1;
double gpa;
double g1, g2, g3, g4, g5, g6;
g1 = 0;
g2 = 0;
g3 = 0;
g4 = 0;
g5 = 0;
g6 = 0;
System.out.println("What is your grade for class 1?");
c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
if (c1 == 'a' || c1 == 'A') {
g1 = 4;
}
if (c1 == 'b' || c1 == 'B') {
g1 = 3;
}
if (c1 == 'c' || c1 == 'C') {
g1 = 2;
}
if (c1 == 'd' || c1 == 'D') {
g1 = 1;
}
if (c1 == 'f' || c1 == 'F') {
g1 = 0;
}
System.out.println("What is your grade for class 2?");
c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
if (c1 == 'a' || c1 == 'A') {
g2 = 4;
}
if (c1 == 'b' || c1 == 'B') {
g2 = 3;
}
if (c1 == 'c' || c1 == 'C') {
g2 = 2;
}
if (c1 == 'd' || c1 == 'D') {
g2 = 1;
}
if (c1 == 'f' || c1 == 'F') {
g2 = 0;
}
System.out.println("What is your grade for class 3?");
c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
if (c1 == 'a' || c1 == 'A') {
g3 = 4;
}
if (c1 == 'b' || c1 == 'B') {
g3 = 3;
}
if (c1 == 'c' || c1 == 'C') {
g3 = 2;
}
if (c1 == 'd' || c1 == 'D') {
g3 = 1;
}
if (c1 == 'f' || c1 == 'F') {
g3 = 0;
}
System.out.println("What is your grade for class 4?");
c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
if (c1 == 'a' || c1 == 'A') {
g4 = 4;
}
if (c1 == 'b' || c1 == 'B') {
g4 = 3;
}
if (c1 == 'c' || c1 == 'C') {
g4 = 2;
}
if (c1 == 'd' || c1 == 'D') {
g4 = 1;
}
if (c1 == 'f' || c1 == 'F') {
g4 = 0;
}
System.out.println("What is your grade for class 5?");
c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
if (c1 == 'a' || c1 == 'A') {
g5 = 4;
}
if (c1 == 'b' || c1 == 'B') {
g5 = 3;
}
if (c1 == 'c' || c1 == 'C') {
g5 = 2;
}
if (c1 == 'd' || c1 == 'D') {
g5 = 1;
}
if (c1 == 'f' || c1 == 'F') {
g5 = 0;
}
System.out.println("What is your grade for class 6?");
c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
if (c1 == 'a' || c1 == 'A') {
g6 = 4;
}
if (c1 == 'b' || c1 == 'B') {
g6 = 3;
}
if (c1 == 'c' || c1 == 'C') {
g6 = 2;
}
if (c1 == 'd' || c1 == 'D') {
g6 = 1;
}
if (c1 == 'f' || c1 == 'F') {
g6 = 0;
}
gpa = (g1 + g2 + g3 + g4 + g5 + g6) / 6;
System.out.println("Your GPA is " + gpa + ". ");
if (gpa > 3.00) {
System.out.println("Gret job, you're on your way to success.");
} else if (gpa > 2.00) {
System.out.println("You did OK, but better than average.");
} else {
System.out.println("You didn't do too well. You should look into getting a tutor.");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I would improve your code as following :</p>\n\n<ul>\n<li>Look at your code, you'll notice the repetition of the same piece of code (print a question => scan for input => analyze the input), it means you could write a method for that.</li>\n<li>If you want to ask for one more grade, you'll have to create a new variable, etc. I would store grades in an array.</li>\n<li>Actually, I'm not even sure I would store them in an array: just sum the grades, and then divide it by the number of grades</li>\n<li>Lower case the user input, so you don't have to test for lowercase and uppercase.</li>\n<li>use <code>if ... else if</code> instead of several <code>if</code></li>\n<li>In your case, you initialize the grade with 0, and store 0 when user type <code>f</code>. It is not necessary to deal with this case.</li>\n<li>You don't deal with E grades?</li>\n</ul>\n\n<p>The code would look like something like that:</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class GpaCalculator {\n private final static Scanner MY_SCANNER = new Scanner(System.in);\n private final static int NUMBER_OF_GRADES = 6;\n\n public static void main(final String[] args) {\n int sum = 0;\n for (int i = 0; i < NUMBER_OF_GRADES; i++) {\n sum += askForGrade(i);\n }\n final double gpa = (double) sum / NUMBER_OF_GRADES;\n\n System.out.println(\"Your GPA is \" + gpa + \". \");\n\n if (gpa > 3.00) {\n System.out.println(\"Gret job, you're on your way to success.\");\n } else if (gpa > 2.00) {\n System.out.println(\"You did OK, but better than average.\");\n } else {\n System.out.println(\"You didn't do too well. You should look into getting a tutor.\");\n }\n }\n\n private static int askForGrade(final int index) {\n System.out.println(\"What is your grade for class \" + (index + 1) + \"?\");\n char c1 = MY_SCANNER.findWithinHorizon(\".\", 0).charAt(0);\n c1 = Character.toLowerCase(c1);\n\n switch(c1){\n case 'a':\n return 4;\n case 'b':\n return 3;\n case 'c':\n return 2;\n case 'd':\n return 1;\n default:\n return 0;\n }\n }\n}\n</code></pre>\n\n<p>Finally, you could improve the prompt to accept only real grades (in your code and in mine, user can provide any character).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T09:20:44.290",
"Id": "44548",
"Score": "1",
"body": "+1 Gud explanation. But best practice says that try to make single exit point for every method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T09:45:10.567",
"Id": "44550",
"Score": "0",
"body": "Yes, you are absoluty right, I edited my answer in consequence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:04:47.380",
"Id": "44553",
"Score": "4",
"body": "@AshishAggarwal I disagree, [using multiple exist points can make your code more readable](http://stackoverflow.com/q/36707/41071)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T10:16:52.757",
"Id": "44558",
"Score": "0",
"body": "@svick I agree with you, but I read everywhere the single exit thing (there's even a PMD rule), but I think it's less readable too. In this case, I think readability is not much impacted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:55:40.080",
"Id": "44589",
"Score": "0",
"body": "@ssssteffff you can use **switch** with a *'char'* instead of `if .. else if ..`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T09:09:15.930",
"Id": "28408",
"ParentId": "28406",
"Score": "5"
}
},
{
"body": "<p>First off, both <code>Grade</code> and <code>Class</code> (<code>GradedClass</code> to avoid confusion with <code>java.lang.Class</code>) make sense as enums.</p>\n\n<pre><code>enum Grade {\n A(4),B(3),C(2),D(1),F(0);\n\n private final int value;\n\n Grade(int value) {\n this.value = value;\n }\n\n int getValue() {\n return value;\n }\n}\n\nenum GradedClass {\n ONE, TWO, THREE, FOUR, FIVE, SIX;\n\n @Override\n public String toString() {\n return \"class \" + (ordinal() + 1);\n }\n}\n</code></pre>\n\n<p>This will allow a much simpler calculation loop :</p>\n\n<pre><code> public double calculateGpa() {\n return calculateTotal() / GradedClass.values().length;\n }\n\n private double calculateTotal() {\n double total = 0d;\n for (GradedClass gradedClass : GradedClass.values()) {\n Grade grade = userInterface.askGradeFor(gradedClass);\n total += grade.getValue();\n }\n return total;\n }\n</code></pre>\n\n<p>Note that I've hidden away the scanner behind a UserInterface interface, in order to separate calculation from UI code.</p>\n\n<p>It's implemented by the ConsoleUI class :</p>\n\n<pre><code>class ConsoleUI implements UserInterface {\n Scanner myScanner = new Scanner(System.in);\n\n @Override\n public Grade askGradeFor(GradedClass gradedClass) {\n System.out.println(MessageFormat.format(\"What is your grade for {0}?\", gradedClass));\n String input = myScanner.findWithinHorizon(\".\", 0);\n return Grade.valueOf(input.toUpperCase());\n }\n\n @Override\n public void presentGpa(double gpa) {\n if (gpa > 3d) {\n System.out.println(\"Great job, you're on your way to success.\");\n } else if (gpa > 2d) {\n System.out.println(\"You did OK, but better than average.\");\n } else {\n System.out.println(\"You didn't do too well. You should look into getting a tutor.\");\n }\n }\n\n}\n</code></pre>\n\n<p>The Main class simply ties everything together :</p>\n\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n UserInterface ui = new ConsoleUI();\n GpaCalculator gpaCalculator = new GpaCalculator(ui);\n\n double gpa = gpaCalculator.calculateGpa();\n ui.presentGpa(gpa);\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:03:48.307",
"Id": "28415",
"ParentId": "28406",
"Score": "7"
}
},
{
"body": "<ul>\n<li>First off try to think all the logics and behavior of your <code>GpaCalculator</code> and seperate them in classes. </li>\n<li>Like bowmore suggested you could use <code>enum</code> which is flexible for your code. </li>\n</ul>\n\n<p>This is my version for your code. </p>\n\n<ul>\n<li>Also try to think about the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/\" rel=\"nofollow\">exceptions</a> that can be raised from the code such as <code>IllegalGradeException</code>.</li>\n</ul>\n\n<p><strong>GradeCalculator class</strong></p>\n\n<pre><code> package com.se.cr;\n\n import java.util.Scanner;\n\n public class GradeCalculator {\n\n private final int NUMBER_OF_CLASSES;\n private Scanner myScanner = new Scanner(System.in);\n\n // Default constructor\n public GradeCalculator(){\n this(6); // By default number of classes are 6\n }\n\n // Customize constructor\n public GradeCalculator(int NUMBER_OF_CLASSES){\n this.NUMBER_OF_CLASSES = NUMBER_OF_CLASSES;\n }\n\n public double calculateGPA(){\n final double GPA = this.calculateSum() / NUMBER_OF_CLASSES;\n return GPA;\n }\n\n protected double calculateSum(){\n double sum = 0.0;\n for(int i = 1; i <= NUMBER_OF_CLASSES; i++){\n sum += this.gradeValue(i);\n }\n return sum;\n }\n\n /**\n * \n * @param classNumber \n * @return grade of that particular <code> classNumber </code>\n */\n protected double gradeValue(int classNumber){\n System.out.print(\"What is your grade for class \" + classNumber + \" ? \");\n char gradeChar = myScanner.next().toLowerCase().charAt(0);\n\n while(gradeChar < 'a' || gradeChar > 'f'){\n System.out.println(\"Wrong choice\"); // raise an exception here and handle it\n System.out.print(\"What is your grade for class \" + classNumber + \" ? \");\n gradeChar = myScanner.next().toLowerCase().charAt(0);\n }\n return this.toGradeValue(gradeChar);\n }\n\n /**\n * \n * @param grade\n * @return numeric representation of <code> grade </code>\n */\n public double toGradeValue(char grade){\n double gradeValue = 0.0;\n switch (grade) {\n case 'a': gradeValue = 5.0; break;\n case 'b': gradeValue = 4.0; break;\n case 'c': gradeValue = 3.0; break;\n case 'd': gradeValue = 2.0; break;\n case 'e': gradeValue = 1.0; break;\n case 'f': gradeValue = 0.0; break;\n }\n return gradeValue;\n }\n }\n</code></pre>\n\n<p><strong>Teacher class</strong> [ you can also make this a separate class other than making it a main class, as bowmore suggested ].</p>\n\n<pre><code> package com.se.cr;\n\n public class Teacher {\n\n public static void main(String[] args) {\n GradeCalculator calculator = new GradeCalculator();\n final double GPA = calculator.calculateGPA();\n\n Teacher teacher = new Teacher();\n teacher.takeDecision(GPA); \n }\n\n /**\n * Teacher will take decision on the basis of <code> GPA </code> \n * @param GPA \n */\n protected void takeDecision(final double GPA){\n System.out.println(\"Your GPA is \" + GPA);\n if (GPA > 3.00) {\n System.out.println(\"Gret job, you're on your way to success.\");\n } else if (GPA > 2.00) {\n System.out.println(\"You did OK, but better than average.\");\n } else {\n System.out.println(\"You didn't do too well. You should look into getting a tutor.\");\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:35:22.053",
"Id": "28417",
"ParentId": "28406",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T08:45:21.010",
"Id": "28406",
"Score": "6",
"Tags": [
"java",
"beginner"
],
"Title": "Simplifying GPA calculator"
}
|
28406
|
<p>I have a User class that will throw an exception if the userid provided in the parameter does not correspond with a user.</p>
<p>I've written a helper function that will return true or false depending on whether a userid belongs to a user or not, but was wondering if my use of a try {} catch {} to do so is correct:</p>
<pre><code> private function userExists($userid)
{
$user_does_not_exist = false;
try
{
$user = new User($userid);
}
catch (Exception $e)
{
$user_does_not_exist = true;
}
return $user_does_not_exist;
}
</code></pre>
<p>Any and all critique is greatly appreciated.</p>
|
[] |
[
{
"body": "<p>I would suggest working the other way around. Expect that a user does not exist and only return true if a user is found.</p>\n\n<pre><code>private function UserExists($userId)\n{\n $userExists = false;\n\n try\n {\n $user = new User($userId);\n if($user !== null)\n $userExists = true;\n }\n catch (Exception $e)\n {\n //handle exception\n }\n\n return $userExists;\n}\n</code></pre>\n\n<p>You can drive this further and ease things by not using a variable to return, like this:</p>\n\n<pre><code>private function UserExists($userId)\n{\n try\n {\n return new User($userId) !== null;\n }\n catch (Exception $e)\n {\n return false; \n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T13:03:39.583",
"Id": "28414",
"ParentId": "28413",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28414",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T12:52:23.517",
"Id": "28413",
"Score": "1",
"Tags": [
"php",
"exception"
],
"Title": "Function that uses an exception to check if user exists"
}
|
28413
|
<p>I'm not sure that I fully understand this pattern. I've written a simple application that uses MVC. Please criticize my approach to the use of this pattern. For convenience, I'll post the source code of the main classes. The source code of the project can be found here: <a href="https://github.com/Leonideveloper/SoundLights/tree/master/SoundLights/src/main">SoundLights on GitHub</a></p>
<p>The app has one screen. Screen background might have 4 different images. To change current screen background the user is using Next and Previous buttons. Buttons Play and Pause(Stop) are used to control for the soundlights. The soundlights is matrix of colored squares (translucent squares, kind of filters).</p>
<p>I've used 2 different models:</p>
<ul>
<li><em>BackgroundModel</em> - to process changing background</li>
<li><em>SoundLightsModel</em> - for working with the soundlights.</li>
</ul>
<p><strong>SoundLightsActivity.java</strong></p>
<pre><code>public class SoundLightsActivity extends Activity {
private SoundLightsController controller;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
controller = new SoundLightsControllerImpl(this);
}
@Override
protected void onDestroy() {
controller.onDestroy();
super.onDestroy();
}
}
</code></pre>
<p><strong>SoundLightsController.java</strong></p>
<pre><code>public interface SoundLightsController {
void onStart();
void onStop();
void onDestroy();
void onPrevious();
void onNext();
}
</code></pre>
<p><strong>SoundLightsControllerImpl.java</strong></p>
<pre><code>public class SoundLightsControllerImpl implements SoundLightsController {
private final SoundLightsModel soundLightsModel;
private final SoundLightsView view;
private final BackgroundModel backgroundModel;
public SoundLightsControllerImpl(Activity activity) {
this.view = new SoundLightsViewImpl(activity, this);
this.soundLightsModel = new SoundLightModelImpl(view);
this.backgroundModel = new BackgroundModelImpl(view, (Context) activity);
}
@Override
public void onStart() {
view.setInvisibleStartButton();
view.setVisibleStopButton();
soundLightsModel.startSoundLights();
}
@Override
public void onStop() {
soundLightsModel.stopSoundLights();
view.setVisibleStartButton();
view.setInvisibleStopButton();
}
@Override
public void onDestroy() {
soundLightsModel.stopSoundLights();
}
@Override
public void onPrevious() {
backgroundModel.toPreviousBackground();
}
@Override
public void onNext() {
backgroundModel.toNextBackground();
}
}
</code></pre>
<p><strong>SoundLightsView.java</strong></p>
<pre><code>public interface SoundLightsView {
void setVisibleStartButton();
void setInvisibleStartButton();
void setVisibleStopButton();
void setInvisibleStopButton();
void setColor(Matrix.Position pos, int color);
Dimension getColorMatrixDimension();
void setBackgroundById(int id);
}
</code></pre>
<p><strong>SoundLightsViewImpl.java</strong></p>
<pre><code>public class SoundLightsViewImpl implements SoundLightsView {
private final ColorMatrixView colorMatrixView;
private final ImageButton startButton;
private final ImageButton stopButton;
private final SoundLightsController controller;
private final ImageButton prevButton;
private final ImageButton nextButton;
private final RelativeLayout rootLayout;
public SoundLightsViewImpl(Activity activity, SoundLightsController controller) {
activity.setContentView(R.layout.soundlights_activity);
this.controller = controller;
colorMatrixView = (ColorMatrixView) activity.findViewById(R.id.colorMatrixView);
startButton = (ImageButton) activity.findViewById(R.id.startButton);
stopButton = (ImageButton) activity.findViewById(R.id.stopButton);
prevButton = (ImageButton) activity.findViewById(R.id.prevButton);
nextButton = (ImageButton) activity.findViewById(R.id.nextButton);
rootLayout = (RelativeLayout) activity.findViewById(R.id.rootLayout);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SoundLightsViewImpl.this.controller.onStart();
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SoundLightsViewImpl.this.controller.onStop();
}
});
prevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SoundLightsViewImpl.this.controller.onPrevious();
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SoundLightsViewImpl.this.controller.onNext();
}
});
}
@Override
public void setVisibleStartButton() {
startButton.setVisibility(View.VISIBLE);
}
@Override
public void setInvisibleStartButton() {
startButton.setVisibility(View.INVISIBLE);
}
@Override
public void setVisibleStopButton() {
stopButton.setVisibility(View.VISIBLE);
}
@Override
public void setInvisibleStopButton() {
stopButton.setVisibility(View.INVISIBLE);
}
@Override
public void setColor(Matrix.Position pos, int color) {
colorMatrixView.setColor(pos, color);
}
@Override
public Dimension getColorMatrixDimension() {
return colorMatrixView.getDimension();
}
@Override
public void setBackgroundById(int id) {
rootLayout.setBackgroundResource(id);
}
}
</code></pre>
<p><strong>SoundLightsModel.java</strong></p>
<pre><code>public interface SoundLightsModel {
void startSoundLights();
void stopSoundLights();
}
</code></pre>
<p><strong>SoundLightModelImpl.java</strong></p>
<pre><code>public class SoundLightModelImpl implements SoundLightsModel, Runnable {
private static final long DELAY_IN_MILLISECONDS = 6;
private final SoundLightsView view;
private final PositionRandomizer positionRandomizer;
private final ColorRandomizer colorRandomizer;
private PeriodicallyTask singlePeriodicallyTask;
public SoundLightModelImpl(SoundLightsView view) {
this.view = view;
positionRandomizer = new PositionRandomizer();
colorRandomizer = new ColorRandomizer();
}
@Override
public void startSoundLights() {
singlePeriodicallyTask = new PeriodicallyTask();
singlePeriodicallyTask.start(this, DELAY_IN_MILLISECONDS);
}
@Override
public void stopSoundLights() {
if (singlePeriodicallyTask != null) {
singlePeriodicallyTask.stop();
singlePeriodicallyTask = null;
}
}
@Override
public void run() {
randomUpdateColor();
}
private synchronized void randomUpdateColor() {
Dimension dim = view.getColorMatrixDimension();
Matrix.Position randomPosition = positionRandomizer.randomPosition(dim);
int randomColor = colorRandomizer.randomColor();
view.setColor(randomPosition, randomColor);
}
}
</code></pre>
<p><strong>PeriodicallyTask.java</strong></p>
<pre><code>public class PeriodicallyTask {
private boolean stopped;
private Handler handler;
private Runnable periodicallyRunnable;
public void start(final Runnable runnable, final long delayInMilliseconds) {
handler = new Handler();
stopped = false;
periodicallyRunnable = new Runnable() {
@Override
public void run() {
synchronized (this) {
runnable.run();
if (!stopped) {
handler.postDelayed(periodicallyRunnable, delayInMilliseconds);
}
}
}
};
periodicallyRunnable.run();
}
public void stop() {
synchronized (this) {
handler.removeCallbacks(periodicallyRunnable);
stopped = true;
}
}
}
</code></pre>
<p><strong>BackgroundModel.java</strong></p>
<pre><code>public interface BackgroundModel {
void toPreviousBackground();
void toNextBackground();
}
</code></pre>
<p><strong>BackgroundModelImpl.java</strong></p>
<pre><code>public class BackgroundModelImpl implements BackgroundModel {
private static final int[] backgroundResourcesIds = new int[] {
R.drawable.thais1, R.drawable.thais2, R.drawable.thais3, R.drawable.thais4
};
private final SoundLightsView view;
private int currentIdIndex;
public BackgroundModelImpl(SoundLightsView view, Context context) {
this.view = view;
currentIdIndex = 0;
changeViewBackground();
}
private void changeViewBackground() {
view.setBackgroundById(backgroundResourcesIds[currentIdIndex]);
}
@Override
public void toPreviousBackground() {
currentIdIndex = previousIdIndex();
changeViewBackground();
}
private int previousIdIndex() {
return currentIdIndex > 0
? (currentIdIndex - 1)
: (backgroundResourcesIds.length - 1);
}
@Override
public void toNextBackground() {
currentIdIndex = nextIdIndex();
changeViewBackground();
}
private int nextIdIndex() {
return currentIdIndex < backgroundResourcesIds.length - 1
? (currentIdIndex + 1)
: 0;
}
}
</code></pre>
<p><strong>Randomizer.java</strong></p>
<pre><code>public class Randomizer {
public static int randomPositiveInt() {
Random random = new Random(System.currentTimeMillis());
random.setSeed(System.nanoTime());
return Math.abs(random.nextInt());
}
}
</code></pre>
<p><strong>ColorRandomizer.java</strong></p>
<pre><code>public class ColorRandomizer {
private static final int MAX_ALPHA_COMPONENT = 45;
public static int randomColor() {
int alpha = Randomizer.randomPositiveInt() % MAX_ALPHA_COMPONENT;
int red = Randomizer.randomPositiveInt() % 256;
int green = Randomizer.randomPositiveInt() % 256;
int blue = Randomizer.randomPositiveInt() % 256;
return Color.argb(alpha, red, green, blue);
}
}
</code></pre>
<p><strong>PositionRandomizer.java</strong></p>
<pre><code>public class PositionRandomizer {
private Matrix.Position prevPosition = null;
public Matrix.Position randomPosition(Dimension dim) {
int row = Randomizer.randomPositiveInt() % dim.rows;
int column = Randomizer.randomPositiveInt() % dim.columns;
return new Matrix.Position(row, column);
}
private synchronized Matrix.Position nextPosition(Dimension dim) {
Matrix.Position next =
prevPosition == null
? new Matrix.Position(0, 0)
: nextPosition(prevPosition, dim);
prevPosition = next;
return next;
}
private Matrix.Position nextPosition(Matrix.Position prevPosition, Dimension dim) {
int column = prevPosition.column + 1;
int row = prevPosition.row;
if (column >= dim.columns) {
column = 0;
++row;
if (row >= dim.rows) {
row = 0;
}
}
return new Matrix.Position(row, column);
}
}
</code></pre>
<p><strong>ColorMatrixView.java</strong></p>
<pre><code>public class ColorMatrixView extends FrameLayout {
private static final int DEF_ROWS = 3;
private static final int DEF_COLUMNS = 2;
private static final int DEF_COLOR = Color.argb(35, 100, 150, 69);
private int rows = DEF_ROWS;
private int columns = DEF_COLUMNS;
private int initColor = DEF_COLOR;
private Context context;
private Matrix<View> matrixElements;
public ColorMatrixView(Context context) {
super(context);
init(context);
}
public ColorMatrixView(Context context, AttributeSet attrs) {
super(context, attrs);
processAttributes(context, attrs);
init(context);
}
public ColorMatrixView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
processAttributes(context, attrs);
init(context);
}
private void processAttributes(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(
attrs, R.styleable.ColorMatrixView);
final int N = typedArray.getIndexCount();
for (int i = 0; i < N; ++i) {
int index = typedArray.getIndex(i);
switch (index)
{
case R.styleable.ColorMatrixView_rows:
this.rows = typedArray.getInt(index, DEF_ROWS);
break;
case R.styleable.ColorMatrixView_columns:
this.columns = typedArray.getInt(index, DEF_COLUMNS);
break;
case R.styleable.ColorMatrixView_initColor:
this.initColor = typedArray.getColor(index, DEF_COLOR);
break;
}
}
typedArray.recycle();
}
private void init(Context context) {
this.context = context;
init();
}
private void init() {
LinearLayout verticalLayout = prepareLinearLayout(LinearLayout.VERTICAL);
matrixElements = new Matrix<View>(rows, columns);
for (int row = 0; row < rows; ++row) {
LinearLayout rowLayout = prepareLinearLayout(LinearLayout.HORIZONTAL);
for (int column = 0; column < columns; ++column) {
View element = prepareColorMatrixElement();
rowLayout.addView(element);
matrixElements.set(new Matrix.Position(row, column), element);
}
verticalLayout.addView(rowLayout);
}
addView(verticalLayout);
}
private LinearLayout prepareLinearLayout(int orientation) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(orientation);
addParams(layout);
return layout;
}
private View prepareColorMatrixElement() {
View tableElement = new ImageView(context);
addParams(tableElement);
tableElement.setBackgroundColor(initColor);
return tableElement;
}
private void addParams(View view) {
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT,
1.0f);
view.setLayoutParams(param);
}
public void setColor(Matrix.Position pos, int color) {
setColor(pos.row, pos.column, color);
}
public void setColor(int row, int column, int color) {
View element = matrixElements.get(row, column);
element.setBackgroundColor(color);
}
public Dimension getDimension() {
return new Dimension(rows, columns);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I've only skimmed through, and all I could find is a <code>bool stopped</code> which I would have called <code>bool isStopped</code>, although <code>stopped</code> is a fairly unambiguous, clear name - as is the rest of this code.</p>\n\n<p>Oh, and maybe the <code>256</code> hard-coded into your <code>ColorRandomizer</code> could be a constant.</p>\n\n<p>Naming is crystal-clear and consistent, indentation is perfect; simple, neat, ...nothing to add.</p>\n\n<hr>\n\n<p>As for MVC, well I can't talk about Java specifics (never wrote a line of Java), but <em>design patterns</em> are a mean of communication, so when you say \"I do X in my <em>controller</em>\", fellow programmers know what you're talking about.</p>\n\n<ul>\n<li>The <strong>Model</strong> contains <em>data that the View needs to render</em>.</li>\n<li>The <strong>View</strong> contains your markup.</li>\n<li>The <strong>Controller</strong> receives a request and responds with a <em>view</em>.</li>\n</ul>\n\n<p>Given that, I believe your <em>model</em> should know nothing about a <em>view</em> - rather, it's the opposite: the <em>view</em> needs to know about the <em>model</em>. Now I'd love to see another answer from an actual Java developer, because I've only done MVC with ASP.NET in C#, so I'm hoping for this to be confirmed or corrected :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T13:54:24.797",
"Id": "58114",
"Score": "1",
"body": "upvote, but I think it's important to mention that the view should only know the model through the controller. So for someone who doesn't know about MVC it's important to mention that it's the controller that communicate between the model and the view"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T13:54:39.387",
"Id": "58115",
"Score": "2",
"body": "I don't agree with the renaming suggestion (`isStopped` should be the name for the getter, if there should be one, which returns `stopped`), otherwise I totally agree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T13:57:03.027",
"Id": "58116",
"Score": "0",
"body": "@user1021726 Although theoretically correct, I myself often implement it so that the view actually knows about the model. And I've seen many other examples that seems to do it that way. (This is just my opinion though)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T13:57:52.300",
"Id": "58117",
"Score": "0",
"body": "In ASP.NET/MVC the view *explicitly* knows about the model."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T14:06:16.410",
"Id": "58120",
"Score": "0",
"body": "@user1021726 [People don't always agree about the MVC concept](http://stackoverflow.com/questions/3742018/in-ideal-mvc-should-the-view-know-the-model) (also read the comments)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T02:36:28.773",
"Id": "35740",
"ParentId": "28419",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "35740",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T14:43:41.410",
"Id": "28419",
"Score": "5",
"Tags": [
"java",
"design-patterns",
"mvc",
"android"
],
"Title": "First introduction to MVC"
}
|
28419
|
<p>I'm getting data to fill out an e-mail template, and I'm wondering if this method is too long. How could I refactor it?</p>
<pre><code>sub getEmailData
{
my $self = shift;
my $defs = QuickContentFunction::Simple::QuerySearchFieldDefinitions->new();
my $phParams = decode_json($self->parameters);
my @aFields = split(/~/, $phParams->{sFields});
my @aCategories = split(/~/, $phParams->{sCategories});
my @aValues = split(/~/, $phParams->{sValues});
my @aConditions = split(/~/, $phParams->{sConditions});
my $sSummary = $phParams->{sSummary};
$sSummary =~ s/\'//g;
my @aSummary = split(/\d/, $sSummary);
my $phData = { name => $self->name };
my $mapping = $self->getOperatorMapping();
for (my $i = 0; $i < scalar(@aFields); $i++) {
my $phFieldInfo = $defs->getFieldHash( $aCategories[$i], $aFields[$i]);
my $value = $aValues[$i];
if ($phFieldInfo->{value_displays}) {
$value = @{$phFieldInfo->{value_displays}}[$value];
} elsif ($phFieldInfo->{value_keys}) {
$value = @{$phFieldInfo->{value_keys}}[$value];
}
push( @{$phData->{conditions}}, {
field => $phFieldInfo->{field_display},
operator => $mapping->{$phFieldInfo->{field_type}}->{$aConditions[$i]},
value => $value,
postfix => $aSummary[$i+1] || undef
} );
}
$phData->{mode} = lc($phParams->{sMode});
if ($self->hasResults()) {
$phData->{deals} = \@{decode_json($self->result)};
}
return $phData;
}
</code></pre>
|
[] |
[
{
"body": "<p>First off, stuff like <code>my @aFields = split(/~/, $phParams->{sFields});</code> is a sign of something gone awry. You've just deserialized <code>$phParams</code> from a JSON object, so why isn't this just stored in a normal array?</p>\n\n<p>There is no need to write <code>$i < scalar(@aFields)</code>, just write <code>$i < @aFields</code>.</p>\n\n<p>I have some comments wrt. this snippet:</p>\n\n<pre><code>my $value = $aValues[$i];\nif ($phFieldInfo->{value_displays}) {\n $value = @{$phFieldInfo->{value_displays}}[$value];\n} elsif ($phFieldInfo->{value_keys}) {\n $value = @{$phFieldInfo->{value_keys}}[$value];\n}\n</code></pre>\n\n<p>You should always <code>use warnings;</code> and <code>use strict;</code>. The above won't run without warnings if warnings are on because <code>@{$phFieldInfo->{value_keys}}[$value]</code> should be written <code>${$phFieldInfo->{value_keys}}[$value]</code>.</p>\n\n<p>Also, the whole thing can be written much shorter:</p>\n\n<pre><code>my $value = ${$phFieldInfo->{value_displays}}[$aValues[$i]]\n || ${$phFieldInfo->{value_keys}}[$aValues[$i]]\n || $aValues[$i];\n</code></pre>\n\n<p><em>Note:</em> this isn't functionally identical with the original code, since I'm assuming that array refs at the keys <code>value_displays</code> and <code>value_keys</code> exists. </p>\n\n<p>This essentially means \"pick the first trueish value\". Note that values like undef, <code>0</code> or the empty string won't be picked. If you want to be able to pick <code>0</code> or the empty string, replace <code>||</code> with <code>//</code>. This requires a recent version of perl (read: not ancient).</p>\n\n<p>The rest looks reasonable. Fixing the stuff I suggested should cut the size a little, and I wouldn't try shortening it further.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T21:14:49.683",
"Id": "44605",
"Score": "0",
"body": "awesome, thanks a lot! The reason the data is stored as a JSON is beyond my control, but I agree, it shouldn't be that way. I actually do have `use warnings` on, but we're on perl version 5.8..could that be why it didn't throw anything? I like your `|| ... ||` construct. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T04:59:10.983",
"Id": "44639",
"Score": "0",
"body": "It should warn even with perl 5.8. That's odd. By the way - using strict is more important than warnings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T21:18:17.463",
"Id": "44664",
"Score": "0",
"body": "there are few problems with `||`; first `$value` is defined with `my` and used on the same line; second `$value` should start with contents of `$aValues[$i]`; third `undef` or other false value will continue evaluation unlike in OP; and last, autovivification will take place unlike in OP. First two are essential problems while others may not spoil OP logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T22:04:08.177",
"Id": "44667",
"Score": "0",
"body": "You're right. I didn't spot that ``$value`` is being reused. Duh."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T22:09:47.730",
"Id": "44669",
"Score": "0",
"body": "I believe I've fixed it now. I'm not used to code where data is being set and reset in this way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T23:18:47.100",
"Id": "44713",
"Score": "0",
"body": "I caught that as well, I think the current form is appropriate for my needs. I was using strict as well, btw."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:42:43.810",
"Id": "44731",
"Score": "0",
"body": "Looking at the code above, I see that I still haven't got it right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:48:20.267",
"Id": "44733",
"Score": "0",
"body": "I've added a note to help others that read my suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T13:26:24.663",
"Id": "44753",
"Score": "0",
"body": "Ok, now I see. This is actually not what I want, since I need to check if $phfieldInfo->{value_keys} exists. Any other ideas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T15:47:11.910",
"Id": "44761",
"Score": "0",
"body": "Not really since it isn't an obfuscation contest :) If you just wanted it short and didn't care about readability, you could nest ternary select operators (``<boolean expression> ? <something> : <something else>``), but assuming that the next developer to work with your code is an angry axe murderer who knows where you live - not including yourself (quoted from Damian Conway), you probably shouldn't do that."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T20:10:50.360",
"Id": "28427",
"ParentId": "28425",
"Score": "4"
}
},
{
"body": "<p>Some of the replaced lines are left as comments.</p>\n\n<pre><code>sub getEmailData {\n my $self = shift;\n\n my $defs = QuickContentFunction::Simple::QuerySearchFieldDefinitions->new();\n\n my $phParams = decode_json($self->parameters);\n # my @aFields = split(/~/, $phParams->{sFields});\n # my @aCategories = split(/~/, $phParams->{sCategories});\n # my @aValues = split(/~/, $phParams->{sValues});\n # my @aConditions = split(/~/, $phParams->{sConditions});\n\n my ($aFields, $aCategories, $aValues, $aConditions) = \n map [ split /~/, $phParams->{$_} ],\n qw(sFields sCategories sValues sConditions);\n\n my $sSummary = $phParams->{sSummary};\n $sSummary =~ tr|'||d; # s/\\'//g;\n my @aSummary = split(/\\d/, $sSummary);\n\n my $phData = { name => $self->name };\n\n my $mapping = $self->getOperatorMapping();\n # for (my $i = 0; $i < scalar(@aFields); $i++) \n for my $i (0 .. $#$aFields) {\n my $phFieldInfo = $defs->getFieldHash( $aCategories->[$i], $aFields->[$i]);\n\n my $value = $aValues->[$i];\n if ($phFieldInfo->{value_displays}) {\n $value = $phFieldInfo->{value_displays}[$value];\n } \n elsif ($phFieldInfo->{value_keys}) {\n $value = $phFieldInfo->{value_keys}[$value];\n }\n\n push @{$phData->{conditions}}, {\n field => $phFieldInfo->{field_display},\n operator => $mapping->{ $phFieldInfo->{field_type} }{ $aConditions->[$i] },\n value => $value,\n postfix => $aSummary[$i+1] || undef\n };\n }\n\n $phData->{mode} = lc($phParams->{sMode});\n if ($self->hasResults()) {\n # $phData->{deals} = \\@{decode_json($self->result)};\n $phData->{deals} = decode_json($self->result);\n }\n\n return $phData;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T23:20:13.653",
"Id": "44714",
"Score": "0",
"body": "I can't tell if the `#$aFields` is a comment...so is it `for my $i (0 .. $aFields)` ? What version of perl is required?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T07:05:38.333",
"Id": "44737",
"Score": "0",
"body": "any perl5 is fine, `$aFields` is array reference so `$#$aFields` is last index for that array (if you're more comfortable with brackets then `$#{$aFields}`)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T21:07:14.103",
"Id": "28442",
"ParentId": "28425",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T18:57:39.863",
"Id": "28425",
"Score": "0",
"Tags": [
"perl"
],
"Title": "Preparing search criteria and results to be e-mailed"
}
|
28425
|
<p>While working with someone else's code I've isolated a time-killer in the (very large) script. Basically this program runs through a list of thousands and thousands of objects to find matches to an input (or many inputs) object. It works well when the number is below 50 but any input higher than that and it begins to take a looooong time. Is this just an issue with the database I'm running it against (30,000 things)? Or is this code written inefficiently?</p>
<pre><code>for i in range(BestX):
Tin=model[BestFitsModel[0][i]][2]
Tau2=np.append(Tau2,model[BestFitsModel[0][i]][6])
Dir=model[BestFitsModel[0][i]][0]
Dir=Dir.replace('inp','out',1) ##open up correct .out file
T=open(Dir,"rb")
hold=''
Tau=[]
for line in T:
if not line.strip():
continue
else:
hold=line.split()
Tau.append(hold)
Tauline=0
Taunumber=0
print 'Loop'
for j in range(5,len(Tau)-50):
if 'RESULTS:' in Tau[j-5][0]:
for k in range(j,j+50):
if (Tau[k][1] == model[BestFitsModel[0][i]][6]):
Tauline=i #line number of the tau
Taunumber=k-(j) #Tau 1, 2, 3, etc.
Dir=Dir.replace('out','stb',1)#.stb file
Dir2=np.append(Dir2,Dir)
F=open(Dir, "rb")
hold=''
Spectrum=[]
for line in F:
hold=line.split()
Spectrum.append(hold)
</code></pre>
<p>BestX is a list of 30,000 objects (stars).</p>
<p>I'm not looking for an answer to this problem, I'm looking for code-critique...there has to be a way to write this so that it performs faster, right?</p>
<p>Thanks.</p>
<p><strong>EDIT</strong>: Reading through the <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips" rel="nofollow">Python Performance Tips</a> I've noticed one little snag (so far). Starting with the line <code>Tau=[]</code> and continuing for the next six lines. I can shorten it up by </p>
<pre><code>Tau=[line.split() for line in T]
</code></pre>
<p>I'm gonna keep looking. Hopefully I'm on the right track.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T21:34:43.993",
"Id": "44608",
"Score": "0",
"body": "Can you clarify a bit further what this is supposed to do and what 'number' you are referring to exactly? The number of input objects? Are the stars in BestX the input objects? Also, with >50 objects, does it work slowly but correctly, or does it not work at all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T21:40:23.687",
"Id": "44609",
"Score": "0",
"body": "Yeah, sorry for being 'nebulous' (drumroll). The BestX file is the file I'm matching my input stars to. If I put in a star it might have 5 matches in that file (I called it a database), or it could have 1000+, when it has a high number of matches it begins to get bogged down dramatically. What this does after it finds the matches -moving down the script- is computes some stellar values of some characteristic or another to give me an averaged value over all the matches for whatever property I'm searching for. I ran a lot of checks and isolated it to this exact region of the code. Need more?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T21:48:37.137",
"Id": "44610",
"Score": "0",
"body": "@Stuart (more) these files I'm searching through are easily less than a gigabyte. That's why I think it's the code structure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T22:04:38.633",
"Id": "44611",
"Score": "0",
"body": "as a first improvement try to give the variables more descriptive names. This should make it easier to understand what's going on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T22:07:57.820",
"Id": "44612",
"Score": "0",
"body": "Your edit improving the code actually changes what it does. What you need is `Tau = [line.split() for line in T if line.strip()]`, i.e. only include the line if it is contains something other than spaces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T22:18:20.487",
"Id": "44613",
"Score": "0",
"body": "I'm doubtful that this code actually works. If there are fewer than 56 lines in `Tau` then the loop `for j...` never actually runs. Is anything done with the variables `Tauline` and `Taunumber`? If so, is that within the `for i...` loop or afterwards? (Also, can you check the indentation as it seems wrong in what you have pasted here). I suspect what is intended is actually to break out of all three loops (i, j, and k) as soon as a match is found; but instead the loops carry on iterating regardless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T22:27:56.370",
"Id": "44614",
"Score": "0",
"body": "Yeah this whole script is wacky. I've been working with it for a while trying to make it better, but I'm not that good so it's really really painful. I timed the script (by importing datetime) and it took roughly 38 seconds to complete and that was only working with 69 matches it found out of the larger file. I ran it with a different parameter (to boost the possible matches) and just shut it down after a few minutes out of frustration."
}
] |
[
{
"body": "<p>Some guesswork here but I think what you want is actually something like this:</p>\n\n<pre><code>def match_something(file, match):\n \"\"\" Finds a line in file starting with 'RESULTS:' then checks the following 50\n lines for match; if it fails returns None, otherwise it returns\n how many lines down from the 'RESULTS:' heading the match is found\n \"\"\"\n in_results_section = False\n results_counter = 0\n for line in file:\n if line.strip():\n if results_header_found:\n if line.split()[1] == match:\n return results_counter # found a match\n else:\n results_counter += 1\n if results_counter > 50:\n return None \n# I'm assuming in the above that there can only be one results section in each file\n\n elif line.startswith('RESULTS:'):\n results_header_found = True\n\nmatched_results = [] \nfor i in range(BestX):\n thing = model[BestFitsModel[0][i]]\n\n # make variables with descriptive names \n directory, input_thing, match = thing[0], thing[2], thing[6]\n list_of_matches = np.append(list_of_matches, match)\n with open(directory.replace('inp', 'out', 1), 'rb') as file:\n m = match_something(file, match)\n if m is not None:\n matched_results.apppend((i, m))\n stb_directory = directory.replace('inp', 'stb', 1), 'rb')\n np.append(directory_list, stb_directory)\n with open(stb_directory, 'rb') as file:\n spectrum = [line.split() for line in file] \n</code></pre>\n\n<p>This uses a function <code>match_something</code> to go through the file. As soon as a result is found, the function exits (<code>return i, results_counter</code>) and then the main loop adds this result to a list of matched results. If no result is found within 50 lines of the line starting 'RESULTS:' then the function returns None, and the loop moves to the next line of <code>BestFitsModel[0]</code>. (If, on the other hand, there can be more than one results section within each file, then you need to alter this accordingly; it should carry on checking the rest of the file rather than returning, which will be slower.) I hope it should be fairly clear what is happening in this code; it should avoid looping through anything unnecessarily (assuming I've guessed correctly what it's supposed to do)</p>\n\n<p>In the original code, it seems that the files are not closed (<code>T.close()</code>), which could cause problems later on in the programme. Using the <code>with</code> notation avoids the need for this in the above code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T23:35:48.180",
"Id": "28430",
"ParentId": "28428",
"Score": "2"
}
},
{
"body": "<p>You are opening the file(never closing it) and then using a <code>for</code> loop. Try using the <code>with</code> statement and list comprehension to open, close and get your list. This goes for both <code>Tau</code> and <code>Spectrum</code>.</p>\n\n<p><code>np</code> and <code>Dir</code> are declared before the loop starts so you can declare\n<code>np_appends =np.append</code> and <code>dir_replace = Dir.replace</code>. For the reason see the part \"Avoiding the dots...\" in Python performance Tips. </p>\n\n<p>You can try to use <code>xrange</code> instead of <code>range</code> if you are on Python 2. Using generators might be better instead of creating the whole list. You'll have to time this.</p>\n\n<p>This isn't much but might be helpful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T05:51:00.673",
"Id": "28485",
"ParentId": "28428",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T21:21:04.760",
"Id": "28428",
"Score": "0",
"Tags": [
"python"
],
"Title": "Is there a better, more efficient way to write this loop?"
}
|
28428
|
<p>I want to verify that I'm correctly handling risk of "Overflowing fixed-length string buffers." I'm also aware that I'm using C-style strings, which falls short of full C++ code.</p>
<p><strong>Main</strong></p>
<pre><code>/*
PURPOSE:
attempt to implement, without using given/known-good code, various concepts
of c++.
one exception:
code in header fileToArray/set_cArrayTemp()
*/
//MOVED TO TOP - ELSE MY HEADERS FAIL
//boilerplate - won't have to use: std::
using namespace std;
//needed to use cout/cin
#include <iostream>
//for using system calls -
//warning: (www.cplusplus.com/forum/articles/11153/)
#include <cstdlib>
//to use strlen
#include <cstring>
//c++ headers (e.g. iostream) don't use .h extension so i am not either
//provides indentation and v spacing for logging
#include "header/logFormatter"
//reads a file to a char array
#include "header/fileToArray"
//dialog gets filename from user
#include "header/fileDialog"
//this is the (p)array that should hold all the text from the file
char *cArray;
//the name of the file to read
char *fileName;
void set_fileName(){
cout << vspace << col1 << "begin set_fileName()";
char *temp = getFileName();
cout << col2 << "tmp: " << temp;
fileName = new char[strlen(temp)];
strcpy(fileName,temp);
delete[] temp;
cout << col2 << "fileName is set: " << fileName;
cout << col1 << "end set_fileName()";
}
void set_cArray(){
cout << vspace << col1 << "begin set_cArray()";
char *temp = fileToArray(fileName);
if(temp){
cout << col2 << "tmp: " << temp;
/*FROM MAN STRCPY:
"If the destination string of a strcpy() is not large enough,
then anything might happen. Overflowing fixed-length string
buffers is a favorite cracker technique for taking complete
control of the machine."
*/
//so, this guards against overflow, yes?
cArray = new char[strlen(temp)];
strcpy(cArray,temp);
delete[] temp;
cout << col2 << "cArray is set: " << cArray;
cout << col1 << "end set_cArray()";
return;
}
cout << col2 << "fail - did not set cArray";
cout << col1 << "end set_cArray()";
}
//expect memory leaks = 0
void cleanup(){
cout << vspace << col1 << "begin cleanup()";
if(cArray){
delete[] cArray;
cout << col2 << "cArray deleted";
}
if(fileName){
delete[] fileName;
cout << col2 << "fileName deleted";
}
cout << col1 << "end cleanup()";
}
void closingMessage(){
cout << vspace << col2 << "APPLICATION COMPLETE";
}
int main(){
system("clear;");/*yes, i know (www.cplusplus.com/forum/articles/11153/)...
,but it provides focus for the moment and it is simple. */
//col0
cout << "begin main()";
set_fileName();
set_cArray();
cleanup();
closingMessage();
cout << "\nend main()";
return 0;
}
//TODO -
//1. use a doWhile so that user can run once and read many files without
//app exit.
//
//2. find way to provide init (not null/safe sate) of pointers
</code></pre>
<p><strong>header (fileToArray):</strong></p>
<pre><code> //reads a file to a char array
//for using files
#include <fstream>
// user inputs a file [path]name
char *filenameTemp;
//this is the (p)array that should hold all the text from the file
char *cArrayTemp;
void set_filenameTemp(char *fileName_param){
cout << vspace << col3 << "begin set_filenameTemp()";
filenameTemp = new char[strlen(fileName_param)];
strcpy(filenameTemp,fileName_param);
cout << col4 << "file name assigned: " << filenameTemp;
cout << col3 << "end set_filenameTemp()";
}
void set_cArrayTemp(){
cout << vspace << col3 << "begin set_cArrayTemp()";
ifstream file(filenameTemp);
if(file.is_open()){
/*---------------------------------------------
source: www.cplusplus.com/doc/tutorials/files/
modified a bit*/
long begin,end,fileSize;
begin = file.tellg();
file.seekg(0,ios::end);
end = file.tellg();
fileSize = (end-begin-1);/* -1 because testing shows fileSize is always
one more than expected based on known lenght
of string in file.*/
/*---------------------------------------------*/
//cout << col4 << "bytes in file (fileSize=): " << fileSize;
cArrayTemp = new char[fileSize];
file.seekg(0,ios::beg);
file.read(cArrayTemp,fileSize);
file.close();
cout << col3 << "end set_cArrayTemp()";
return;
}
cout << col4 << "fail - file not open";
cout << col3 << "end set_cArrayTemp()";
}
//caller is responsible for memory
//may return null
char *fileToArray(char *fileName_param){
cout << vspace << col2 << "begin fileToArray()";
if(fileName_param){
cout << col3 << "file name received: " << fileName_param;
set_filenameTemp(fileName_param);
set_cArrayTemp();
delete[] filenameTemp;
cout << col2 << "end fileToArray()";
return cArrayTemp;
}
cout << col3 << "received NULL fileName_param";
cout << col2 << "end fileToArray()";
return cArrayTemp;
}
</code></pre>
<p><strong>header (fileDialog):</strong></p>
<pre><code> //dialog gets filename from user
// user inputs a file [path]name
//number of chars to get from user input
static const int size = 20;//20 will do for now
/*FROM MAN STRCPY:
"If the destination string of a strcpy() is not large enough,
then anything might happen. Overflowing fixed-length string
buffers is a favorite cracker technique for taking complete
control of the machine."
*/
//so, this guards against overflow, yes?
//that is, by using getline, rather than cin >> var,
//size of array is controlled.
//caller is responsible for memory
char *getFileName(){
cout << vspace << col2 << "begin getFileName()";
char* input = new char[size];
cout << col2 << "enter filename: ";
cin.getline(input,size);
cout << col2 << "end getFileName()";
return input;
}
//NOTE:
// currently, this hardly justifies a header file - i expect to do more later.
// may eventually use this for all userdialog and rename to userDialog
</code></pre>
<p><strong>header (logFormatter):</strong></p>
<pre><code> //STRICTLY FOR LOGGING
// spares me from managing chains of \n and \t
//this allows me to use indentation to show progress/flow
// making this a psuedo-debugger
//
//left-most column - col0 is imaginary/conceptual
//char col0 = "";
static const char col1[] = "\n ";//4 spaces
static const char col2[] = "\n ";//8 spaces
static const char col3[] = "\n ";// etc.
static const char col4[] = "\n ";
static const char vspace[] = "\n\n";
//NOTE: changed from using \t since default is 8 spaces
</code></pre>
|
[] |
[
{
"body": "<p>It is very apparent that you are new. That is fine; we were all new once. I'll try to adjust my feedback accordingly. Let me know if you are not familiar with some of the terminology, and I'll provide an explanation or definition.</p>\n\n<hr>\n\n<h3>Overflow safeguards</h3>\n\n<p>First of all, I'll discuss what seems to be the issue you are most concerned with: <strong>buffer overflows</strong>. I'd like to state that at this level, you should not really care about that (yet), at least not from a security standpoint. You should focus on learning the language and programming in general first.</p>\n\n<p>Your code is following the general correct idea: Make sure buffers are large enough by dynamically allocating memory, and limiting the size of input strings when you are not. Note that <code>std::string</code> does all of this for you by growing as needed.</p>\n\n<p>In modern C++ code, you would normally avoid allocating buffers the way you do, because memory management quickly becomes hard as a program grows. In C++, <a href=\"http://en.wikipedia.org/wiki/RAII\" rel=\"nofollow noreferrer\">the RAII pattern</a> is essential. It boils down to allocating resources in the constructor of an object (a class instance), and freeing them automatically in the destructor when the object goes out of scope. This is what <code>std::string</code> does for you, as well as growing as needed if you add text to the string.</p>\n\n<hr>\n\n<h2>High-level issues</h2>\n\n<h3>1. I strongly recommend you to <em>reduce the commenting level</em>.</h3>\n\n<p>I used to teach programming at the local university, and I saw that over-commenting \"technique\" a lot. My experience is that it not a good idea. <strong>It works as a crutch, allowing you to read your comments rather than your code.</strong> However, you already know how to read text; you need to learn how to read code. Stick to regular commenting levels. If you <em>must</em> have notes, keep them in a separate document. You want to make it as inconvenient as possible for you to look at them, forcing you to read the code itself when possible.</p>\n\n<h3>2. You are not writing C++.</h3>\n\n<p>You are writing C code, with C++ library calls. Write your own <code>String</code> class instead of using raw arrays in the code. Take advantage of all the things C++ has to offer. (This normally includes <code>std::string</code>, but writing your own <code>String</code> class for practice is a nice exercise.)</p>\n\n<h3>3. Your headers should not contain function definitions.</h3>\n\n<p>In C++, there is something called the <strong><a href=\"http://en.wikipedia.org/wiki/One_definition_rule\" rel=\"nofollow noreferrer\">one definition rule</a></strong>, which states that any definition should occur at most once in a program. (There are some exceptions to this, but you don't have to think about that yet.) Headers are meant to be included in <em>several</em> files, so they can only have <em>declarations</em> in them. For example:</p>\n\n<p>In <code>fileDialog.hpp</code>:</p>\n\n<pre><code>char *getFileName();\n</code></pre>\n\n<p>In <code>fileDialog.cpp</code>:</p>\n\n<pre><code>char *getFileName(){\n cout << vspace << col2 << \"begin getFileName()\";\n char* input = new char[size];\n cout << col2 << \"enter filename: \";\n cin.getline(input,size);\n cout << col2 << \"end getFileName()\";\n return input;\n}\n</code></pre>\n\n<p>The former is a declaration, the latter a definition. While we're on the subject of headers: It's normal for user-defined headers to have a <code>.h</code>, <code>.hpp</code> or <code>.hxx</code> suffix. I personally prefer <code>.hpp</code> to separate them from C headers.</p>\n\n<h3>4. Avoid using global variables.</h3>\n\n<p>Global variables are bad, because they have a very large scope and can be changed from anywhere, at any time, sometimes without you realizing. Either implement a class design and put the variables into class scope, or pass them around using function arguments. Variables that will never change (often called <em>constants</em> :-) ) can be left in the global scope, but should be declared <code>const</code>.</p>\n\n<h3>5. Learn the basics of a debugger.</h3>\n\n<p>Basic use of a debugger is very simple, and it allows you to remove a lot of the <code>cout</code> calls that clutter the code. Learn to set breakpoints and step through your code; that's all you need for now. As a beginner, I recommend using a visual debugger and not just raw <code>gdb</code>. (You can use a <code>gdb</code> frontend, though.)</p>\n\n<h3>6. Separate output from computations.</h3>\n\n<p>Functions that <em>do</em> something should generally not perform IO. One of the key reasons for that is reusability. You want to write code that you can reuse later. While it's not very likely that you will reuse these functions later, you should <em>train as you fight</em> and follow good practice whenever possible. Later users of your functions (i.e. you at a later time) may not want that output, and the way to solve that is to <strong>decouple IO from computations</strong>.</p>\n\n<hr>\n\n<h2>Lower-level issues</h2>\n\n<h3>7. It's safe to <code>delete</code> a null-pointer.</h3>\n\n<p>Instead of writing</p>\n\n<pre><code>if(cArray){\n delete[] cArray;\n</code></pre>\n\n<p>Write</p>\n\n<pre><code>delete [] cArray;\ncArray = nullptr;\n</code></pre>\n\n<p><code>delete</code>ing a null-pointer has zero effect, and is therefore harmless, so there's no point in checking against null. What you <em>should</em> do, however, is to set your pointer to null after deleting it, ensuring that nothing bad will happen if it is deleted again. In C++11, the null pointer is called <code>nullptr</code>. If for some reason you are not using C++11 (as a C++ learner in 2013, you should be), use <code>0</code> (or <code>NULL</code>) instead.</p>\n\n<h3>8. Consider inverting conditions to reduce nesting.</h3>\n\n<p>Instead of this code (superfluous comments and <code>cout</code>s removed, whitespace inserted to increase readability):</p>\n\n<pre><code>if (temp) {\n cArray = new char[strlen(temp)];\n strcpy(cArray,temp);\n delete[] temp;\n return;\n}\n\n// Handle temp == nullptr ...\n</code></pre>\n\n<p>Consider writing this:</p>\n\n<pre><code>if (!temp) {\n // Handle temp == nullptr ...\n}\n\ncArray = new char[strlen(temp)];\nstrcpy(cArray,temp);\ndelete[] temp;\n</code></pre>\n\n<p>There is a lot more to comment on, but these are the most pressing issues for now, and should be more than enough to get you started. I encourage you to implement as many of these changes as you can (except maybe refactoring to classes), and then post your updated code as a new question for further review.</p>\n\n<p>Some of the things that still remain to be pointed out are:</p>\n\n<ul>\n<li>Best practices</li>\n<li>Design issues -- what I would do differently, and why</li>\n<li>Identifier naming</li>\n<li>Exception safety and memory leaks</li>\n<li>File IO</li>\n</ul>\n\n<p>(I am listing these so you can think about them yourself before posting another review.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T14:10:36.563",
"Id": "44650",
"Score": "0",
"body": "+1. I did not think about the commenting that way, but I also didn't want to sound too arrogant. I've learned some other things, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T01:50:38.767",
"Id": "44716",
"Score": "0",
"body": "@Lstor - First, thank you for the time you have given me. Second, thank you for info on nullptr - I've read a fair amount in a few weeks and found that nowhere. First step will be to abandon gedit in favor of an IDE to get debugging. Then I work my way through all that you have provided."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T14:11:27.403",
"Id": "44757",
"Score": "0",
"body": "You're welcome :-) To get C++11 with g++, compile with `-std=c++11`. You don't have to use an IDE, you can also use a standalone visual debugger. Personally I prefer Vim and [Nemiver](https://projects.gnome.org/nemiver/) for small-scale development."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T22:37:59.233",
"Id": "461494",
"Score": "0",
"body": "`cArray = new char[strlen(temp)];\nstrcpy(cArray,temp);` is bad - UB as not enough memory was allocated for a _string_. Suggest `cArray = new char[strlen(temp) + 1];`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T06:14:45.770",
"Id": "28432",
"ParentId": "28429",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>You may not like to use <code>std::</code>, but it'll save you some headaches eventually. I too was in the habit when I started, but I broke out of it. More information about its use <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">here</a>.</p></li>\n<li><p>You really won't need <code>closingMessage()</code>, especially since it only outputs one message. It's an unneeded function-call, too.</p></li>\n<li><p><code>size</code> can just go inside <code>getFileName()</code> if there will be no other functions to use it. Better yet, just put that function in the same file as <code>main()</code>. This also applies to <code>logFormatter</code>.</p></li>\n<li><p>I will have to agree with @Lstor on the commenting thing. Although there's nothing wrong with documenting your code, too much of it creates clutter. At this level, I would just comment like this:</p>\n\n<ol>\n<li><p>Include a short explanation of the file at the top. This will remind you AND others what the following code is supposed to do.</p></li>\n<li><p>If a line or block of code may look complicated to someone else, add a few notes about it. If you're just doing something common like file I/O, no need to comment that. YOU may not know how it works right away, but that's why you're learning through coding.</p></li>\n</ol></li>\n<li><p>Although @Lstor has mentioned <code>std::string</code> already, I cannot stress it enough. You're do a lot of deleting pointer-handling here. Don't be afraid to learn the STL; it's there to help you. Yes, you should learn about deleting and pointer-handling on your own, but that would be best for \"learning\" programs and not serious programs. You cannot let this get in the way of learning responsible coding, especially when other people read your code.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T15:38:44.023",
"Id": "44651",
"Score": "2",
"body": "\"If a line or block of code may look complicated to someone else, add a few notes about it.\" Better yet, rewrite it so that it doesn't look complicated, or hide it inside a function with a meaningful name. If that's impossible, *then* comment it. I like to have very short comments describing 5-10 line blocks of code, though, almost like labels."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T02:20:12.103",
"Id": "44717",
"Score": "0",
"body": "@Jamal - as I said to Lstor, thank you for your time! I expect a request for code review is more demanding than a request to answer a focused, one point question. I really appreciate the link you provided concerning namespace std; that causes immediate change."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T14:48:09.720",
"Id": "28438",
"ParentId": "28429",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28432",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T21:54:06.203",
"Id": "28429",
"Score": "4",
"Tags": [
"c++",
"c",
"strings"
],
"Title": "Manage risk of \"Overflowing fixed-length string buffers\""
}
|
28429
|
<p>I'm working on a TCP Server using .NET and the following code is my first attempt to process the received data (from the socket) to create a packet to deliver. Basically, the packet has a header (7 bytes) where the first 3 bytes are always <code>0x12 0x34 0x89</code> and the next 7 bytes are the message length. For example: </p>
<p><code>0x12 0x34 0x89 0x00 0x00 0x00 0x02 0x20 0x20</code></p>
<p>The packet then is a 2 length packet and the sent data is <code>0x20 0x20</code>.</p>
<p>To process this I am using an if-elseif chain, which I don't like. Is there a better pattern to take away that if-elseif chain? </p>
<pre><code> public void ProcessIncomingData(byte[] buffer, int length)
{
for (int i = 0; i < length; i++)
{
ProcessByte(buffer[i]);
}
}
private void ProcessByte(byte b)
{
if (_status == PacketStatus.Empty && b == FirstHeaderByte)
{
_status = PacketStatus.FirstHeaderReceived;
}
else if (_status == PacketStatus.FirstHeaderReceived && b == SecondHeaderByte)
{
_status = PacketStatus.SecondHeaderReceived;
}
else if (_status == PacketStatus.SecondHeaderReceived && b == ThridHeaderByte)
{
_status = PacketStatus.ThirdHeaderReceived;
}
else if (_status == PacketStatus.ThirdHeaderReceived || _status == PacketStatus.ReceivingPacketLenght)
{
const int sizeOfInt32 = sizeof (int);
const int sizeOfByte = sizeof (byte);
_packetLength |= b << (sizeOfInt32 - ++_packetLenghtOffset) * sizeOfByte;
_status = _packetLenghtOffset < 4 ? PacketStatus.ReceivingPacketLenght : PacketStatus.ReceivingData;
}
else if (_status == PacketStatus.ReceivingData)
{
_packet.Add(b);
var receivedByteCount = _packet.Count;
if (receivedByteCount == _packetLength)
{
var packetData = new byte[_packet.Count];
_packet.CopyTo(packetData);
var receivedPacketHandler = PacketReceived;
if(receivedPacketHandler != null)
{
receivedPacketHandler(this, new PacketReceivedEventArgs{ Packet = packetData });
}
ResetControlVariables();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T03:16:57.220",
"Id": "44634",
"Score": "1",
"body": "TCP servers already exist, ones written in C are faster. If you want uber speed, the code will have to be messy. If you want clarity, then I would separate the process of scanning the header from the process of scanning the length from reading the actual data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T06:24:43.523",
"Id": "44640",
"Score": "0",
"body": "You have a typo in the code: `ThridHeaderByte`, and several places you are writing `Lenght` instead of `Length`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T09:49:46.993",
"Id": "44645",
"Score": "0",
"body": "`sizeof` is meant for use in `unsafe` code, you shouldn't use it like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T19:15:14.217",
"Id": "44656",
"Score": "0",
"body": "@Leonid, I know you´re right but this is just a hobby. Thank you for share your recommendation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T19:16:00.797",
"Id": "44657",
"Score": "0",
"body": "@Lstor, thank you, I always make the same mistakes. I´ve fixed them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T19:16:44.130",
"Id": "44658",
"Score": "0",
"body": "@svick, how should I do it? Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T00:31:41.380",
"Id": "44788",
"Score": "0",
"body": "@lontivero You can use the constants `4` and `1` directly. in C#, you can be sure that `int` is a 32-bit signed integer and that `byte` is an 8-bit unsigned integer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T17:24:55.167",
"Id": "45349",
"Score": "0",
"body": "@lontivero, there is nothing wrong with making a hobby project. However, when you ask for help to \"make the code better\", you need to have a specific goal in mind. Sounds like you would rather have a slower but clean and easy to understand TCP server rather than a fast and messy and tricky one. If this was a consulting project of yours and a client said \"got to be fast\", then you would write it one way. If a client said \"Our only junior programmer needs to be able to maintain this and speed is not an issue\", then you would write it differently. Typically you make it clean first fast second ..."
}
] |
[
{
"body": "<p>There is a bug in that you are not resetting the state when you read an unexpected byte. For example, this byte sequence would be accepted as a valid header by your code:</p>\n\n<p>0x12 0xff 0x34 0xff 0x89</p>\n\n<p>I wonder whether you would get a neater solution if you used a stream:</p>\n\n<pre><code>Stream stream = new MemoryStream(buffer);\nReadHeader(stream);\nint length = ReadLength(stream);\nbyte[] data = new byte[length];\nstream.Read(data, 0, length);\n</code></pre>\n\n<p>Where ReadHeader looks something like this:</p>\n\n<pre><code>byte[] header = new byte[TcpHeader.Length];\nstream.Read(header, 0, TcpHeader.Length);\nwhile (!header.equals(TcpHeader)) {\n // move back to 1 byte on from where we last tried to read the header\n stream.Seek(1 - TcpHeader.Length, SeekOrigin.Current);\n stream.Read(header, 0, TcpHeader.Length);\n}\n</code></pre>\n\n<p>And where ReadLength reads 4 bytes and creates an int, taking network byte order into consideration.</p>\n\n<p>Note there are some defects in my code which I have left there to keep it readable:</p>\n\n<ul>\n<li>The length field is probably an unsigned int, whereas Stream.Read only accepts an int.</li>\n<li>Stream.Read may not read all the bytes you asked for, so a loop is required to fill the buffer.</li>\n<li>We may reach the end of the stream while reading.</li>\n</ul>\n\n<p>(feedback on my first ever answer is very welcome!)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T09:47:46.407",
"Id": "44644",
"Score": "0",
"body": "Your general idea is sound, but I don't think trying to reparse the header at every possible position is a good idea (even if the question indicates that's what's wanted)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T19:30:45.943",
"Id": "44659",
"Score": "0",
"body": "@chris, I like your code but, as svick says, reparse the header is something that I don´t want to do. \nAbout the defect you mentioned, you're absolutely right. I did a UT to it and fails (Thank you!). +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T21:15:50.747",
"Id": "44663",
"Score": "0",
"body": "I agree that it seems bad to scan for the header, and I was going to say so in my answer, but on reflection I decided that a TCP server should be tolerant to junk data. I.e., if a valid packet is prefixed with an invalid partial header, I would expect the server to cope with that gracefully. Hence I followed the same logic expressed in the question :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T07:51:15.127",
"Id": "28434",
"ParentId": "28431",
"Score": "1"
}
},
{
"body": "<p>Simple pattern: Set up a hash table or map that maps the incoming byte to a function that returns the correct response.</p>\n\n<p>(C++ pseudocode - can be done in C# as well - don't have time now for all the implementation details:)</p>\n\n<pre><code>__statusType responseFunc(_statusType,byte);\n\nmap<byte,responseFunc> responseMap;\n\nprivate void ProcessByte(byte b)\n\n{\n _status= responseMap[_status](_status,b);\n}\n</code></pre>\n\n<p>Although you have some nested conditions, etc, your handler functions can deal with those conditions - but you may have to rethink your design and set up some classes that properly represent and understand your conditions. A long switch case or 'if else if' is invariably the result of poor design. You need to think carefully about your architecture. </p>\n\n<p>Another thing to consider is abstracting your conditions a bit and setting up an enumeration or class hierarchy to represent them. They can then be used as the key for your map or a parameter to your handler functions. </p>\n\n<p><strong>Yes - this is work</strong> - but clean design does require some effort. If you don't like long conditional statements (and you shouldn't) put in the effort to clean them up. </p>\n\n<p><strong>You should think along those lines - maps, dictionaries, enumerations, class hierarchies, factories, etc - whenever you run into a situation that seems to require an extended 'if else if..' or 'switch case';</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T21:00:40.830",
"Id": "44661",
"Score": "0",
"body": "This is not a solution. I have conditions to walk through different states."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T21:05:07.023",
"Id": "44662",
"Score": "0",
"body": "Your handler functions can deal with those conditions - and you may have to rethink your design and set up some classes that properly represent and understand your conditions. You should not have downvoted - I have been designing systems and writing production code for 20 years: A long switch case or if else if is invariably the result of poor design. You need to think carefully about your architecture."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T21:22:14.350",
"Id": "44665",
"Score": "0",
"body": "Another thing to consider is abstracting your conditions a bit and setting up an enumeration or class hierarchy to represent them. They can then be used as the key for your map or a parameter to your handler functions. Yes - this is work - but clean design does require some effort. If you don't like long conditional statements (and you shouldn't) put in the effort to clean it up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T21:28:54.677",
"Id": "44666",
"Score": "0",
"body": "see edit of answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T22:05:40.680",
"Id": "44668",
"Score": "0",
"body": "@Mickey, i've fixed the -1 issue and i am grateful for your help and effort. I agree with you on setting up some classes that properly represent and understand my conditions, that's the point. I know very well the pattern that you destails, in fact i wrote about it (http://geeks.ms/blogs/lontivero/archive/2012/01/30/refactoring-move-switch-to-table.aspx). It is just that I think it is not what I am looking for exactly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T22:12:51.733",
"Id": "44670",
"Score": "0",
"body": "@lontivero - OK thanks. I don't know all the details of your scenario and I did not examine the whole thing in detail. I just now from experience that this sort of problem can usually be cleaned up with the hash table/mapped function approach, combined with some abstraction of your various specific conditions. Any time I have a 'switch case' or 'if else if' with more than 3 choices, I start thinking about my design. Many is the time that my 'version 1' release had a 20 part switch case which refactoring reduced to one line using a hash table, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T23:26:42.023",
"Id": "44673",
"Score": "0",
"body": "After all the discussion, I still think it is not what I want but it is the best answer because the code looks better. See my own answer where I implemented your suggestion."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T20:31:05.997",
"Id": "28441",
"ParentId": "28431",
"Score": "2"
}
},
{
"body": "<p>This answer is just to show the current implementation (proposed by Mikey).</p>\n\n<pre><code> public PacketHandler()\n {\n _packet = new List<byte>();\n _handlers = new Dictionary<PacketStatus, Action<byte>>{\n { PacketStatus.Empty, b => Expect(FirstHeaderByte, b, PacketStatus.FirstHeaderReceived) },\n { PacketStatus.FirstHeaderReceived, b => Expect(SecondHeaderByte, b, PacketStatus.SecondHeaderReceived) },\n { PacketStatus.SecondHeaderReceived,b => Expect(ThirdHeaderByte, b, PacketStatus.ThirdHeaderReceived)},\n { PacketStatus.ThirdHeaderReceived, AcceptPacketLength},\n { PacketStatus.ReceivingPacketLength, AcceptPacketLength},\n { PacketStatus.ReceivingData, AcceptData},\n { PacketStatus.Unsynchronized, b => Expect(FirstHeaderByte, b, PacketStatus.FirstHeaderReceived) }\n };\n }\n\n public void ProcessIncomingData(byte[] buffer, int length)\n {\n for (_currentByteIndex = 0; _currentByteIndex < length; _currentByteIndex++)\n {\n var currentByte = buffer[_currentByteIndex];\n var handler = _handlers[_status];\n handler(currentByte);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T23:24:41.203",
"Id": "28446",
"ParentId": "28431",
"Score": "0"
}
},
{
"body": "<p>I come up with a solution using bit mask to detect the header. I think using Dictionary looks more maintainable anyway.</p>\n\n<pre><code> private int _expectedBytesLength;\n private int _consumedBytesLength;\n private readonly byte[] _packetMask = new byte[] { 0x12, 0x34, 0x89, 0xFF, 0xFF, 0xFF, 0xFF };\n private byte[] _packetHeaderBuffer = new byte[7]; // should be allocated with _packetMask.Length in constructor\n private List<byte> _packet = new List<byte>();\n\n public void ProcessByte(byte b) {\n if (_expectedBytesLength > 0) {\n if (_expectedBytesLength > _consumedBytesLength) {\n _packet.Add (b);\n _consumedBytesLength++;\n }\n if (_consumedBytesLength >= _expectedBytesLength) {\n var packetData = new byte[_packet.Count];\n _packet.CopyTo (packetData);\n Console.WriteLine (packetData.Length);\n // raise events etc.\n _expectedBytesLength = 0;\n _consumedBytesLength = 0;\n _packet.Clear ();\n }\n } \n else {\n bool inState = (b & _packetMask[_consumedBytesLength]) == b;\n if (inState) {\n _packetHeaderBuffer[_consumedBytesLength] = b;\n _consumedBytesLength++;\n if (_consumedBytesLength >= _packetMask.Length) {\n int length = 0;\n for (int i = 3; i < 7; i++) {\n length <<= 1;\n length += _packetHeaderBuffer[i];\n }\n _expectedBytesLength = length + _packetHeaderBuffer.Length;\n }\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T15:51:57.973",
"Id": "28512",
"ParentId": "28431",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28441",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T02:42:00.013",
"Id": "28431",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"socket"
],
"Title": "if-elseif chain. Is there a better pattern?"
}
|
28431
|
<p><strong>users_controller.rb:</strong></p>
<pre><code>class UsersController < ApplicationController
def new
end
def create
user = User.create(params[:user])
if user.id
session[:user_id] = user.id
redirect_to '/city/map'
else
redirect_to new_session_path, flash: { error: 'This name is already taken.' }
end
end
end
</code></pre>
<p><strong>sessions_controller.rb:</strong></p>
<pre><code>class SessionsController < ApplicationController
def new
end
def create
user = User.new(params[:session]).authorize
if user
session[:user_id] = user.id
redirect_to '/city/map'
else
redirect_to new_session_path, flash: { error: 'Your login information is invalid.' }
end
end
def destroy
end
end
</code></pre>
<p>How can I DRY it (only in terms of repeatable code in <code>create</code> actions in these controllers)?</p>
|
[] |
[
{
"body": "<p>Before drying, make sure your code working.</p>\n\n<p>In the first block, your approach is wrong</p>\n\n<pre><code>user = User.create(params[:user])\n</code></pre>\n\n<p>But the user object is not persisted and no id will be assigned. (only <code>create!</code> will try to save to db and will throw error if failed)</p>\n\n<p>A conventional approach is</p>\n\n<pre><code>user = User.new(params[:user])\nif user.save\n # do something\nelse\n # handling error\nend\n</code></pre>\n\n<p>In your second block, I don't know what will your custom method <code>authorize</code> do, and can't comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T12:11:21.227",
"Id": "44647",
"Score": "0",
"body": "Actually `User.create` will never return `nil`, so it's not wrong but very unidiomatic, better + `new` + `is x.save` as you show."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T12:40:41.610",
"Id": "44648",
"Score": "0",
"body": "@tokland, thanks for pointing out that. I mixed it with `create!` which will save to db."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T10:19:56.900",
"Id": "28436",
"ParentId": "28435",
"Score": "2"
}
},
{
"body": "<p>Comments by Billy Chan are very valuable but I still think your question is worth response. So...</p>\n\n<p>Is this code repetitive? Yes.\nShould you DRY it? No.\nWhy?</p>\n\n<p>To quote DRY principle from <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">Wikipedia</a> </p>\n\n<blockquote>\n <p>\"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.\"</p>\n</blockquote>\n\n<p>So what does it mean in general is that, you shouldn't repeat the same code twice, as this is a part of knowledge is a system (application).<br>\nBut why do I think it is not the same, even if it's quite exactly same code in two controllers? Because the KNOWLEDGE hidden in those pieces of code is different.\nIn each of those controllers you have logic that describes how to go around different pieces of data submitted by user concerning two different object classes. The behaviour of create action in controller is not universal enough that you may save all objects in the same manner. Sometimes you want to associate created object with current_user, other times there may be a need to add some tasks to background queue (posting to Facebook, compressing images). For this reason it would be unwise to make those methods one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T10:49:59.330",
"Id": "28460",
"ParentId": "28435",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T09:28:26.173",
"Id": "28435",
"Score": "-3",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "How can I DRY this Rails code?"
}
|
28435
|
<p>This is (supposedly) a multi-threaded scheduler for one-time and/or repeating tasks. The tasks are simple <code>std::function<void()></code> objects. I built it to be a crucial part of a larger project I'm working on, but I developed it stand-alone, so no context is missing for a review.</p>
<p>I'm making heavy use of C++11 language and library features (especially thread support and chrono stuff).</p>
<p>Tasks are supposed to be scheduled by specifying a start <code>time_point</code>, or a delay (converted to a <code>time_point</code> by adding it to <code>now()</code>.) An optional duration specifies repeat intervals for the task (if it's non-zero).</p>
<p>It should be possible to de-schedule tasks, preventing them from being started for execution from then on. (Already running tasks won't be stopped, to keep things a bit simpler, and also because I couldn't figure out a clean way to do it anyway.)</p>
<p>I've never done anything with multithreading of this scale/complexity, and in case my brain never recovers from repeatedly being torn into 5 or more threads, I'd like to get some review/feedback from others. Specifically, race conditions/deadlocks/other threading-unpleasantness I didn't spot, lifetime issues, or really anything problematic.</p>
<p>Some simple code at the very bottom demonstrates how it's meant to be used. It seemed to work when compiled with clang 3.3 and libc++.</p>
<pre><code>#include <chrono>
#include <condition_variable>
#include <deque>
#include <list>
#include <mutex>
#include <thread>
#include <utility>
#include <vector>
namespace scheduling {
template <class Clock>
class Scheduler {
typedef Clock clock_type;
typedef typename clock_type::time_point time_point;
typedef typename clock_type::duration duration;
typedef std::function<void()> task_type;
private:
struct Task {
public:
Task (task_type&& task, const time_point& start, const duration& repeat) : task(std::move(task)), start(start), repeat(repeat) { }
task_type task;
time_point start;
duration repeat;
bool operator<(const Task& other) const {
return start < other.start;
}
};
public:
typedef typename std::list<Task>::iterator task_handle;
private:
std::mutex mutex;
std::condition_variable tasks_updated;
std::deque<task_handle> todo;
std::condition_variable modified;
bool running;
std::list<Task> tasks;
std::list<task_handle> handles;
std::vector<std::thread> threads;
public:
Scheduler() : threads(4) {
}
~Scheduler() {
halt();
}
task_handle schedule(task_type&& task, const time_point& start, const duration& repeat=duration::zero()) {
task_handle h;
{
std::lock_guard<std::mutex> lk(mutex);
h = tasks.emplace(tasks.end(), std::move(task), start, repeat);
handles.push_back(h);
}
tasks_updated.notify_all();
return h;
}
task_handle schedule(task_type&& task, const duration& delay=duration::zero(), const duration& repeat=duration::zero()) {
return schedule(std::move(task, clock_type::now()+delay, repeat));
}
void unschedule(const task_handle& handle) {
{
std::lock_guard<std::mutex> lk(mutex);
auto handle_it = std::find(handles.begin(), handles.end(), handle);
if (handle_it != handles.end()) {
tasks.erase(handle);
todo.remove(handle);
handles.erase(handle_it);
}
}
tasks_updated.notify_all();
}
void clear() {
{
std::lock_guard<std::mutex> lk(mutex);
tasks.clear();
handles.clear();
}
tasks_updated.notify_all();
}
void run() {
{
std::lock_guard<std::mutex> lk(mutex);
if (running) return;
running = true;
for (auto& t : threads) {
t = std::thread([this]{this->loop();});
}
}
while (true) {
std::unique_lock<std::mutex> lk(mutex);
if (!running) break;
auto task_it = min_element(tasks.begin(), tasks.end());
time_point next_task = task_it == tasks.end() ? clock_type::time_point::max() : task_it->start;
if (tasks_updated.wait_until(lk, next_task) == std::cv_status::timeout) {
if (task_it->repeat != clock_type::duration::zero()) {
task_it->start += task_it->repeat;
}
else {
handles.remove(task_it);
tasks.erase(task_it);
}
todo.push_back(task_it);
modified.notify_all();
}
}
for (auto& t : threads) {
t.join();
}
}
void halt() {
{
std::lock_guard<std::mutex> lk(mutex);
if (!running) return;
running = false;
}
tasks_updated.notify_all();
modified.notify_all();
}
private:
void loop() {
while (true) {
std::function<void()> f;
{
std::unique_lock<std::mutex> lk(mutex);
while (todo.empty() && running) {
modified.wait(lk);
}
if (!running) {
return;
}
f = todo.front()->task;
todo.pop_front();
}
f();
}
}
};
}
#include <iostream>
void outp(const std::string& outp) {
static std::mutex m;
std::lock_guard<std::mutex> lk(m);
std::cout << std::this_thread::get_id() << ": " << outp << std::endl;
}
int main(int argc, char* argv[]) {
scheduling::Scheduler<std::chrono::steady_clock> sched;
sched.schedule([&sched]{outp("Task 1");}, std::chrono::steady_clock::now());
sched.schedule([&sched]{outp("Task 2");}, std::chrono::steady_clock::now()+std::chrono::seconds(2), std::chrono::seconds(2));
sched.schedule([&sched]{outp("Task 3");}, std::chrono::steady_clock::now()+std::chrono::seconds(2), std::chrono::seconds(2));
sched.schedule([&sched]{outp("Task 4");}, std::chrono::steady_clock::now()+std::chrono::seconds(2), std::chrono::seconds(2));
sched.schedule([&sched]{outp("Task 5");}, std::chrono::steady_clock::now()+std::chrono::seconds(2), std::chrono::seconds(2));
sched.schedule([&sched]{outp("Task 6");}, std::chrono::steady_clock::now()+std::chrono::seconds(3));
sched.schedule([&sched]{outp("Task 7");}, std::chrono::steady_clock::now()+std::chrono::seconds(3));
sched.schedule([&sched]{outp("Task 8");}, std::chrono::steady_clock::now()+std::chrono::seconds(3));
sched.schedule([&sched]{outp("Task 9");}, std::chrono::steady_clock::now()+std::chrono::seconds(3));
sched.schedule([&sched]{outp("Task 10"); sched.halt(); }, std::chrono::steady_clock::now()+std::chrono::seconds(5));
sched.run();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T18:43:59.410",
"Id": "44655",
"Score": "0",
"body": "Just a comment for now -- note that `std::function` is not free and its type erasure mechanism comes at a run-time cost. Perhaps it's worth considering using templates with perfect forwarding to accept anything callable, similarly to how `std::async` does it (see how it takes `Function`): http://en.cppreference.com/w/cpp/thread/async"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T20:11:04.687",
"Id": "44660",
"Score": "0",
"body": "Thanks for the comment; I probably wouldn't have found out about this for ages, or probably ever. The suggestion is basically, that instead of an std::function<void()>, I would store a T, that would then be something like void(*)()? Come to think of this, what type is []{} exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T23:22:14.003",
"Id": "44672",
"Score": "0",
"body": "Quick, dirty, non-variadic, and quite possibly wrong: http://ideone.com/j3FcqS (also it's probably more user-friendly to provide a factory function to deduce the type automatically).\n\nSee `boost::packaged_task` (e.g., \"task constructor\") for a more complete example: http://www.boost.org/doc/libs/release/doc/html/thread/synchronization.html#thread.synchronization.futures.reference.packaged_task\n\nEach lambda function is of a distinct \"closure type\" (\"a unique unnamed non-union non-aggregate type\", typically implemented as a function object): http://en.cppreference.com/w/cpp/language/lambda"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:09:39.677",
"Id": "61597",
"Score": "0",
"body": "At first glance, you're using stuff from both `<string>` and `<algorithm>` without including those headers."
}
] |
[
{
"body": "<p>It looks/sounds like you're trying to build a sort of <a href=\"https://en.wikipedia.org/wiki/Thread_pool_pattern\" rel=\"nofollow noreferrer\">thread pool</a>. If that's the case, take a look at this <a href=\"https://softwareengineering.stackexchange.com/questions/173575/what-is-a-thread-pool\">StackExchange link</a> for some help on what it is (a thread design pattern). For your purposes you essentially have a worker queue (a single threaded thread pool), where the only difference is (as you are already doing) you use a mutex object to block the 'running' of the current scheduled task instead of a semaphore object.</p>\n\n<p>Just some notes on your code that I could see:\nLine 35, you have <code>std::deque<task_handle> todo</code> while a <code>task_handle</code> is defined as a <code>std::list<Task>::iterator</code>. If you're using a <code>deque</code> for performance reasons, consider switching all container types to a <code>deque</code> as I didn't see any code that inherently 'needs' a list (efficiency of removing/adding in the middle of the list vs. at begin/end).</p>\n\n<p>There's also a lot of extra 'scope/control' braces to help 'control' the flow of the mutexes (i.e. Java way of doing mutex locks) via an 'auto mutex locker' object. I get the need for the control braces, but what's happening under the hood is more complex:</p>\n\n<pre><code>void clear() {\n { // <- stack enters new location\n std::lock_guard<std::mutex> lk(mutex); // stack consumes memory for 'auto' object, then mutex.lock is called and control returned\n tasks.clear();\n handles.clear();\n } // stack destroys 'auto lock' object which then calls mutex.unlock\n tasks_updated.notify_all();\n}\n</code></pre>\n\n<p>Consider the following instead:</p>\n\n<pre><code>void clear() { // no extra stack (aside from normal operation)\n mutex.lock();\n tasks.clear();\n handles.clear();\n mutex.unlock();\n tasks_updated.notify_all();\n} // no extra stack calls and actually 1 less line of code\n</code></pre>\n\n<p>Line 103: <code>time_point next_task = task_it == tasks.end() ? clock_type::time_point::max() : task_it->start;</code>\nWhile technically correct it could potentially lead to some confusion down the road if this ever produces a bug; it is your code so as long as you can read it it's all good.</p>\n\n<p>Your private loop function is an infinite loop:</p>\n\n<pre><code>void loop() {\n while (true) {\n std::unique_lock<std::mutex> lk(mutex);\n while (todo.empty() && running) {\n modified.wait(lk);\n }\n if (!running) {\n return;\n }\n f = todo.front()->task;\n todo.pop_front();\n }\n}\n</code></pre>\n\n<p>consider this instead (just replaced while (true) with while (running)):</p>\n\n<pre><code>void loop() {\n while (running) {\n std::unique_lock<std::mutex> lk(mutex);\n while (todo.empty() && running) {\n modified.wait(lk);\n }\n if (!running) {\n return;\n }\n f = todo.front()->task;\n todo.pop_front();\n }\n}\n</code></pre>\n\n<p>Also, why is <code>Scheduler</code> templated for the clock type instead of just being explicit or derive some classes off of a scheduler that has a specific clock type?</p>\n\n<p>You also have <code>task_type</code> declared as a <code>std::function<void()></code> which means a function that returns <code>void</code> and takes no arguments, yet you're passing in functions that take a <code>std::string</code> as an argument (this is only in your demo code), while technically it might work you're also possibly smashing the stack when you do this (a big no-no).</p>\n\n<p>You also have a <code>struct</code> stuffed in a class (your <code>Task</code> structure) that looks likes it's only used specifically for the <code>Scheduler</code> class, instead consider just making the member variables in your <code>struct</code> private member variables of your <code>Scheduler</code> class.</p>\n\n<p>One last note: it's usually considered 'best' practice to group your member scope accessors (public/private/protected), instead of spreading the keywords where needed.</p>\n\n<p>I can refactor the code an post what I see if you would like, otherwise I hope this all helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T22:51:19.440",
"Id": "63459",
"Score": "0",
"body": "Thanks for your review, and merry christmas! I do use 4 threads (`:44`). Good tip with list/deque - I'll be changing that. The scopes were for exceptions. (possibly in the future; I'll leave it this way, but I acknowlege your concerns ;P) Infinite loop because `running` should be accessed under a lock. Template because subclasses are more complex than i thought i could ever need. I am not passing void(std::string)'s. `Scheduler` uses multiple instances of `Task`, it's used like a named tuple. I'll reorder public/private. Sorry this is so short and brutal, 600 character limit and all..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T01:57:24.907",
"Id": "37560",
"ParentId": "28437",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T14:34:41.383",
"Id": "28437",
"Score": "7",
"Tags": [
"c++",
"c++11",
"multithreading",
"scheduled-tasks"
],
"Title": "Multithreaded task-scheduler"
}
|
28437
|
<p>For my current project, I have elected to represent database rows as objects.</p>
<p>So an individual comment can be retrieved as a class like so:</p>
<pre><code>$comment = new Comment(1);
</code></pre>
<p>Here is the Comment class code:</p>
<pre><code><?php
class Comment
{
private $userid, $postid, $content, $date, $name, $ip, $legacy;
public function __construct($comment_id)
{
$sql = new mysqli(REGISTRY_DBVALUES_SERVER, REGISTRY_DBVALUES_USERNAME, REGISTRY_DBVALUES_PASSWORD, REGISTRY_DBVALUES_DATABASE);
$stmt = $sql->prepare("SELECT id, userid, postid, content, date, name, ip, legacy
FROM ".SITE_TABLE_COMMENTS."
WHERE id = ?");
$stmt->bind_param("i", $comment_id);
$stmt->bind_result($id, $userid, $postid, $content, $date, $name, $ip, $legacy);
$stmt->execute();
while($row = $stmt->fetch())
{
$this->userid = $userid;
$this->postid = $postid;
$this->content = $content;
$this->date = $date;
$this->name = $name;
$this->ip = $ip;
$this->legacy = $legacy;
}
$stmt->free_result();
$sql->close();
}
public function getUserID()
{
return $this->userid;
}
public function getPostID()
{
return $this->postid;
}
public function getContent()
{
return $this->content;
}
public function getDate()
{
return $this->date;
}
public function getName()
{
return $this->name;
}
public function getIP()
{
return $this->ip;
}
public function getLegacy()
{
return $this->legacy;
}
}
?>
</code></pre>
<p>This allows you to retrieve the different attribute values for an individual comment using methods.</p>
<p>I am open to criticism on <strong>all</strong> aspects of the design, but was particularly curious if this is an accepted way of handling retrieval of individual data records?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T19:41:26.123",
"Id": "44705",
"Score": "0",
"body": "is the code complete? There aren't any defined properties."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T17:47:19.310",
"Id": "44770",
"Score": "0",
"body": "Sorry, don't know where they disappeared to -- added."
}
] |
[
{
"body": "<p>This is not OOP, your comment is hard coupled with mysqli. What if you would write the exact same program but now with PDO? you will have to change the Comment class.</p>\n<p>Then performance wise: you are now opening a mysqli connection for every comment.</p>\n<p>You seem to think that using the word 'class' and method names as 'getMyVar()' equals OOP. It doesnt.</p>\n<p>Programming is always about problem solving, and a good program is about solving a problem in such a way you can easily reuse that solution for other sort of the same problems.</p>\n<p>OOP is very dangerous, because it alows us programmers to write even crapper code as before. That is why some really smart guys came up with loads of rules to live by in OOP land, called SOLID: <a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)</a></p>\n<p>Now, lets place your code next to the SOLID rules.</p>\n<h1>1 Single responsibility principle</h1>\n<p>The Comment class fails on this account. It does multiple things as far as I can see. It works as a storage object for a Comment with methods to retrieve the parameters of the comment <strong>AND</strong> it also retrieves the comment from the Database. So we allready have a little problem here.</p>\n<h1>2 Open/closed principle</h1>\n<p>Again, not so good. An example: say I have a special sort of comment that has an extra field called 'permissions':</p>\n<pre><code>class PermissionComment extends Comment {}\n</code></pre>\n<p>Uh oh, In order to save the permission field into the object, I will have to rewrite the entire __construct while I only added 1 field. Not so good.</p>\n<p>Also, all your variables are public variables. I don't need to use the get() methods to access a variable. I can access it directly. We thus violate the above rule in multiple ways. We cannot easily extend the comments functionality and we dont encapsulate it correctly</p>\n<h1>3 Liskov substitution principle</h1>\n<p>As I allready wrote somewhere at the top, say we want to change mysqli with PDO. Or we have written an extension of the mysqli object that does some caching of queries, I would now have to rewrite my Comment class because mysqli is hard coded into the object. Not so good again.</p>\n<h1>4 Interface segregation principle</h1>\n<p>This one, I will let go since it is not really in order here</p>\n<h1>5 Dependency inversion principle</h1>\n<p>Again, could be better. The Comment class i tightly coupled with your database connect. Your comment class 'knows' about the database-connection. It knows how to connect to a database. It knows how comments are stored while in fact it's just a container of comment data.</p>\n<h1>What now?</h1>\n<p>Back to the drawing board. You write you want to write a class that represents a Comment. Ok good. As example I omitted a lot of parameters in the code below, in fact, mostly because I'm lazy :p</p>\n<p>So lets write a class that represents a basic Comment:</p>\n<pre><code>class Comment {\n\n private $id;\n\n private $content;\n\n private $title;\n\n public function __construct($data) {\n $this->id = $data['id'];\n $this->content = $data['content'];\n $this->title = $data['title'];\n }\n\n public function getId() {\n return $this->id;\n }\n\n public function getContent() {\n return $this->content;\n }\n\n public function getTitle() {\n return $this->title;\n }\n}\n</code></pre>\n<p>Good, a Simple class that represents a Comment and only a Comment. But, one problem. What happend if we change the way the data is passed in. Or the key's change. and how can we be sure that that Comment class will only extract the data it needs. How does another programmer know what key's that $data array needs to have without having to read your entire code?</p>\n<p>Let's change the constructor into:</p>\n<pre><code>public function __construct($content, $title) {\n $this->content = $content;\n $this->userId = $userId;\n}\n</code></pre>\n<p>Ooeeh, cheecky. But huh? where did $id go?\nWell, let's just say I want to create a Comment and later add it to the database, or I want to create a Comment object for testing purposes, or just a default comment to pass to the the frontend, my Comment doesn't have an id. I can now easily create a Content without needing a database id.</p>\n<p>And for those Comments who do have an ID, we create an additional class:</p>\n<pre><code>class DbComment extends Comment {\n\n private $id;\n\n public function __construct($content, $userId, $id) {\n $this->id = $id;\n parent::__construct($content, $userId);\n }\n\n public function getId() {\n return $this->id;\n }\n}\n</code></pre>\n<p>See how little code I had to write to simply add a Field to the Comment object?</p>\n<p>But now your thinking: What a load of bull. This code can't even fetch a Comment from the database. True, but a 'Comment' object is a Comment and not a CommentFetcher.</p>\n<p>We could now write a CommentFetcher class that fetches and saves Comments and returns a DbComment. Example:</p>\n<pre><code>class CommentFetcher {\n\n private $mysql;\n\n public function __construct(mysqli $mysql) {\n $this->mysql = $mysql;\n }\n\n public function fetch($id) {\n $stmt = $this->mysql->prepare("SELECT id, title, content FROM comment_comments WHERE id = ?");\n $stmt->bind_param("i", $id);\n $stmt->bind_result($id, $title, $content);\n $stmt->execute();\n return new DbComment($content, $title, $id);\n }\n}\n</code></pre>\n<p>Note how i pass in a mysqli object in the constructor. All the class says is I need a mysqli object. If I now write my <code>ThisClassCachesMysqliQueries extends Mysqli</code> class I can simply pass it in, the CommentFetcher will have no idea I passed in a different class because it's still a mysqli object. But I will have added super duper caching into my program without having to change the CommentFetcher, cool huh?</p>\n<p>So now we have a generic <code>Comment</code> class, we have a special case <code>Comment</code>, the <code>DbComment</code>. This is also a Comment but one that exists in a database somewhere and thus has an Id and we have a <code>CommentFetcher</code> that fetches comments from the Database.</p>\n<p>Now a note: The code that I have written here is still crap. Don't use it ;)\nA Class that can only fetch comments isn't really usefull. But you get the point, a CommentController that can update, fetch and insert Comments is something really nice.</p>\n<p>Also I would advice you to rething how you are saving comments. Know, a comment has to know about users, ip, legacy,... While in fact all a Comment needs is a Title, data and content. A different table and controller would then look up hte user that postes the comment in the user_posted_comment table etc etc etc.</p>\n<p>Once in a while, I take a step back an think, what am I writing? because at the end of the day, a Comment is a Comment and not some exotic objet that knows about users, ip-adresses and legacy.</p>\n<p>But hey, atleast you are using bound params and prepared statements! Big up yoself.\nI hope this answer helps you. else simply flame me in the commentbox below</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T17:39:40.657",
"Id": "44767",
"Score": "0",
"body": "Thank you for the thorough review, it is much appreciated. One question -- and it may be very stupid, but this is the place to ask such questions: is there at this point an advantage to still using a Comment object over, say, an associative array being simple returned by our Fetcher?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T17:54:00.007",
"Id": "44772",
"Score": "0",
"body": "And furthermore, wouldn't many arguments for constructors make code less clean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T22:00:04.360",
"Id": "44786",
"Score": "1",
"body": "@Racktash Many arguments will actually in the long run make the code better to read. In a half year you will look back at that comment class and think, huh? only one argument to pass in? but now you see, ah ok, i need these arguments. And to answer your other question. If a Comment doesn't have any extra functionality you could opt for indeed returning a simple associative array. If it doens't help you or solve a problem you are having, don't do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T08:11:08.277",
"Id": "44813",
"Score": "0",
"body": "@Racktash your welcome! We've all been there and done that ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T16:05:30.523",
"Id": "28513",
"ParentId": "28440",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28513",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-13T18:33:02.313",
"Id": "28440",
"Score": "2",
"Tags": [
"php",
"classes"
],
"Title": "Representing database row as a class"
}
|
28440
|
<p>I'm getting into jQuery and I figured I'd start with log in / sign up form. (As an aside, I'm fully aware log in / sign up forms exist ad infinitum; this is more as a learning exercise than anything) </p>
<p>The idea is that the form fields will fade in depending on whether the user wants to log in or sign up to the site. Most of the CSS is via <a href="http://twitter.github.io/bootstrap/" rel="nofollow">Twitter Bootstrap</a>.</p>
<p><a href="http://jsfiddle.net/FdV54/" rel="nofollow">JSFiddle</a></p>
<p><strong>HTML</strong></p>
<pre><code> <head>
<!-- _csrf is generated server side -->
<meta name="_csrf" content="TEST_CSRF">
</head>
<body>
<div class="login"></div>
<div class="buttonArea"></div>
</body>
</code></pre>
<p><strong>JavaScript / jQuery</strong></p>
<pre><code>$(document).ready(function () {
// Variables for various HTML elements
var initSignUp = $('<input type="button" value="Sign Up" class="btn btn-primary showSignUp">');
var initLogin = $('<input type="button" value="Login" class="btn btn-primary showLogin">');
var sSignUp = $('<input type="button" value="Sign Up" class="btn btn-primary" id="sSignUp">');
var sLogin = $('<input type="button" value="Login" class="btn btn-primary" id="sLogin">');
var spacer = $('<input type="button" value="" class="btn btn-primary emptyLabel">');
var csrf = $("meta[name='_csrf']").attr("content");
addButtons(initLogin, spacer, initSignUp);
function addButtons(left, mid, right) {
addDivs(1, '.buttonArea', true);
$('.buttonArea').find('.control-group').addClass('form-horizontal');
$('.buttonArea').find('.controls').append(left);
$('.buttonArea').find('.controls').append(mid);
$('.buttonArea').find('.controls').append(right);
}
function fadeIn() {
$('.hiddenForm').css('visibility', 'visible').hide().fadeIn('slow');
}
function clearCanvas() {
$('.login').empty();
$('.buttonArea').empty();
}
// Helper to insert the actual div element HTML
function addDivs(numForms, baseClass, skipForm) {
var formHorizontal = '.form-horizontal';
var formHtml = '<form id="target" class="form-horizontal" method="post"></form>';
var csrfHtml = '<input type="hidden" name="_csrf" value="' + csrf + '">';
var controlGroupDiv = '<div class="control-group"><div class="controls"></div></div>';
if (skipForm) {
for (i = 0; i < numForms; i += 1) {
$(baseClass).append(controlGroupDiv);
}
} else {
$(baseClass).append(formHtml);
$('#target').append(csrfHtml);
for (i = 0; i < numForms; i += 1) {
$('#target').append(controlGroupDiv);
}
}
}
function getControlGroup(index) {
return $('.control-group')[index];
}
function getControls(index) {
return $('.controls')[index];
}
function addFormElement(index, label, input) {
var group = getControlGroup(index);
var control = getControls(index);
$(group).addClass('hiddenForm');
$(control).append(input);
$(group).prepend(label);
}
function addBlankLabel(index) {
var label = '<label class="control-label emptyLabel">Hidden Label</label>';
var control = getControls(index);
$(control).append(label);
}
function addUserNameForm(index) {
var label = '<label for="username" class="control-label">Username</label>';
var input = '<input id="username" type="text" name="username" placeholder="Username" value="">';
addFormElement(index, label, input);
}
function addEmailForm(index) {
var label = '<label class="control-label" for="inputEmail">Email</label>';
var input = '<input id="inputEmail" type="text" name="email" placeholder="Email" value="">';
addFormElement(index, label, input);
}
function addPasswordForm(index) {
var label = '<label class="control-label" for="inputPassword">Password</label>';
var input = '<input id="inputPassword" type="password" name="password" placeholder="password" value="">';
addFormElement(index, label, input);
}
// Helper to clear the old forms and generate divs for new form elements
function drawDivs() {
clearCanvas();
addDivs(3, '.login');
}
// Generate log in form
$('.buttonArea').on('click', '.showLogin', function () {
drawDivs();
addBlankLabel(0);
addEmailForm(1);
addPasswordForm(2);
$('#target').attr('action', '/users/session');
$('#target').attr('method', 'post');
fadeIn();
addButtons(sLogin, spacer, initSignUp);
});
// Generate sign up form
$('.buttonArea').on('click', '.showSignUp', function () {
drawDivs();
addUserNameForm(0);
addEmailForm(1);
addPasswordForm(2);
$('#target').attr('action', '/users');
$('#target').attr('method', 'post');
fadeIn();
addButtons(initLogin, spacer, sSignUp);
});
// Submit sign up form
$('.buttonArea').on('click', '#sSignUp', function () {
$('#target').trigger('submit');
});
// Submit login form
$('.buttonArea').on('click', '#sLogin', function () {
$('#target').trigger('submit');
});
});
</code></pre>
|
[] |
[
{
"body": "<p>If your looking to find performance improvements i've always know this to be faster</p>\n\n<pre><code>$('<input>', {\n type: \"button\", \n value: \"\", \n 'class': \"btn btn-primary emptyLabel\"\n});\n</code></pre>\n\n<p>Than this </p>\n\n<pre><code>$('<input type=\"button\" value=\"\" class=\"btn btn-primary emptyLabel\">');\n</code></pre>\n\n<p>That would be a good start</p>\n\n<p>Also you should cache your elements instead of calling a function <code>5+</code> times call it only once</p>\n\n<pre><code>$('.buttonArea').find('.control-group').addClass('form-horizontal');\n$('.buttonArea').find('.controls').append(left);\n$('.buttonArea').find('.controls').append(mid);\n$('.buttonArea').find('.controls').append(right);\n</code></pre>\n\n<p>This ^ repeats throughout most of the code.</p>\n\n<p>To this</p>\n\n<pre><code>var $buttonArea = $('.buttonArea'),\n $controls = $buttonArea.find('.controls');\n\n$buttonArea.find('.control-group').addClass('form-horizontal');\n$controls.append(left);\n$controls.append(mid);\n$controls.append(right);\n</code></pre>\n\n<p>also you call <code>attr</code> twice on the same element here </p>\n\n<pre><code> $('#target').attr('action', '/users/session');\n $('#target').attr('method', 'post');\n</code></pre>\n\n<p>This basically finds the #target in the <code>DOM</code> then adds the <code>action</code> attribute. then if finds #target again and adds the <code>method</code> attribute you should do it with a <code>Object</code></p>\n\n<pre><code>$('#target').attr({\n 'method', 'post',\n 'action': '/users/session'\n});\n</code></pre>\n\n<p>Again here you are doing unnecessary stuff </p>\n\n<pre><code>$('.login').empty();\n$('.buttonArea').empty();\n</code></pre>\n\n<p>When you can simple do this </p>\n\n<pre><code>$('.login, .buttonArea').empty();\n</code></pre>\n\n<p>I'm not 100% sure on this one but I'm sure you can use 1 <code>eventListener</code> instead of 2 here</p>\n\n<pre><code> $('.buttonArea').on('click', '#sSignUp', function () {\n $('#target').trigger('submit');\n });\n\n // Submit login form\n $('.buttonArea').on('click', '#sLogin', function () {\n $('#target').trigger('submit');\n });\n</code></pre>\n\n<p>You should try this </p>\n\n<pre><code> $('.buttonArea').on('click', '#sLogin, #sSignUp', function () {\n $('#target').trigger('submit');\n });\n</code></pre>\n\n<p>I'm sure that's enough to keep you busy for now :) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T04:19:10.233",
"Id": "28451",
"ParentId": "28450",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28451",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T04:10:09.230",
"Id": "28450",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"form",
"twitter-bootstrap"
],
"Title": "Log in / sign up form"
}
|
28450
|
<p>Each data structure has its own time complexities. The biggest one that jumps out at you is the hash table. The average times for Insertion, Deletion and Searching are all O(1). But it's really just constant time, since there can be multiple reps through each of these to find the right spot. The real question is, can we do each of those operations in exactly one operation, if space wasn't an issue?</p>
<p>Recently I was working on the radix sort, and figuring out how to speed it up as much as possible. The one thing I settled on was doing a 2-byte counting sort, thus you would only have to loop once through. Then I got to thinking about the trie I used before, with integers where I traversed through by modding the number by 10 each time through. </p>
<p>This seemed to be faster than any other data structure that I've tried, but wanted to make it faster. What I tried today was treating the trie as a guaranteed 2-level tree: each node with \$2^{16}\$ (65536) children. That way I can reference each number like this: <code>root->link[twoByte1]->link[twoByte2]</code>. Where <code>twoByte1</code> is the first 16 bits, and <code>twoByte2</code> is the second 16-bit chunk. Problem is, this is a lot of memory. Instead, I decided to make an array of structures, with \$2^{16}\$ bool (uint8_t) values instead, and ran across the same issue. To fix this, I made the following structure.</p>
<pre><code>struct trie {
unsigned int link[2048];
};
</code></pre>
<p>I decided to use 2048 unsigned integers (or signed, wasn't sure if there would be a difference) instead. That way I can treat each bit as the true/false value during look up. In order to reference each position, I would take the first 16 bytes, and reference the element he same way as before, but the 2nd I would divide by 32 to find out which element of the integer array to use, and mod the number again by 32 to find out which bit to look at. The following is the code I used to reference it:</p>
<pre><code>uint8_t getData (int data, uint16_t& dir, uint16_t& pos, uint8_t& x) {
dir = (data >> 0) & 0xffff;
pos = (data >> 16) & 0xffff;
x = pos / 32;
return pos % 32;
}
</code></pre>
<p>The <code>insert</code> function was simply finding the spot and turning the bit on. To do this, I would get the data from the function above, then OR the specific bit with 1. Similarly with deletion, only I would invert the bit string, then AND it, to turn it off. Then to search for that element, I would just return the specific bit. Help with how to clear the bit was found in <a href="//stackoverflow.com/q/47981"><em>How do you set, clear, and toggle a single bit?</em> on SO</a>.</p>
<p>Here is the code for those three functions:</p>
<pre><code>void insert(trie *root, int data) {
uint16_t dir, pos;
uint8_t x, y = getData(data, dir, pos, x);
root[dir].link[x] |= 1 << y;
}
bool find(trie *root, int data) {
uint16_t dir, pos;
uint8_t x, y = getData(data, dir, pos, x);
return root[dir].link[x] & (1 << y);
}
void remove(trie *root, int data) {
uint16_t dir, pos;
uint8_t x, y = getData(data, dir, pos, x);
root[dir].link[x] &= ~(1 << y);
}
</code></pre>
<p>From here it was as simple as initializing the array of structs. The great thing is that with the number of elements coming in, the data structure will never grow any farther out. Also, in the case of threading, since I'm only turning the bits on during insertion, I don't think I would need to synchronize any of the threads. Therefore it could be speed up with threading. What are your thoughts on this? I made a <a href="http://ideone.com/McwWTV" rel="nofollow noreferrer">test case on Ideone</a>. I ran a test on a Linux machine running on an i7, and was able to process 250 million integers every 2.5 seconds.</p>
|
[] |
[
{
"body": "<p>First there is no C++ here.<br>\nYou are simply doing C (use class and member functions that way you will not be passing pointers around).</p>\n\n<p>So what you have implemented is a chunked set.\nEach chunk <code>trie</code> uses 2048 integers to hold existence information and somewhere outside the scope of code review you are creating arrays of theses to define your set.</p>\n\n<p>Looking at the code:</p>\n\n<pre><code>uint16_t dir, pos;\nuint8_t x, y = getData(data, dir, pos, x);\n</code></pre>\n\n<p>This is awful. The first think I am thinking is that <code>x</code> is undefined because you think that functions can return multiple values. <strong>BUT</strong> I read on and find that <code>x</code> is passed in and is assigned inside the function. This is just horrible in terms of style and readability.</p>\n\n<p>Rues of thumb:</p>\n\n<ol>\n<li>Declare one variable per line (and make their names meaningful).</li>\n<li>Don't mix input/output parameters and return values all in the same function.<br>\nWhen you use output parameters the result is usually a success value.</li>\n</ol>\n\n<p>What is <code>trie</code>.</p>\n\n<pre><code>bool find(trie *root, int data)\n</code></pre>\n\n<p>It looks like you have to pass an array of them through for this to work. From inside this function I can not tell how legal it is to access multiple elements. I am assuming the memory management is done somewhere else but who know.</p>\n\n<p>You are making the assumption that an unsigned int is 32 bits.</p>\n\n<pre><code>return pos % 32; // assigned to y\n\n// All your code then calculates bit offsets like this\n(1 << y)\n</code></pre>\n\n<p>The standard only requires 16. <a href=\"https://stackoverflow.com/a/271132/14065\">https://stackoverflow.com/a/271132/14065</a></p>\n\n<p>Overall I think this is marginal for <strong>C</strong> code as you can not do much more.<br>\nBut for <strong>C++</strong> code this absolutely terrible. There is no encapsulation, there is no protection from using the code wrong. There is no initialization to make sure it is all set to zero.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T18:36:14.093",
"Id": "28470",
"ParentId": "28453",
"Score": "4"
}
},
{
"body": "<p><code>int data; data >> 16</code> is actually <em>Undefined Behavior</em>. My suggestion, in addition to most of what's already been said, is to stick to <code>unsigned int</code>s as much as possible in C.</p>\n\n<p>Edit: uppercased Undefined Behaviour again (after someone unhelpfully lowercased it) because it’s a technical term from the standard.</p>\n\n<p>It’s Undefined Behaviour if data is negative, that is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:20:42.307",
"Id": "46068",
"Score": "0",
"body": "Technically, it's UB iff `int` is 16 bits or less. Or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-11T14:47:56.520",
"Id": "382377",
"Score": "1",
"body": "@Listor: `int` is a signed type."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:57:23.523",
"Id": "29194",
"ParentId": "28453",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-07-14T05:37:28.720",
"Id": "28453",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"performance",
"binary-search",
"hash-map"
],
"Title": "Fast integer handling"
}
|
28453
|
<p>I have a C++ class which acts as an abstraction for an IO device which is controlled through file descriptors. As I am very new to C++, I would be glad if you can give me devastating feedback on things I've done wrong.</p>
<p>This especially covers:</p>
<ul>
<li>Code style</li>
<li>Design patterns</li>
<li>Error handling</li>
<li>Things which are open for failures</li>
<li>C++ approaches which can be used over C approaches (file IO)</li>
</ul>
<p><strong>gpio.h</strong></p>
<pre><code>#ifndef SRC_GPIO_H_
#define SRC_GPIO_H_
#define GPIO_IN 0
#define GPIO_OUT 1
#define GPIO_LOW 0
#define GPIO_HIGH 1
class GPIO {
public:
explicit GPIO(int id);
~GPIO();
int Value();
void Value(int value);
int Direction();
void Direction(int value);
private:
int _id;
int _value_fd;
int _direction_fd;
bool Exists();
void Export();
void Unexport();
void OpenValueFd();
void OpenDirectionFd();
void CloseValueFd();
void CloseDirectionFd();
void SeekToTopOfValueFd();
void SeekToTopOfDirectionFd();
};
#endif
</code></pre>
<p><strong>gpio.cc</strong></p>
<pre><code>#include "../src/gpio.h"
#define GPIO_PATH_EXPORT "/sys/class/gpio/export"
#define GPIO_PATH_UNEXPORT "/sys/class/gpio/unexport"
#define GPIO_PATH_DIRECTORY "/sys/class/gpio/gpio%d"
#define GPIO_PATH_DIRECTION "/sys/class/gpio/gpio%d/direction"
#define GPIO_PATH_VALUE "/sys/class/gpio/gpio%d/value"
GPIO::GPIO(int id) {
Export();
OpenValueFd();
OpenDirectionFd();
}
GPIO::~GPIO() {
CloseValueFd();
CloseDirectionFd();
Unexport();
}
bool
GPIO::Exists() {
char * path;
if (asprintf(&path, GPIO_PATH_DIRECTORY, id) < 0)
throw "Error generationg GPIO directory path.";
int result = access(path, F_OK);
free(path);
return static_cast<bool> result++;
}
void
GPIO::Export() {
char * id;
if (Exists()) return;
if (asprintf(&id, "%d", _id) < 0)
throw "Error converting id to char.";
int fd = open(GPIO_PATH_EXPORT, O_WRONLY);
if (fd < 0)
throw "Error opening GPIO export.";
if (write(fd, id, strlen(id)) < 0)
throw "Error writing to GPIO export.";
if (close(fd) < 0)
throw "Error closing GPIO export.";
free(id);
}
void
GPIO::Unexport() {
char * id;
if (!Exists()) return;
if (asprintf(&id, "%d", _id) < 0)
throw "Error converting id to char.";
int fd = open(GPIO_PATH_UNEXPORT, O_WRONLY);
if (fd < 0)
throw "Error opening GPIO unexport.";
if (write(fd, id, strlen(id)) < 0)
throw "Error writing to GPIO unexport.";
if (close(fd) < 0)
throw "Error closing GPIO unexport.";
free(id);
}
int
GPIO::Value() {
char data[2];
SeekValueFdToTop();
data[1] = 0;
if (read(_value_fd, data, 1) < 0)
throw "Error reading from GPIO value.";
if (strncmp(data, "0", 1) == 0)
return GPIO_LOW;
if (strncmp(data, "1", 1) == 0)
return GPIO_HIGH;
throw "Invalid GPIO value.";
}
void
GPIO::Value(int value) {
SeekValueFdToTop();
switch (value) {
case GPIO_LOW:
if (write(_value_fd, "0\n", 2) < 0)
throw "Error writing to GPIO value.";
break;
case GPIO_HIGH:
if (write(_value_fd, "1\n", 2) < 0)
throw "Error writing to GPIO value.";
break;
default:
throw "Error cannot set invalid GPIO value.";
}
}
int
GPIO::Direction() {
char data[4];
SeekValueFdToTop();
data[3] = 0;
if (read(_direction_fd, data, 1) < 0)
throw "Error reading from GPIO direction.";
if (strncmp(data, "in", 2) == 0)
return GPIO_IN;
if (strncmp(data, "out", 3) == 0)
return GPIO_OUT;
throw "Invalid GPIO direction.";
}
void
GPIO::Direction(int value) {
SeekValueFdToTop();
switch (value) {
case GPIO_IN:
if (write(_value_fd, "in\n", 3) < 0)
throw "Error writing to GPIO direction.";
break;
case GPIO_OUT:
if (write(_value_fd, "out\n", 4) < 0)
throw "Error writing to GPIO direction.";
break;
default:
throw "Error cannot set invalid GPIO direction.";
}
}
void
GPIO::OpenValueFd() {
char * path;
if (asprintf(&path, GPIO_PATH_VALUE, _id) < 0)
throw "Error generating GPIO value path.";
if ((_value_fd = open(path, O_RDWR)) < 0)
throw "Error opening GPIO value.";
free(path);
}
void
GPIO::OpenDirectionFd() {
char * path;
if (asprintf(&path, GPIO_PATH_DIRECTION, _id) < 0)
throw "Error generating GPIO direction path.";
if ((_direction_fd = open(path, O_RDWR)) < 0)
throw "Error opening GPIO direction.";
free(path);
}
void
GPIO::CloseValueFd() {
if (close(_value_fd) < 0)
throw "Error closing GPIO value.";
}
void
GPIO::CloseDirectionFd() {
if (close(_direction_fd) < 0)
throw "Error closing GPIO direction.";
}
void
GPIO::SeekToTopOfValueFd() {
if (lseek(_value_fd, SEEK_SET, 0) < 0)
throw "Error seeking to top of GPIO value.";
}
void
GPIO::SeekToTopOfDirectionFd() {
if (lseek(_direction_fd, SEEK_SET, 0) < 0)
throw "Error seeking to top of GPIO direction.";
}
</code></pre>
<p>Source can be found <a href="https://github.com/bodokaiser/node-native-gpio/tree/master/src" rel="nofollow">here</a></p>
|
[] |
[
{
"body": "<h2>Prefer the C++ way</h2>\n\n<p>As you seem to expect, one of the key issues with your code is that it's not very C++y.</p>\n\n<h3>1. Prefer <code>std::string</code> over C-style strings.</h3>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/string/basic_string\"><code>std::string</code></a> is better in almost every way. It takes care of its own memory and grows when needed. The speed is usually comparable to C-style strings (sometimes faster, sometimes slower). The code written using <code>string</code> is often more readable. For example, compare your code:</p>\n\n<pre><code>if (strncmp(data, \"in\", 2) == 0)\n</code></pre>\n\n<p>with the <code>std::string</code> variant:</p>\n\n<pre><code>if (data == \"in\")\n</code></pre>\n\n<h3>2. Prefer <code>iostream</code> to <code>FILE*</code>.</h3>\n\n<p>The C++ library for IO is typesafe, extensible, object-oriented and should be preferred. Use an <code>ifstream</code> to read from a file and <code>ofstream</code> to write, or <code>fstream</code> for both.</p>\n\n<h3>3. Consider throwing exceptions derived from <code>std::runtime_error</code> and <code>std::logic_error</code></h3>\n\n<p>By having an exception hierarchy, you can have fine grained control over which errors to catch where. Your code will also play nice with others, who might expect your exceptions to behave like the standard ones. Want to catch everything? Catch <code>std::exception</code>. Want to catch only your own? Do so. Want to get the error message? Call <code>.what()</code>.</p>\n\n<p>Remember that exceptions should always be thrown by value, and <code>catch</code>ed (caught) by reference(-to-<code>const</code>).</p>\n\n<h3>4. Prefer <code>enum</code> or <code>const</code>s to <code>#define</code>d constants.</h3>\n\n<p>Instead of</p>\n\n<pre><code>#define GPIO_IN 0\n#define GPIO_OUT 1\n</code></pre>\n\n<p>write</p>\n\n<pre><code>enum IODirection { GPIO_IN = 0, GPIO_OUT = 1 };\n</code></pre>\n\n<p>For your path name <code>#define</code>s, use <code>const std::string</code> instead. (And consider moving them into class scope as <code>static</code>, or into a namespace.)</p>\n\n<p>You get type safety, easier debugging, normal scope rules; the works.</p>\n\n<h3>5. Avoid leading underscores in identifiers.</h3>\n\n<p>The following identifiers are <strong>reserved</strong>:</p>\n\n<ul>\n<li>Any name that begins with an underscore and is in the global namespace.</li>\n<li>Any name that begins with an underscore followed by a capital letter.</li>\n<li>Any name that contains two consecutive underscores.</li>\n</ul>\n\n<p>While your <code>_id</code> and similar variables are technically correct, don't rely on yourself or others memorizing these rules. Play it safe and move the underscore to the other side: <code>id_</code>, or drop it altogether.</p>\n\n<h2>Other things</h2>\n\n<p>These are mostly nitpicking, but you asked for a \"very critical review\" :-)</p>\n\n<h3>6. <code>#include</code> the proper headers.</h3>\n\n<p>I'm guessing you already are, and that maybe they were removed when posting the code for review. I'm mentioning it just in case. It's nice to include <code>#include</code>s in the review code, too.</p>\n\n<h3>7. Let the build system take care of include paths.</h3>\n\n<p>Instead of: <code>#include \"../src/gpio.h\"</code>, prefer to just use <code>#include \"gpio.h\"</code> and let the preprocessor and build system take care of finding the right header for you. This makes it a lot easier to move files at a later point.</p>\n\n<h3>8. Don't cast unless you have to.</h3>\n\n<p>Instead of</p>\n\n<pre><code>return static_cast<bool> result++;\n</code></pre>\n\n<p>write</p>\n\n<pre><code>return result++ != 0;\n</code></pre>\n\n<p>(And use parenthesis on your casts.)</p>\n\n<h3>9. Use <code>fclose()</code> instead of <code>close()</code>.</h3>\n\n<p>The C library function is called <code>fclose()</code>. (This is a moot point, however, since you should prefer C++ IO anyway.)</p>\n\n<h3>10. Use descriptive names and a clear interface</h3>\n\n<p>Your public interface functions have names that imply that they don't change the state of the class. If they don't, make the functions <code>const</code>. (Your <code>Exists()</code> function should at least be <code>const</code>. The same <em>may</em> apply to functions that are only reading.) Consider separating the state changing functionality from the non-state-changing functionality, and putting the latter into <code>const</code> functions.</p>\n\n<p>Rename functions that <em>do</em> change state to reflect that.</p>\n\n<p>Finally, <code>data</code> is a classic, horrible variable name. I'm sure you can do better!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T11:27:46.400",
"Id": "28462",
"ParentId": "28455",
"Score": "14"
}
},
{
"body": "<p>A few points to add to those from @Lstor. </p>\n\n<p>Firstly I'm puzzled about the underlying GPIO devices - why use character\nstrings in the interface to a GPIO?</p>\n\n<p>And quite fundamentally, you don't seem to have compiled your code. </p>\n\n<ul>\n<li><code>GPIO::GPIO()</code>: id is not used (to set the class variable)</li>\n<li><code>GPIO::Exists()</code>: uses <code>id</code> not <code>_id</code></li>\n<li><code>GPIO::Exists()</code>: return statement is missing brackets. </li>\n<li><code>SeekValueFdToTop</code> des not exist (called in <code>Value</code> and <code>Direction</code> functions)</li>\n</ul>\n\n<hr>\n\n<p>In <code>GPIO::Exists()</code> the <code>result++</code> gets it wrong in two ways:</p>\n\n<ul>\n<li><p>firstly it is horrible to rely on the -1/0 return from <code>access</code> to to\nbe turned into 0/1 by incrementing</p></li>\n<li><p>secondly you use post-increment, so it doesn't happen.</p></li>\n</ul>\n\n<p>You should be using </p>\n\n<pre><code>return result == 0; // returns `true` if file exists\n</code></pre>\n\n<hr>\n\n<p>You use <code>asprintf</code> everywhere. I had to look that up and find it is a\nnon-standard function that allocates the necessary string. Using it to create\npaths on-demand seems unnecessary. You could create the base path just once\nin the constructor. But I'm a C-guy and all that allocation/deallocation is\nforeign to me. I guess C++ strings will be doing that in the background if\nyou use strings instead...</p>\n\n<hr>\n\n<p>You should use brackets, even when not strictly needed:</p>\n\n<pre><code>if (asprintf(&path, GPIO_PATH_VALUE, _id) < 0) {\n throw \"Error generating GPIO value path.\";\n}\n</code></pre>\n\n<p><hr>\nYour <code>Value</code> and <code>Direction</code> functions have various issues. </p>\n\n<ul>\n<li><p>Using <code>strncmp</code> in <code>Value</code> to check for \"0\" and \"1\" is not sensible. Instead, use </p>\n\n<pre><code>if (data[0] == '0') {...} \n</code></pre>\n\n<p>although <code>data</code> does not need to be an array when reading a single char.</p></li>\n<li><p>I think you should have separate get/set functions rather than overloading\n<code>Value</code> and <code>Direction</code> to mean either get or set.</p></li>\n<li><p>You use non-existent <code>SeekValueFdToTop</code> in both the <code>Value</code> and <code>Direction</code> functions.\nThe appropriate functions are <code>SeekToTopOfValueFd</code> and\n<code>SeekToTopOfDirectionFd</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T13:59:08.940",
"Id": "28463",
"ParentId": "28455",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "28462",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T09:02:51.013",
"Id": "28455",
"Score": "5",
"Tags": [
"c++",
"linux",
"io"
],
"Title": "Abstraction for an IO device"
}
|
28455
|
<p>I want to remove not only spaces, but certain characters, as well from the beginning or end of a JavaScript string. </p>
<pre><code>function trim(str, characters) {
var c_array = characters.split('');
var result = '';
for (var i=0; i < characters.length; i++)
result += '\\' + c_array[i];
return str.replace(new RegExp('^[' + result + ']+|['+ result +']+$', 'g'), '');
}
</code></pre>
<p>The function can be used as follows:</p>
<pre><code>trim(' - hello** +', '+*- ');
</code></pre>
<p>The escaping is required as <code>+ * .</code> etc. would be used in the regular expression. Is there a better way to trim any character in JavaScript? Or a better way to do the escaping, as not every character needs it?</p>
|
[] |
[
{
"body": "<p>There are many different ways to tackle trimming <a href=\"/questions/tagged/strings\" class=\"post-tag\" title=\"show questions tagged 'strings'\" rel=\"tag\">strings</a>, a <a href=\"/questions/tagged/regex\" class=\"post-tag\" title=\"show questions tagged 'regex'\" rel=\"tag\">regex</a> is probably the most popular, and there are lots of blogs and performance tests out there, (<kbd><a href=\"http://blog.stevenlevithan.com/archives/faster-trim-javascript\">one such blog</a></kbd>), that you can look at and decide which is best.</p>\n\n<p>So continuing along the lines that you have demonstrated, then this may be of some help to you.</p>\n\n<p>Javascript</p>\n\n<pre><code>/*jslint maxerr: 50, indent: 4, browser: true */\n\nvar trim = (function () {\n \"use strict\";\n\n function escapeRegex(string) {\n return string.replace(/[\\[\\](){}?*+\\^$\\\\.|\\-]/g, \"\\\\$&\");\n }\n\n return function trim(str, characters, flags) {\n flags = flags || \"g\";\n if (typeof str !== \"string\" || typeof characters !== \"string\" || typeof flags !== \"string\") {\n throw new TypeError(\"argument must be string\");\n }\n\n if (!/^[gi]*$/.test(flags)) {\n throw new TypeError(\"Invalid flags supplied '\" + flags.match(new RegExp(\"[^gi]*\")) + \"'\");\n }\n\n characters = escapeRegex(characters);\n\n return str.replace(new RegExp(\"^[\" + characters + \"]+|[\" + characters + \"]+$\", flags), '');\n };\n}());\n\n/*jslint devel: true */\n\nconsole.log(trim(\" - hello** +\", \"+*- \"));\n</code></pre>\n\n<p>On <kbd><a href=\"http://jsfiddle.net/Xotic750/QNPa8/\">jsfiddle</a></kbd></p>\n\n<p>Of course, you can customise which characters you wish to escape, or flags to test for, as per your own needs. <kbd><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\">Regular Expressions</a></kbd></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T08:52:10.753",
"Id": "86141",
"Score": "0",
"body": "Good solution, but please use following function to determine if the parameter is a string:\n`var isString = function(str) { return typeof str == 'string' || str instanceof String; };`\nIf you try to use a string like this `new String('123')` it won't work..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T14:52:33.430",
"Id": "86191",
"Score": "0",
"body": "If that was a concern then I would probably go for `Object.prototype.toString.call(str) === '[object String]'` as a safer option."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T14:58:07.027",
"Id": "28465",
"ParentId": "28464",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "28465",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T14:24:30.347",
"Id": "28464",
"Score": "15",
"Tags": [
"javascript",
"strings",
"regex"
],
"Title": "Trim certain characters from a string in JavaScript"
}
|
28464
|
<p>I have multiple different implementations of an object, which implement this custom <code>interface</code> I made called <code>Board</code>.</p>
<p><code>Board</code> contains a method that looks like the following</p>
<pre><code>public void ConvertFromString(String formattedString);
</code></pre>
<p>Each object implementing <code>Board</code> calls <code>ConvertFromString()</code> in its constructor. </p>
<p>Looks like the following.</p>
<pre><code>public void BoardImpl1 implements Board
{
public Board(string B)
{
ConvertFromString(b);
}
public void ConvertFromString(String formattedString)
{
//do some parsing on string and set up the BoardImpl properties
}
}
</code></pre>
<p>ConvertFromString being public causes a warning, so the best practice workaround would be to make <code>BoardImpl</code> final. Is there a better way to write this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T16:36:22.667",
"Id": "44695",
"Score": "4",
"body": "Voting to close, as I think this question is better suited on StackOverflow. While your code is technically working, in practice it is not. You are not really asking for a code review, you are asking for a solution to a problem; which belongs on SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T16:58:51.923",
"Id": "44697",
"Score": "0",
"body": "Well I'm not sure if my OP wasn't clear. I stated that I can make my class Final, which gets rid of the warning.\n\nI was wondering if something should be restructured so that I don't end up making a bunch of final classes each time I want to implement the Interface."
}
] |
[
{
"body": "<p>The warning you get, is because you call an overridable method from your constructor. This is bad because subclasses may change the implementation of the method to access other parts of the object, while it is not fully initialized yet.</p>\n\n<p>So to get rid of the warning : don't call overridable methods from the constructor.</p>\n\n<p>Then how to get around your predicament?</p>\n\n<p>Well you could : </p>\n\n<ul>\n<li>make the public method final.</li>\n<li>make the class final (which you found yourself)</li>\n<li>duplicate the logic (while possible, not the way to go)</li>\n<li>have the public method delegate to a private method, and have the constructor call the private method.</li>\n</ul>\n\n<p>Like this : </p>\n\n<pre><code>public class BoardImpl implements Board {\n public BoardImpl(String b) {\n doConvertFromString(b);\n }\n\n public void convertFromString(String formattedString) {\n doConvertFromString(formattedString);\n }\n\n private void doConvertFromString(String formattedString) {\n //do some parsing on string and set up the BoardImpl properties\n }\n}\n</code></pre>\n\n<p>I wouldn't worry about making all implementations final. <em>final is your friend</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T18:27:18.477",
"Id": "28469",
"ParentId": "28466",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28469",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T15:33:02.973",
"Id": "28466",
"Score": "1",
"Tags": [
"java",
"interface"
],
"Title": "Defining a Constructor In an Interface Java?"
}
|
28466
|
<p>I've received reviews on the last version <a href="https://codereview.stackexchange.com/questions/28455/c-class-needs-a-very-critical-review">here</a>, but as an update would make the answers not fitting anymore, I think it is wise to open a new post.</p>
<p>I followed most of the hints of the last review and now want to check if I done things write or made new mistakes.</p>
<p>If you are interested in the complete source click <a href="https://github.com/bodokaiser/node-native-gpio/blob/2902666f9cd5ceb99b3edaf698a8a217572d7a92/src/gpio.cc" rel="nofollow noreferrer">here</a></p>
<p><strong>gpio.h</strong></p>
<pre><code>#ifndef SRC_GPIO_H_
#define SRC_GPIO_H_
#include <string>
#include <fstream>
#include <iostream>
using std::string;
using std::fstream;
enum GPIODirection {
GPIO_IN = 0,
GPIO_OUT = 1
};
enum GPIOValue {
GPIO_LOW = 0,
GPIO_HIGH = 1
};
class GPIO {
public:
explicit GPIO(int id);
~GPIO();
int Value();
void Value(int value);
int Direction();
void Direction(int value);
private:
int id_;
fstream value_;
fstream direction_;
bool Exists();
void Export();
void Unexport();
static const string PATH_EXPORT;
static const string PATH_UNEXPORT;
static const string PREFIX;
static const string POSTFIX_VALUE;
static const string POSTFIX_DIRECTION;
};
#endif
</code></pre>
<p><strong>gpio.cc</strong></p>
<pre><code>#include "gpio.h"
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include <exception>
#include <stdexcept>
using std::ios;
using std::endl;
using std::string;
using std::stringstream;
using std::logic_error;
using std::runtime_error;
const string GPIO::PATH_EXPORT = "/sys/class/gpio/export";
const string GPIO::PATH_UNEXPORT = "/sys/class/gpio/unexport";
const string GPIO::PREFIX = "/sys/class/gpio/gpio";
const string GPIO::POSTFIX_VALUE = "/value";
const string GPIO::POSTFIX_DIRECTION = "/direction";
GPIO::GPIO(int id) {
id_ = id;
Export();
stringstream value_path;
stringstream direction_path;
value_path << PREFIX;
value_path << id;
value_path << POSTFIX_VALUE;
direction_path << PREFIX;
direction_path << id;
direction_path << POSTFIX_DIRECTION;
value_.open(value_path.str().c_str());
direction_.open(direction_path.str().c_str());
}
GPIO::~GPIO() {
value_.close();
direction_.close();
Unexport();
}
bool
GPIO::Exists() {
stringstream path;
path << PREFIX;
path << id_;
fstream gpio;
gpio.open(path.str().c_str());
bool result = gpio.good();
gpio.close();
return result;
}
void
GPIO::Export() {
if (Exists()) return;
fstream gpio_export;
stringstream string_stream;
string_stream << id_;
gpio_export.open(PATH_EXPORT.c_str(), ios::out);
gpio_export << string_stream.str();
gpio_export.close();
}
void
GPIO::Unexport() {
if (!Exists()) return;
fstream gpio_unexport;
stringstream string_stream;
string_stream << id_;
gpio_unexport.open(PATH_UNEXPORT.c_str(), ios::out);
gpio_unexport << string_stream.str();
gpio_unexport.close();
}
int
GPIO::Value() {
string value;
value_.seekp(0);
value_ >> value;
if (value == "0") return GPIO_LOW;
if (value == "1") return GPIO_HIGH;
throw logic_error("Invalid GPIO value.");
}
void
GPIO::Value(int value) {
value_.seekp(0);
switch (value) {
case GPIO_LOW:
value_ << "0" << endl;
if (!value_.good())
throw runtime_error("Error writting to value file stream.");
break;
case GPIO_HIGH:
value_ << "1" << endl;
if (!value_.good())
throw runtime_error("Error writting to value file stream.");
break;
default:
throw logic_error("Error cannot set invalid GPIO value.");
}
}
int
GPIO::Direction() {
string direction;
direction_.seekp(0);
direction_ >> direction;
if (direction == "in") return GPIO_IN;
if (direction == "out") return GPIO_OUT;
throw logic_error("Invalid GPIO direction.");
}
void
GPIO::Direction(int value) {
direction_.seekp(0);
switch (value) {
case GPIO_IN:
direction_ << "in" << endl;
if (!direction_.good())
throw runtime_error("Error writting to direciton file stream.");
break;
case GPIO_OUT:
direction_ << "out" << endl;
if (!direction_.good())
throw runtime_error("Error writting to direciton file stream.");
break;
default:
throw logic_error("Error cannot set invalid GPIO direction.");
}
}
</code></pre>
<p>Things I guess could be done better:</p>
<ul>
<li>class methods</li>
<li>implementation of Exist()</li>
<li>error handling</li>
<li>string formatting</li>
<li>path constants</li>
<li>int to string cast (std::to_string seems not to be available)</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T18:48:16.130",
"Id": "44703",
"Score": "0",
"body": "Check this out for argument about explicitly calling close: http://codereview.stackexchange.com/q/540/507"
}
] |
[
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>To me, <code>value</code> and <code>direction</code> don't sound like stream names. Maybe they should be called something else? It depends on the domain terminology (which I'm not familiar with).</p></li>\n<li><p>Don't ever pollute the global namespace by using <code>using</code> in headers. Write the full qualifiers.</p></li>\n<li><p>Your <code>stringstream</code> operations look like they can be factored out into a separate function.</p></li>\n<li><p>Note that <code>std::endl</code> forces a stream flush. If you just want the newline, use <code><< '\\n'</code> instead.</p></li>\n<li><p>I think it's nice to sort <code>#include</code>s alphabetically.</p></li>\n<li><p>In C++11, <code>fstream::open</code> takes a <code>std::string</code> argument as well.</p></li>\n<li><p>Consider changing the names of <code>Value</code> and <code>Direction</code> (like William Morris points out in the other review). If a function changes the state of the object, it should be named differently (probably with a verb).</p></li>\n<li><p>Prefer to initialize variables using initializer lists in constructors.</p></li>\n<li><p>Your <code>Value</code> and <code>Direction</code> functions are nearly identical.</p></li>\n</ul>\n\n<p>You can refactor to something like this:</p>\n\n<pre><code>std::string GPIO::ReadFromBeginningOfStream(std::fstream& stream)\n{\n stream.seekg(0); // NOTE: seekg, *not* seekp\n std::string tmp;\n stream >> tmp;\n return tmp;\n}\n\nint\nGPIO::Value() {\n std::string const& value = ReadFromBeginningOfStream(value_);\n\n if (value == \"0\") return GPIO_LOW;\n if (value == \"1\") return GPIO_HIGH;\n\n throw logic_error(\"Invalid GPIO value.\");\n}\n</code></pre>\n\n<p>And then similar but with passing in the other stream in <code>Direction()</code>.</p>\n\n<p><strong>NOTE:</strong> Seek in an <em>input</em> stream by calling <code>seekg()</code>; in an <em>output</em> stream by calling <code>seekp()</code>.</p>\n\n<ul>\n<li><code>Exists()</code> should be <code>const</code>, like this: <code>bool Exists() const;</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T16:49:37.280",
"Id": "44696",
"Score": "0",
"body": "What do you mean with the \"using\" headers? Should I just always use std::string or v8::Object? I renamed the functions to SetValue, GetValue, ... I also need \"<< std::endl\" else the value is not written (tried this already) Also I get a compiler error on settings Exists() const"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T17:02:25.313",
"Id": "44698",
"Score": "1",
"body": "You can use `using` in implementation files (preferably inside each function), but not in headers. If you need flushing, then use `endl` like you are, I just mentioned it :-) Which error do you get if you set `Exists()` to const?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T17:58:31.067",
"Id": "44700",
"Score": "0",
"body": "(You added the `const` to `Exists()` in both the declaration and definition, right?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T17:59:12.430",
"Id": "44701",
"Score": "0",
"body": "When I just put `bool Exists() const` to the header the compiler says that Exists() does not match any declaration"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T18:01:50.317",
"Id": "44702",
"Score": "0",
"body": "ah you have to place the const in the implementation between Exists() and opening bracket - did not knew this"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T16:12:53.520",
"Id": "28468",
"ParentId": "28467",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28468",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T15:46:28.603",
"Id": "28467",
"Score": "3",
"Tags": [
"c++"
],
"Title": "GPIO wrapper class"
}
|
28467
|
<p>I am creating an application just for practicing c# as well as new programming ways. So i came across the idea that i create an application that stores information about "soldiers" ex. Names, ranks, titles, etc... but the trick here is that i want the soldier title to be automatically upgraded when it's rank increases.</p>
<h3>I have created a small application to demonstrate the idea.</h3>
<h2>Soldier Class</h2>
<pre><code>public class Soldier
{
public string Name { get; private set; }
public int Rank { get; private set; }
public string Title { get; private set; }
public Soldier(string name)
{
Name = name;
RefreshTitle();
}
public void Rankup(int rank = -1)
{
if (-1 != rank)
Rank = rank;
else
Rank++;
RefreshTitle();
}
public void RefreshTitle()
{
Title = SoldierRankLibrary.GetSoldierTitle(Rank);
}
}
</code></pre>
<h2>Soldier Rank Library</h2>
<pre><code>public class SoldierRankLibrary
{
private static readonly Dictionary<int, string> RankDictionary = new Dictionary<int, string>
{
{0, "Novice"},
{1, "Second Lieutenant"},
{2, "First Lieutenant"},
{3, "Captain"},
{4, "Major"},
{5, "Lieutenant Colonel"},
{6, "Colonel"}
//etc...
};
public static string GetSoldierTitle(int requiredRank)
{
return RankDictionary.FirstOrDefault(rank => rank.Key == requiredRank).Value;
}
}
</code></pre>
<h2>Using the code</h2>
<pre><code>static void Main()
{
//Create new soldier...
var soldier = new Soldier("Daniel");
//Print soldier info...
PrintSoldierInfo(soldier);
//Upgrade soldier...
soldier.Rankup();
//Print soldier info...
PrintSoldierInfo(soldier);
Console.Read();
}
static void PrintSoldierInfo(Soldier soldier)
{
Console.WriteLine("****************************************");
Console.WriteLine("Name: {0}", soldier.Name);
Console.Write("Rank: ");
switch (soldier.Rank)
{
case 0:
Console.WriteLine("novice");
break;
case 1:
Console.WriteLine("*");
break;
case 2:
Console.WriteLine("**");
break;
case 3:
Console.WriteLine("***");
break;
case 4:
Console.WriteLine("****");
break;
case 5:
Console.WriteLine("*****");
break;
case 6:
Console.WriteLine("******");
break;
case 7:
Console.WriteLine("*******");
break;
}
Console.WriteLine("Title: {0}", soldier.Title);
Console.WriteLine("****************************************");
Console.WriteLine();
}
</code></pre>
<h2>Conclusion</h2>
<p><em><strong>I am really waiting for your answers and i hope you give me detailed information about what i miss, what i can do better, how could i improve this code.</em></strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T17:46:04.213",
"Id": "44769",
"Score": "0",
"body": "Based upon the code provided, you are avoiding the benefits of polymorphism by using enums and switches and string literals. According to Fowler (and his disciples) these can be classified as 'code smells'. Consider polymorphism and OO design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T12:41:26.770",
"Id": "44822",
"Score": "0",
"body": "While technically not relevant, *novice* is not a military rank :-) Pick your country from the list: [Wikipedia: List of comparative military ranks](http://en.wikipedia.org/wiki/List_of_comparative_military_ranks)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T22:25:06.373",
"Id": "44891",
"Score": "0",
"body": "@Lstor : hehehe i know i was just creating a question :D"
}
] |
[
{
"body": "<p>You can change <code>Rank</code> type to some <code>enum</code>.</p>\n\n<pre><code>public enum Rank\n{\n Unknown = -1,\n Novice = 0,\n SecondLieutenant = 1,\n ....\n}\n\npublic static class SoldierRankLibrary\n{\n private static readonly Dictionary<int, string> RankDictionary = new Dictionary<Rank, string>\n {\n {Rank.Novice, \"Novice\"},\n ....\n };\n\n public static string DisplayName(this Rank rank)\n {\n if (RankDictionary.ContainsKey(rank))\n {\n return RankDictionary[rank];\n }\n return rank.ToString();\n }\n}\n\npublic class Soldier\n{\n public string Name { get; private set; }\n public Rank Rank { get; private set; }\n public string Title { get { return Rank.DisplayName(); } }\n\n public Soldier(string name, Rank rank = Rank.Unknown)\n {\n Name = name;\n Rank = rank;\n }\n\n public void Rankup()\n {\n Rank++;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T18:21:25.207",
"Id": "44776",
"Score": "0",
"body": "Very nice well detailed explanation thank you very much Nik"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:30:55.237",
"Id": "28489",
"ParentId": "28471",
"Score": "1"
}
},
{
"body": "<p><strong>Get rid of SoldierRankLibrary</strong></p>\n\n<ul>\n<li><code>GetSoldierRank()</code> belongs in the <code>Soldier</code> class. That's what <code>Rank { get; set; }</code> is for.</li>\n<li>the <code>Dictionary</code> will be replaced by an <code>enum</code> (see below). An <code>enum</code> does not need be inside of any class. You can use boolean operators on enums (\"<\", \"==\", ...)</li>\n</ul>\n\n<p><strong>Use Enum instead of Dictionary</strong></p>\n\n<ul>\n<li><p>Your dictionary is mimicking an Enum. In other words and Enum\ninherently associates a number with a name. And in general using Enum\nis preferred over strings.</p></li>\n<li><p>Make separate <code>OfficerRank</code> and <code>EnlistedRank</code> enums if that works\nbetter.</p></li>\n<li><p>I like @Nik's answer with \"unknown\". But I'd make it \"0\" instead of\n\"-1\". The natural default value of an enum variable is zero.</p></li>\n<li><p>If the underlying int values matter elsewhere in code just make sure you put the ranks in the desired order.</p></li>\n</ul>\n\n<p><strong>Soldier Class</strong></p>\n\n<ul>\n<li><p><code>Rank</code> and <code>Title</code> appear to be the same thing. Do you really need to refer to the soldier's rank by its underlying (integer) value?</p></li>\n<li><p>Explicitly set variables in the constructor. We all know default values for .NET types, but you want to convey intent and meaning.</p></li>\n<li><p>Exhaustively set the entire state in the constructor. Again, intent and meaning.</p></li>\n<li><p><code>Rankup()</code> - change name to <code>Promote()</code>. Don't pass in an integer, pass in something that has meaning. We're going to utilize <code>Rank</code> enum so this fills the bill.</p></li>\n<li><p><code>RefreshTitle()</code> - obsolete. Rank/Title is the same thing. The <code>Rank</code> enum keeps us from having to deal with a string and an int.</p></li>\n<li><p>Property mis-use. It makes no sense to have a <code>private Title set</code> and\na <code>public RefreshTitle()</code>. Think of a <code>Property</code> as a method. A lot of existing code goes away simply by using the public get properties.</p></li>\n<li><p>Override <code>ToString()</code>. Now <code>PrintSoldierInfo()</code> disappears. </p></li>\n</ul>\n\n<p><strong>New Code</strong></p>\n\n<pre><code>public enum Rank {undefined, BuckPrivate, Sergeant, Lieutenant, Captain}\n\npublic class Soldier {\n public string Name { get; protected set; }\n public Rank Rank { get; protected set; }\n\n public Soldier (string name) {\n Name = name ?? \"No Name\"; // null coalescing.\n Rank = Rank.undefined; // maybe private if enlisted or lieutenant if officer \n }\n\n public void Promote (Rank newRank) {\n if ((int)this.Rank < (int)newRank ) this.Rank = newRank;\n // we don't allow Demotion in this method. \n }\n\n public override string ToString() {\n Stringbuilder me = new Stringbuilder(); // need to import System.Text to use Stringbuilder\n\n// C# string formatting avoids clumsy string concatination; clearer and less error prone\n me.AppendLine(\"Name: {0} Rank: {1}\", Name,Rank); \n\n return me.ToString(); // Stringbuilder must be converted to a string.\n }\n}\n</code></pre>\n\n<p><strong>Using Soldier</strong></p>\n\n<pre><code>Soldier grunt = new Soldier(\"Sad Sack\");\ngrunt.Promote(Rank.Sergeant);\nConsole.WriteLine (grunt); // ToString() is automagically called.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T18:21:04.297",
"Id": "44775",
"Score": "0",
"body": "This is very nice... There are some errors though so i edited your answer please accept the edit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T11:55:59.030",
"Id": "44819",
"Score": "0",
"body": "1. `Dictionary<int, string>` instead of an `enum` can make sense if the `string`s should be human readable, you can't have `\"Second Lieutenant\"` in an `enum`. 2. You can't use `private` as an `enum` value like that, because it's a keyword. You should use the normal .Net naming conventions and write `Private`. Or you could use `@private`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T12:25:36.967",
"Id": "44820",
"Score": "0",
"body": "The issues that `enum` solves and/or prevents here trumps the need to extract proper grammar from `enum` values. Proper grammar is a secondary issue. Then indeed a `Dictionary<Rank, string>` (vice `Dictionary<int, string>`) would do well for extracting `Second Lieutenant` (2 words) from `Rank.SecondLieutenant`. But for Heaven's sake get away from obtuse use of integers and express things in terms of the problem domain."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T17:55:39.033",
"Id": "28518",
"ParentId": "28471",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28518",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T18:44:20.110",
"Id": "28471",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Automatic Property Upgrading"
}
|
28471
|
<p>I'm working on a simple blogsystem (for learning purposes, not to reinvent the wheel). In this system the user can add existing or new tags to a blogpost. I wrote a method to achieve this, but it's ugly, inconvenient and probably of bad performance.</p>
<p>Some facts:</p>
<ul>
<li>I make use of Propel as mapper to a PostgreSQL database</li>
<li>relevant tables in this part are <code>tag</code> and <code>post_tag</code></li>
</ul>
<p>CREATE-Statements:</p>
<pre><code>CREATE TABLE tag (
id integer NOT NULL,
name character varying(100),
slug character varying(100),
modified timestamp(0) without time zone
);
CREATE SEQUENCE tag_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ONLY tag
ADD CONSTRAINT tag_pkey PRIMARY KEY (id);
ALTER TABLE ONLY tag ALTER COLUMN id SET DEFAULT nextval('tag_id_seq'::regclass);
CREATE TABLE post_tag (
post_id integer NOT NULL,
tag_id integer NOT NULL
);
ALTER TABLE ONLY post_tag
ADD CONSTRAINT post_tag_pkey PRIMARY KEY (post_id, tag_id);
ALTER TABLE ONLY post_tag
ADD CONSTRAINT post_tag_post FOREIGN KEY (post_id) REFERENCES post(id) ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE ONLY post_tag
ADD CONSTRAINT post_tag_tag FOREIGN KEY (tag_id) REFERENCES tag(id) ON UPDATE CASCADE ON DELETE CASCADE;
</code></pre>
<ul>
<li>The method is called after submitting the post. It gets the postID and an array containing all tags assigned to this post. It adds new tags in the table <code>tag</code> and makes sure that in table <code>post_tag</code> all new, all previously existing and all previously existing but not assigned tags, which the user chose, are connected to the post.</li>
</ul>
<p>This is the method:</p>
<pre><code> public function addTagByPost($posttags, $postid){
//collect all existing tags
$all = $this->getAllTags();
$existing = array();
foreach($all AS $tags){
$existing[$tags->getName()] = $tags->getId();
}
//delete all tags linked to the post
$links = PostTagQuery::create()
->filterByPostId($postid);
$links->delete();
foreach($posttags AS $tag){
if(!isset($existing[$tag])){
//add new tags from post
$newtag = new Tag();
$newtag->setName($tag);
$newtag->setSlug($this->generateSlug($tag));
$newtag->save();
$tagid = $newtag->getId();
}else{
$tagid = $existing[$tag];
}
//link all tags to the post
$link = new PostTag();
$link->setPostId($postid);
$link->setTagId($tagid);
$link->save();
}
}
</code></pre>
<p>Imagine in table <code>tag</code> are three rows, PHP, MySQL and PostgreSQL. Imagine there is a blogpost tagged with PHP and PostgreSQL. The user edits the post, removing the tag PHP and adding the tag Python. When he submits, the current tags are PostgreSQL and Python.</p>
<p>At first, all existing tags are fetched from db (PHP, MySQL and PostgreSQL).
Then all links between the current post and its tags are deleted from table <code>post_tag</code> (PHP and PostgreSQL).</p>
<p>Now the tags assigned by the user (PostgreSQL and Python) are matched against the existing ones (PHP, MySQL and PostgreSQL). As Python does not already exist, it is added to table <code>tag</code>.</p>
<p>Now, all userassigned tags are accessible via id. These IDs are then inserted into table <code>post_tag</code> (PostgreSQL and Python), so the post is connected to them.</p>
<p>Please feel free to make suggestions.</p>
|
[] |
[
{
"body": "<p>Take a step back and look at your code. Do the different classes/objects ha ve Single responsibility? Or is the same class responsible for adding posts, managing tags and coupling a tag to a post?</p>\n\n<p>I think it is time to go back to the drawing board and see what you actually want/need.</p>\n\n<p>Then every class you write should only have a single responsibility. e.g. representing a comment or a TaggableComment class that extends the Comment class and adds the ability to add and remove tags.</p>\n\n<p>Also make sure that a Class shouldn't have to know how to handle the creation of other objecs. Using the 'new' operator inside a class methods is bad practice. If you would like to change the way a Tag is constructed, you will now have to change the Comment class aswell, not useful.</p>\n\n<p>Look into some programming patterns, A really good read is: <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\" rel=\"nofollow\">http://addyosmani.com/resources/essentialjsdesignpatterns/book/</a> I know, it's not php but javascript. But moest of the patterns there also apply to php, it's the idea behind the patterns that will help you</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T08:40:45.437",
"Id": "28543",
"ParentId": "28473",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T19:32:28.973",
"Id": "28473",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"postgresql",
"propel"
],
"Title": "Adding new or existing tags to a blog post"
}
|
28473
|
<p><a href="http://jsfiddle.net/Cone/v5jaz/2/" rel="nofollow">Here is my script</a> of a simple jQuery-powered galler I've decided to create while studying JavaScript. Please point out my mistakes and let me know how the script can be optimized!</p>
<p><strong>JavaScript</strong></p>
<pre class="lang-js prettyprint-override"><code>// define globals
var overL = $('div.overlay_p');
var temP = $('div.pre_load');
var imgM = $('span.p_img');
var fCont = $('p.aligner');
var allin = $('span.hold_all');
var imGal = $('.img_gallery');
var orImg = $('img.thumb');
var nextB = $('span.next_div');
var prevB = $('span.prev_div');
// function on img click
orImg.on('click', function () {
clearAll();
overL.fadeIn();
currentImage = $(this);
getDim($(this).attr('alt'));
});
// fucntion on NEXT or PREV click
$('span#nav').on('click', function () {
if($(this).attr('class')=='next_div'){
nextImg = currentImage.next('img');
}else{
nextImg = currentImage.prev('img');
}
var nextImgA = nextImg.attr('alt');
currentImage = nextImg;
imgM.fadeOut().delay(600).empty().fadeIn();
getDim(nextImgA);
});
// get WIDTH and HEIGHT of the loaded IMAGE, and load into p_img
function getDim(element) {
temP.html('<img src="' + element + '"/>');
var dUrl = $('img', temP);
checkButtons(currentImage);
var imgW = dUrl.width();
var imgH = dUrl.height();
fCont.animate({
width: imgW,
height: imgH
}, 600, function () {
imgM.html('<img src="' + element + '"/>').parent('span').fadeIn(400);
});
}
//clear cocntainers
function clearAll() {
temP.empty();
imgM.empty();
}
//HIDE relevnt button if NEXT or PREV img does not exist
function checkButtons(element) {
if (element.prev('img').attr('alt') === undefined) {
prevB.hide();
nextB.show();
} else if (element.next('img').attr('alt') === undefined) {
nextB.hide();
prevB.show();
} else {
nextB.show();
prevB.show();
}
}
//on CLOSE click
$('span.close_div').on('click', function () {
allin.fadeOut(300, function () {
fCont.fadeOut(function () {
overL.fadeOut(function () {
fCont.attr('style', '');
});
clearAll();
});
});
});
</code></pre>
<p><strong>CSS</strong></p>
<pre class="lang-css prettyprint-override"><code>html, body {
height:1000px;
width:100%;
}
* {
padding:0;
margin:0;
}
a {
text-decoration:none;
}
.overlay_p {
position:fixed;
width:100%;
z-index:10;
display:none;
min-height:100%;
background:url('http://s20.postimg.org/5c4ymoxah/image.png');
}
p.aligner {
border-radius:4px;
overflow:hidden;
box-shadow:0 3px 6px #000;
z-index:50;
height:60px;
width:60px;
margin:150px auto;
line-height:0;
border:1px solid silver;
position:relative;
padding:8px;
background:url('http://s20.postimg.org/r630mhhft/249_1.gif') center center no-repeat #fff;
display:block;
}
p.aligner img {
vertical-align:top;
}
span.close_div {
font-family:Calibri;
line-height:25px;
padding:0 10px;
right:0;
cursor:pointer;
top:0;
background:#fff;
color:#333;
position:absolute;
}
span.next_div, span.prev_div {
font-family:Calibri;
line-height:25px;
padding:0 10px;
right:0;
display:block;
text-align:center;
width:60px;
cursor:pointer;
margin-top:-13px;
top:50%;
background:#fff;
color:#333;
position:absolute;
}
span.prev_div {
left:0;
}
.pre_load {
position:fixed;
top:-2000px;
}
.thumb {
height:100px;
width:150px;
}
.hold_all {
display:none;
}
img_gallery a {
display:table;
float:left;
position:relative;
}
img_gallery a img {
float:left;
}
.click {
border:2px solid red;
}
</code></pre>
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><div class="pre_load"></div>
<div class="overlay_p">
<p class="aligner"> <span class="hold_all" id="all_here">
<span class="p_img"></span>
<span class="prev_div" id="nav">prev</span>
<span class="next_div" id="nav">next</span>
<span class="close_div">X</span>
</span>
</p>
</div>
<div class="img_gallery">
<img src="http://papermashup.com/wp-content/uploads/2009/07/gallery.png" class="thumb" alt="http://www.st-hughs.ox.ac.uk/__data/assets/image/0014/5153/Gym---Main-Room.jpg">
<img src="http://2.bp.blogspot.com/-V3ImhEBNtS4/UJRC08KGp6I/AAAAAAAAAJc/8rMMG6VIbvQ/s320/Candy.jpg" class="thumb" alt="http://2.bp.blogspot.com/-V3ImhEBNtS4/UJRC08KGp6I/AAAAAAAAAJc/8rMMG6VIbvQ/s320/Candy.jpg">
<img src="http://images.nationalgeographic.com/wpf/media-live/photos/000/201/cache/common-ancestor-all-creatures_20194_600x450.jpg" class="thumb" alt="http://images.nationalgeographic.com/wpf/media-live/photos/000/201/cache/common-ancestor-all-creatures_20194_600x450.jpg">
</div>
</code></pre>
|
[] |
[
{
"body": "\n\n<pre class=\"lang-js prettyprint-override\"><code>$(this).hasClass('next_div')\n</code></pre>\n\n<p>is usually preferred over</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$(this).attr('class')=='next_div'\n</code></pre>\n\n<p>jQuery object variables are usually prefixed with a dollar sign (<code>$</code>):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var $allin = $('span.hold_all');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T08:13:06.710",
"Id": "44977",
"Score": "0",
"body": "Thx for a comment! Will try to follow your advice!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T13:02:51.950",
"Id": "28600",
"ParentId": "28474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T19:43:49.427",
"Id": "28474",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"jquery",
"html",
"css"
],
"Title": "Optimization of a simple jQuery-powered image gallery"
}
|
28474
|
<p>It works fine, but it is slow. </p>
<p>Could anybody help make this faster?</p>
<pre><code>import itertools
from decorators import timer
from settings import MENU, CASH
class Cocktail(object):
def __init__(self, group, name, sell, count=0):
self.group = group
self.name = name
self.sell = sell
self.count = count
class Check(object):
def __init__(self, cash, menu=MENU):
self.__cash = cash
self.__cheapest_cocktail = 10000
self.__menu = self.__read_menu(menu)
self.__matrix = self.__create_matrix()
self.correct = []
def __read_menu(self, menu):
result = []
for group in menu:
key = group.keys()[0]
for cocktail in group[key]:
if self.__cheapest_cocktail > cocktail['sell']:
self.__cheapest_cocktail = cocktail['sell']
result.append(Cocktail(
key,
cocktail['name'],
cocktail['sell'],
))
return result
def __create_matrix(self):
result = []
max_count = self.__cash // self.__cheapest_cocktail
for cocktail in self.__menu:
row = []
for i in range(0, max_count):
row.append(Cocktail(
cocktail.group,
cocktail.name,
cocktail.sell,
i
))
result.append(row)
return result
def find_combinations(self):
for check in itertools.product(*self.__matrix):
if sum([(c.sell * c.count) for c in check]) == self.__cash:
self.correct.append(check)
check = Check(CASH)
check.find_combinations()
check.__matrix size 80x25
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T20:59:32.400",
"Id": "44709",
"Score": "1",
"body": "Hello, could you please add some more information about what you are trying to achieve here? Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T21:01:49.020",
"Id": "44710",
"Score": "0",
"body": "I try find all row combinations which sum elements equal any given number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:28:25.067",
"Id": "44727",
"Score": "0",
"body": "What is `check.__matrix size 80x25` after your code? Is it part of the code? Can you give a sample Input and output of your program so it can be easier to understand?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:56:50.407",
"Id": "44735",
"Score": "0",
"body": "Probably not worth an answer but I think you should have a look at http://www.youtube.com/watch?v=o9pEzgHorH0 (I have no idea how many times I've posted a link to this video on this SE)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T07:02:26.733",
"Id": "53043",
"Score": "0",
"body": "I believe you are trying to solve the knapsack problem, here is an example: http://rosettacode.org/wiki/Knapsack_Problem/Python"
}
] |
[
{
"body": "<p>Take a look at <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow\">Python Performace Tips</a> and search for list comprehension. As far as I can understand your code you can use it.</p>\n\n<p>An example would be this function.</p>\n\n<pre><code>def __create_matrix(self):\n max_count = self.__cash // self.__cheapest_cocktail\n return [ [Cocktail(cocktail.group,cocktail.name,cocktail.sell,i)\n for i in xrange(0, max_count)] for cocktail in self._menu]\n</code></pre>\n\n<p>You don't need to create a list if you are not using it elsewhere. In the <code>find_combinations</code> function you can avoid the overhead of list creation because you are only interested in the sum of the elements.</p>\n\n<pre><code>def find_combinations(self):\n for check in itertools.product(*self.__matrix):\n if sum((c.sell * c.count) for c in check) == self.__cash:\n self.correct.append(check)\n</code></pre>\n\n<p>I think there is a bug in your code. You are using a class<code>Cocktail</code> but using <code>cocktail</code> in your code. I understand they are different but I think you have messed up <strong>C</strong> with <strong>c</strong> in your code in the <code>__read_menu</code> function. It is confusing whether or not you have messed it up.</p>\n\n<p>That is all I can think of because I don't understand what the code is doing unless. Please edit your question to add sample input and output.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:46:47.130",
"Id": "28491",
"ParentId": "28477",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T20:53:31.733",
"Id": "28477",
"Score": "2",
"Tags": [
"python",
"algorithm",
"combinatorics"
],
"Title": "Find all row combinations which sum elements equal to any given number"
}
|
28477
|
<p>I have a query which selects a show from <code>anime_series</code>, then selects corresponding information from other tables (such as studio, which is stored as a SMALLINT reference to another table). The below query works as intended, but I really don't believe my code is as efficient as it can or should be.</p>
<p>The real complexity is that shows can and often do have multiple genres and studios. I'm current using <code>GROUP_CONCAT</code> on the multiple genres, studio names, and studio links, though I'm not sure this is the best method. I'm using a sub query for the next episode because I only need the first episode that hasn't aired, again, my method is probably over-complicating it.</p>
<pre><code>SELECT
anime.*,
episode.number AS episode,
episode.air_date AS ep_airdate,
station.name AS station_name,
station.link AS station_link,
GROUP_CONCAT(DISTINCT genre.name ORDER BY LOWER(genre.name)) AS genres,
GROUP_CONCAT(DISTINCT studio.name) AS studio_names,
GROUP_CONCAT(DISTINCT studio.link) AS studio_links
FROM
`anime_series` AS anime
LEFT JOIN (
SELECT
`air_date`,
`series`,
`number`
FROM
`anime_episodes`
WHERE
`air_date` > NOW()
GROUP BY `series`) episode
ON anime.id = episode.series
LEFT JOIN `anime_stations` station
ON anime.station = station.id
LEFT JOIN `anime_genre_connections`
ON anime_genre_connections.series_id = anime.id
JOIN `anime_genres` AS genre
ON anime_genre_connections.genre_id = genre.id
LEFT JOIN `anime_studio_connections`
ON anime_studio_connections.series = anime.id
JOIN `anime_studios` AS studio
ON anime_studio_connections.studio = studio.id
WHERE anime.id = 1
GROUP BY anime.id;
</code></pre>
<p>Here's some table examples (anime_series missing irrelevant columns):</p>
<pre><code>anime_series
id | station
1 | 1
anime_stations
id | name | link
1 | Something TV | http://example.com
anime_episodes
id | series | air_date | number
1 | 1 | 2013-07-09 01:00:00 | 1
2 | 1 | 2013-07-16 01:00:00 | 2
anime_genre_connections
id | series_id | genre_id
1 | 1 | 1
2 | 1 | 2
anime_genres
id | name
1 | Comedy
2 | Action
anime_studio_connections
id | series | studio
1 | 1 | 1
2 | 1 | 2
anime_studios
id | name | link
1 | Example | http://example.com
2 | Some Studio | http://example.com
</code></pre>
<p><strong>EDIT:</strong> I should also add that I'm splitting the returned columns genres, studio_names, and studio_links into arrays after the query has executed.</p>
|
[] |
[
{
"body": "<p>I would say the <code>DISTINCT</code> keywords in the following quote are superfluous. I would recommend to explicitely use <code>INNER JOIN</code> but even as it is, your <code>JOIN</code> clauses should implicitly compute that already. The only time I would use <code>DISTINCT</code> would be if I suspected that one anime had duplicate records of multiple of the same studio/genre. </p>\n\n<pre><code>GROUP_CONCAT(DISTINCT genre.name ORDER BY LOWER(genre.name)) AS genres,\nGROUP_CONCAT(DISTINCT studio.name) AS studio_names,\nGROUP_CONCAT(DISTINCT studio.link) AS studio_links\n</code></pre>\n\n<p>Your use of <code>GROUP_CONCAT()</code> should not cause much if any performance difference, as it computes that on the result set to display it differently. I'm curious about the reason you are using <code>LEFT JOIN</code> and joining a subquery, can you clarify? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T21:22:06.970",
"Id": "88500",
"Score": "0",
"body": "This question's pretty old and I've since changed it, but the subquery was to select the nearest future episode. Not too long after asking this I replaced the subquery with a normal `LEFT JOIN` with an additional `ON` clause of `AND episode.airdate > NOW()`, with a `GROUP BY anime.id` removed duplicates. The `LEFT JOINS` are on foreign rows that may not exist. I can update the question with my latest revision of the query if you'd like, assuming that's not frowned upon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T21:58:58.930",
"Id": "88504",
"Score": "2",
"body": "I think it would be better to start a new Code Review post instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T22:29:41.190",
"Id": "88508",
"Score": "0",
"body": "I may do that another time. I do appreciate your input on this, though!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T09:38:55.373",
"Id": "88550",
"Score": "0",
"body": "+1 for pointing out that `DISTINCT` is redundant. I'd go further and recommend placing `UNIQUE` constraints on the `*_connections` tables to achieve the same guarantee."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T17:19:34.837",
"Id": "51233",
"ParentId": "28478",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T21:14:01.050",
"Id": "28478",
"Score": "6",
"Tags": [
"mysql",
"sql"
],
"Title": "Optimizing a query with many joins"
}
|
28478
|
<p>I am starting out with Java programming and get limited feedback from my professor. Following is an assignment that I handed in, and just re-factored. I wanted to see if people with Java experience could give some pointers on improving how it looks. Last semester I took a C++ course so splitting sections up into public/private methods/classes/objects is pretty foreign to me. Feedback on commenting is also welcome; I'm not sure about how much I should be commenting.</p>
<p>Note: All user input is taken is as a string as per the Professor's request. Hence the <code>parseDouble</code>s flying around.</p>
<pre><code> import java.util.Scanner;
public class ReportBuilder {
static Scanner keyboard = new Scanner(System.in);
public static int numericalInputs = 7;
private static String firstName;
private static String lastName;
static String reportName;
public static void main(String[] args) {
firstName = "Empty";
lastName = "Empty";
reportName = "Empty";
System.out.println("This program will generate a report based on the input");
System.out.println("If you wish to exit enter \"-1\"");
System.out.println("Please enter your first name:");
firstName = FirstInput.main();
System.out.println(firstName + ", please enter your last name one character at a time");
System.out.println("When you are finished, type 'Stop'");
lastName = SecondInput.main();
System.out.println("Hi, " + firstName + " " + lastName + ".");
System.out.println("Enter the name of the report:");
reportName = keyboard.next();
if (reportName.equals("-1")) {
exit();
}
else {
System.out.println("Please enter seven numbers one at a time");
ThirdInputv2.main();
}
keyboard.close();
}
public static void exit() {
System.out.println("Good bye!");
System.exit(0);
}
}
public class FirstInput {
public static String main() {
String ownerName = "Empty";
ownerName = ReportBuilder.keyboard.next();
if (ownerName.equals("-1")) {
ReportBuilder.exit();
}
else {
ownerName = ownerName.replaceAll("[0-9]+ ?","");
}
return ownerName;
}
}
public class SecondInput {
private static String lastName;
private static int stringLength;
public static String main() {
lastName = "Empty";
return characterInput();
}
private static String characterInput() {
/* This method takes in the last name one character at a time then stops when instructed.
*/
String[] charArray = new String[20];
String lastInput = "None";
stringLength = -1;
for (int i = 0; i < charArray.length; i++) {
/* This loop takes in individual strings and creates an array of strings of length 1.
*/
lastInput = ReportBuilder.keyboard.next();
charArray[i] = lastInput.substring(0,1);
if (lastInput.equals("-1")) {
ReportBuilder.exit();
}
/* The validateLast method of CheckNum is called to see if the user input contains a number.
*/
else if (CheckNum.validateLast(charArray[i])) {
System.out.println("Please do not enter any numbers");
i--;
}
/* When the user enters "Stop" no more input is accepted
*/
else if (lastInput.equalsIgnoreCase("Stop")) {
stringLength = i;
break;
}
}
lastName = stringCharacters(charArray, stringLength);
return lastName;
}
private static String stringCharacters(String[] characters, int length) {
/* This method concatenates all characters
* then turns them into a single string, containing the last name.
*/
String lastName = "";
for (int i = 0; i < length; i++) {
lastName = lastName + characters[i];
}
return lastName;
}
}
public class ThirdInputv2 {
private static int numberOfInputs = ReportBuilder.numericalInputs;
private static String[] userInputString = new String[numberOfInputs];
// The following arrays are created so that each one can be fed into the grandTotal method
private static double[] arrayOfInputs = new double[numberOfInputs];
private static double[] arrayOfMaxValues = new double[numberOfInputs];
private static double[] arrayOfMinValues = new double[numberOfInputs];
private static double[] arrayOfAccumulators = new double[numberOfInputs];
private static double[] arrayOfAverages = new double[numberOfInputs];
public static void main() {
numArray();
System.out.println("");
printReport();
}
private static void numArray() {
/* This method collects each number entered by the user then stores it in an array
* After each number is entered: the max value, minimum value, average, and total are displayed
*/
int elementCounter = 1;
for(int i = 0; i < numberOfInputs; i++) {
userInputString[i] = ReportBuilder.keyboard.next();
// Program exit condition of -1:
if (userInputString[i].equals("-1")) {
ReportBuilder.exit();
}
if (i == 0); {
arrayOfAccumulators[i] = Double.parseDouble(userInputString[i]);
arrayOfAverages[i] = arrayOfAccumulators[i];
}
arrayOfInputs[i] = Double.parseDouble(userInputString[i]);
if (i > 0) {
arrayOfAccumulators[i] = arrayOfAccumulators[i-1] + arrayOfInputs[i];
arrayOfAverages[i] = arrayOfAccumulators[i-1]/elementCounter;
}
arrayOfMaxValues[i] = maxCalc(arrayOfInputs, elementCounter);
arrayOfMinValues[i] = minCalc(arrayOfInputs, elementCounter);
elementCounter++;
printMetrics(arrayOfInputs[i], arrayOfMaxValues[i], arrayOfMinValues[i],
arrayOfAccumulators[i], arrayOfAverages[i], elementCounter);
}
}
private static double maxCalc(double[] arrayNums, int counter) {
/* This method finds the greatest element in the incoming array.
*/
double highest = -1;
highest = arrayNums[0];
for(int i = 0; i<counter; i++) {
if(arrayNums[i] > highest) {
highest = arrayNums[i];
}
}
return highest;
}
private static double minCalc(double[] arrayNums, int counter) {
/* This method finds the lowest element in the incoming array.
*/
double lowest = -1;
lowest = arrayNums[0];
for (int i = 0; i<counter; i++) {
if(arrayNums[i] < lowest) {
lowest = arrayNums[i];
}
}
return lowest;
}
private static void printMetrics(double input, double max, double min, double accumulator, double average, int counter) {
/* This method prints the metrics for the latest user input value.
*/
System.out.println("The running total is " + accumulator);
System.out.println("The max value so far is " + max
+ " and the min value is " + min);
System.out.println("The average value is " + average);
if(counter < numberOfInputs) {
System.out.println("Please enter the next number:");
}
}
private static void printReport() {
/* This method prints out the final report to screen.
*/
String name = ReportBuilder.reportName;
// Header
System.out.println("Report ID: " + name);
System.out.println("Input" + "\t" + "Max" + "\t" + "Min" + "\t" + "Total" + "\t" + "Average");
System.out.println("----------------------------------------");
// Body
for (int row = 0; row < numberOfInputs; row++) {
// This loop prints out the contents of each column, row by row
System.out.println(arrayOfInputs[row] + "\t" + arrayOfMaxValues[row] + "\t" + arrayOfMinValues[row]
+ "\t" + arrayOfAccumulators[row] + "\t" + arrayOfAverages[row]);
}
// Grand Total row containing the sum of each column
System.out.println("----------------------------------------");
System.out.println(grandTotal(arrayOfInputs) + "\t" + grandTotal(arrayOfMaxValues) + "\t"
+ grandTotal(arrayOfMinValues) + "\t" + grandTotal(arrayOfAccumulators) + "\t"
+ grandTotal(arrayOfAverages) + " = Grand Totals");
}
private static double grandTotal(double[] columnArray) {
/* This method calculates the sum of all values for a given column in the report.
*/
double gTotal = columnArray[0];
for (int i = 1; i < 7; i++) {
gTotal = gTotal+ columnArray[i];
}
return gTotal;
}
}
public class CheckNum {
public static boolean validateLast(String testString) {
/* The variable isNumeric returns true if the input string contains an integer between 0 and 9
*/
boolean isNumeric;
if(testString.matches("[0-9]+")) {
isNumeric = true;
}
else {
isNumeric = false;
}
return isNumeric;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:16:04.140",
"Id": "44724",
"Score": "0",
"body": "You can read [this](http://programmers.stackexchange.com/questions/119600/beginners-guide-to-writing-comments) and [this](http://programmers.stackexchange.com/questions/173118/should-comments-say-why-the-program-is-doing-what-it-is-doing-opinion-on-a-dic) for advice about using comments. These are pretty good."
}
] |
[
{
"body": "<p>Just a few comments:</p>\n\n<ul>\n<li>in Java, comments describing methods are ususally placed right before the method declaration, not after it. Also, use <code>/** ... */</code>, so they are turned into <a href=\"http://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow\">Javadoc</a> comments.</li>\n<li>Its odd how you create separate classes for each of the input tasks, and how those classes define a <code>main</code> method. In Java, the <code>main</code> method describes the entry point to your program, like the <code>main</code> method in your first class. Calling other methods <code>main</code> may lead to confusion.</li>\n<li>Rather than having several classes with lots of static variables, try to convert those classes to simple methods of your main class, and make those variables local to those methods.</li>\n</ul>\n\n<hr>\n\n<p>Actually I did not plan on doing this, but whatever. Here's my version of the code.</p>\n\n<pre><code>import java.util.Scanner;\n\n/**\n * [describe what the program is doing]\n */\npublic class ReportBuilder {\n\n static Scanner keyboard = null;\n\n /**\n * main program flow\n */\n public static void main(String[] args) {\n keyboard = new Scanner(System.in);\n\n System.out.println(\"This program will generate a report based on the input\");\n System.out.println(\"If you wish to exit enter \\\"-1\\\"\");\n\n System.out.println(\"Please enter your first name:\");\n String firstName = getFirstName();\n\n System.out.println(firstName + \", please enter your last name one character at a time\");\n System.out.println(\"When you are finished, type 'Stop'\");\n String lastName = getLastName();\n\n System.out.println(\"Hi, \" + firstName + \" \" + lastName + \".\");\n System.out.println(\"Enter the name of the report:\");\n String reportName = readString();\n\n System.out.println(\"Please enter seven numbers one at a time\");\n double[] numbers = getNumberArray(7);\n System.out.println(\"\");\n printReport(reportName, numbers);\n\n keyboard.close(); \n }\n\n /**\n * handle exit condition each time a keyboard input is read\n */\n private static String readString() {\n String input = keyboard.next();\n if (\"-1\".equals(input)) {\n System.out.println(\"Good bye!\");\n System.exit(0);\n }\n return input;\n }\n\n private static String getFirstName() {\n String firstName = readString();\n return firstName.replaceAll(\"[0-9]+ ?\",\"\");\n }\n\n /** This method takes in the last name one character at a time then stops when instructed.\n */\n private static String getLastName() {\n String lastName = \"\";\n while (true) {\n String input = readString();\n // When the user enters \"Stop\" no more input is accepted\n if (input.equalsIgnoreCase(\"Stop\")) {\n break;\n }\n // The validateLast method of CheckNum is called to see if the user input contains a number.\n if (isNumber(input)) {\n System.out.println(\"Please do not enter any numbers\");\n }\n // add character to lastName\n lastName += input.substring(0, 1);\n }\n return lastName;\n }\n\n /** This method collects each number entered by the user then stores it in an array\n * After each number is entered: the max value, minimum value, average, and total are displayed\n */ \n private static double[] getNumberArray(int numberOfInputs) {\n double[] inputs = new double[numberOfInputs];\n double min = 9999, max = 0, sum = 0, avg = 0;\n\n for (int i = 0; i < numberOfInputs; i++) { \n String userInput = readString();\n\n if (isNumber(userInput)) {\n inputs[i] = Double.parseDouble(userInput);\n min = Math.min(min, inputs[i]);\n max = Math.max(max, inputs[i]);\n sum = sum + inputs[i];\n avg = sum / (i+1);\n\n System.out.println(\"The running total is \" + sum);\n System.out.println(\"The max value so far is \" + max\n + \" and the min value is \" + min);\n System.out.println(\"The average value is \" + avg);\n\n if (i < numberOfInputs) {\n System.out.println(\"Please enter the next number:\");\n }\n } else {\n System.out.println(\"Please enter a number!\");\n i--;\n }\n }\n return inputs;\n }\n\n /** This method prints out the final report to screen.\n */\n private static void printReport(String name, double[] numbers) {\n double min = 9999, max = 0, sum = 0, avg = 0;\n double[] mins = new double[numbers.length];\n double[] maxs = new double[numbers.length];\n double[] sums = new double[numbers.length];\n double[] avgs = new double[numbers.length];\n\n // Header\n System.out.println(\"Report ID: \" + name);\n System.out.println(\"Input\" + \"\\t\" + \"Max\" + \"\\t\" + \"Min\" + \"\\t\" + \"Total\" + \"\\t\" + \"Average\");\n System.out.println(\"----------------------------------------\");\n\n // Body\n // This loop prints out the contents of each column, row by row\n for (int i = 0; i < numbers.length; i++) {\n // okay, here's a bit of code duplication, but not that critical\n mins[i] = min = Math.min(min, numbers[i]);\n mins[i] = max = Math.max(max, numbers[i]);\n sums[i] = sum = sum + numbers[i];\n avgs[i] = avg = sum / (i+1);\n\n System.out.println(numbers[i] + \"\\t\" + max + \"\\t\" + min + \"\\t\" + sum + \"\\t\" + avg);\n }\n\n // Grand Total row containing the sum of each column\n System.out.println(\"----------------------------------------\");\n System.out.println(sum(numbers) + \"\\t\" + sum(maxs) + \"\\t\" + sum(mins) \n + \"\\t\" + sum(sums) + \"\\t\" + sum(avgs) + \" = Grand Totals\");\n }\n\n /** This method calculates the sum of all values for a given column in the report.\n */\n private static double sum(double[] nums) {\n double sum = 0;\n for (int i = 1; i < nums.length; i++) {\n sum += nums[i];\n }\n return sum;\n }\n\n /** @return true if the input string contains an integer\n */\n private static boolean isNumber(String testString) {\n return testString.matches(\"[0-9]+\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T16:35:19.023",
"Id": "44764",
"Score": "0",
"body": "Thanks for the comments. About how my classes were split up, what is a more intuitive way that I could have split up the program?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T20:30:38.743",
"Id": "44785",
"Score": "0",
"body": "@freddygv See my edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T14:32:50.907",
"Id": "44833",
"Score": "0",
"body": "Looks great, I really appreciate it. I'm surprised to only see one class, definitely need to look further into when to split them up. By the way, how come you split up the keyboard scanner by initializing it to null? I hadn't seen that before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T14:57:59.380",
"Id": "44835",
"Score": "0",
"body": "@freddygv About the Scanner: No special reason, I just wanted the main method to be \"symmetrical\". Start with creating the scanner, end with closing it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T11:57:09.960",
"Id": "28503",
"ParentId": "28479",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28503",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T22:03:32.537",
"Id": "28479",
"Score": "4",
"Tags": [
"java",
"homework"
],
"Title": "Grade report builder"
}
|
28479
|
<p><strong>Iterative</strong> functions – loop-based imperative repetitions of a process.</p>
<p><strong>Example</strong></p>
<pre><code>//iterative function calculates n!
function factorialIterative(n) {
var sum = 1;
if (n <= 1) {
return sum;
}
while (n > 1) {
sum *= n;
n -= 1;
}
return sum;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T22:50:54.187",
"Id": "28480",
"Score": "0",
"Tags": null,
"Title": null
}
|
28480
|
Iteration is the repetition of a block of statements within a computer program, usually with mutable state.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T22:50:54.187",
"Id": "28481",
"Score": "0",
"Tags": null,
"Title": null
}
|
28481
|
<p>So I came across an interesting problem awhile back, and I finally got around to solving it. Basically, it needs to allow the user to provide two words, and have them progressively splice together, like so:</p>
<pre><code>Word 1: 123
Word 2: abc
Result: 123abc
12a3bc
1a2b3c
a1b2c3
ab1c23
abc123
</code></pre>
<p>The two words provided must maintain their order as they weave between eachother, and they should be arranged so that any two letters in one word are never separated by more than one letter from the other word.</p>
<p>I half expect to learn that I over-thought the problem, but I still think it's pretty slick. I'm open to all kinds of feedback.</p>
<p>EDIT: Here's the updated version. Old version is below:</p>
<h1>!/usr/bin/ruby</h1>
<pre><code>class Array
def swap!(a,b)
self[a], self[b] = self[b], self[a]
self
end
end
class String
def phase(other)
if self.empty?
[other]
elsif other.empty?
[self]
else
@word1 = self.split("")
@word2 = other.split("")
@combined_words = []
@word2.each { |letter| @combined_words.push({:letter => nil, :word => nil}) }
@word1.each do |letter|
@combined_words.push({:letter => letter, :word => 1})
@combined_words.push({:letter => nil, :word => nil})
end
@word2.each { |letter| @combined_words.push({:letter => letter, :word => 2}) }
end
while @combined_words.include?({:letter => nil, :word => nil})
nil_loc = @combined_words.rindex{ |addr| addr[:word].nil? }.to_i
word2_subloc = @combined_words.drop(nil_loc).index{ |addr| addr[:word] == 2 }.to_i
if word2_subloc == 0
@combined_words.delete_at(nil_loc)
print "\n\n"
@combined_words.each do |addr|
if not addr[:letter].nil?
print addr[:letter]
end
end
print "\n\n"
else
@combined_words.swap!(nil_loc, word2_subloc + nil_loc)
end
end
end
end
puts "What is your first word?"
param1 = gets
puts "Cool, what is your second word?"
param2 = gets
puts param1.chomp.phase(param2.chomp)
</code></pre>
<p>Old version:</p>
<pre><code>#!/usr/bin/ruby
class Array
def swap!(a,b)
self[a], self[b] = self[b], self[a]
self
end
end
class Phaser
def initialize(word1, word2)
raise unless word1.is_a?(String) && word2.is_a?(String)
@word1 = word1.split("")
@word2 = word2.split("")
@combined_words = []
@word2.each { |letter| @combined_words.push({:letter => nil, :word => nil}) }
@word1.each { |letter|
@combined_words.push({:letter => letter, :word => 1 })
@combined_words.push({:letter => nil, :word => nil})
}
@word2.each { |letter| @combined_words.push({:letter => letter, :word => 2}) }
end
def phase
if !@combined_words.include?({:letter => nil, :word => nil})
return
else
nil_loc = @combined_words.rindex{ |addr| addr[:word].nil? }.to_i
word2_subloc = @combined_words.drop(nil_loc).index{ |addr| addr[:word] == 2 }.to_i
if word2_subloc == 0
@combined_words.delete_at(nil_loc)
print "\n\n"
@combined_words.each do |addr|
if not addr[:letter].nil?
print addr[:letter]
end
end
else
@combined_words.swap!(nil_loc, word2_subloc + nil_loc)
end
phase
end
end
end
puts "What is your first word?"
param1 = gets
puts "Cool, what is your second word?"
param2 = gets
test_phase = Phaser.new(param1.chomp, param2.chomp)
test_phase.phase
</code></pre>
|
[] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>raise unless word1.is_a?(String) && word2.is_a?(String)</code>: Don't lose a second testing types of arguments, it's the caller's responsability to get it right.</p></li>\n<li><p>Blank lines: You should be more careful with blank lines, used without consistency hinder readability severly. Here are <a href=\"https://code.google.com/p/tokland/wiki/RubyIdioms#General_formatting\" rel=\"nofollow\">my opinions</a> on this.</p></li>\n<li><p>I am tempted to write a bot that, upon finding an <code>each</code>, <code>+=</code>, <code>delete</code>, <code>insert</code>, <code>value[x] = y</code> or similar, automatically comments \"this code looks terrible because it's in imperative style, try functional\" :-) Sadly, most of the time the bot would be right. The problem is that you think about the problem in terms of <em>how</em> (do this, do that) instead of <em>what</em>, so variables are modified everywhere and it's just impossible to understand what the algorithm is doing. I've written at length about this subject, so if you're curious: <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">FP in Ruby</a>. Here the more natural approach seems a recursive functional algorithm.</p></li>\n</ul>\n\n<p>That's how I'd write it:</p>\n\n<pre><code>class String\n def interleave(other)\n if self.empty?\n [other]\n elsif other.empty?\n [self]\n else\n interleaved1 = [self[0]].product(self[1..-1].interleave(other))\n interleaved2 = [other[0]].product(self.interleave(other[1..-1]))\n (interleaved1 + interleaved2).map(&:join)\n end\n end\nend\n\np \"123\".interleave(\"abc\")\n#=> [\"123abc\", \"12a3bc\", \"12ab3c\", \"12abc3\", \"1a23bc\", \"1a2b3c\", \"1a2bc3\", \"1ab23c\", \"1ab2c3\", \"1abc23\", \"a123bc\", \"a12b3c\", \"a12bc3\", \"a1b23c\", \"a1b2c3\", \"a1bc23\", \"ab123c\", \"ab12c3\", \"ab1c23\", \"abc123\"]\n</code></pre>\n\n<p>In fact I'd implement the more generic <code>Array#interleave</code> (and go <em>Array</em> <-> <em>String</em> when needed). The changes in the implementation are minimal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T16:37:34.387",
"Id": "44765",
"Score": "0",
"body": "Thank you so much for the feedback, I'll definitely be reading those links when I get home. Just looking at your output though, your method doesn't seem to be producing the right results. For instance the 3rd element in your output is \"12ab3c\" but it should be \"1a2b3c\", which in your output doesn't occur until the 6th element"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T17:51:04.747",
"Id": "44771",
"Score": "0",
"body": "@bad_sample: I noticed your output is shorter, I create all possible interleavings. Can you add a link to the specifications on the question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T18:01:21.007",
"Id": "44862",
"Score": "0",
"body": "No link, it's just my own idea. I'll update my post to be more clear about the requireemnts"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-20T20:18:51.690",
"Id": "45194",
"Score": "0",
"body": "I made some changes and uploaded the edited version based on some of your feedback. It's still imperative style but I did implement some of your changes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-20T23:05:13.727",
"Id": "45210",
"Score": "0",
"body": "@bad_sample: What I don't understand are the specifications of the problem: which outputs do you want and which don't. For example \"1ab23c\" seems a valid interleaving of 123 and abc, why isn't in your output?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T00:51:06.577",
"Id": "45285",
"Score": "0",
"body": "I updated the specifications: The two words provided must maintain their order as they weave between each other, and they should be arranged so that any two letters in one word are never separated by more than one letter from the other word. So in your example, 1ab23c is invalid because b and c are separated by more than two letters in 123"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T12:06:50.260",
"Id": "28504",
"ParentId": "28484",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T03:45:14.133",
"Id": "28484",
"Score": "1",
"Tags": [
"ruby",
"strings",
"recursion"
],
"Title": "Ruby string splicer"
}
|
28484
|
<p>I've written a program:</p>
<pre><code>import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
/**
*
* @author Mohammad Faisal
*/
public class FileContentMatcher {
public static void main(String[] args) throws IOException {
String textToMatch = "Quick Styles gallery on";
ArrayList<String> paths = new ArrayList<String>();
String content;
int found = 0;
int notFound = 0;
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File path = new File("E:\\anchit\\temp");
File[] listOfFiles = path.listFiles(filter);
for (File file : listOfFiles) {
content = FileUtils.readFileToString(file);
if (content.contains(textToMatch)) {
//System.out.println("Found in: " + file.getAbsolutePath());
paths.add(file.getAbsolutePath());
found++;
} else {
//System.out.println("No found\n" + content);
notFound++;
}
}
for (String pth : paths) {
System.out.println(pth);
}
System.out.println("Found in " + found + " files.\nNot found in " + notFound + " files.");
}
}
</code></pre>
<p>In which I've used <a href="http://commons.apache.org/proper/commons-io/" rel="nofollow">Apache Commons IO</a> api.<br>
My actual requirement is to list all the files in the given directory which contains the search phrase <code>textToMatch</code> in minimum amount of time about 4-5 seconds, where number of files could be upto 100000. But this program takes much more time than that.<br>
So I need to optimize this code but not getting <strong>how</strong>?<br>
Is there any API which can help me? I've heard of <code>Lucene</code> but not getting how to work with it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:45:31.717",
"Id": "44732",
"Score": "2",
"body": "well, the number of files doesn't tell how many GB/TB of data you need to go through; and how many seconds does you program currently take?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:51:28.200",
"Id": "44734",
"Score": "2",
"body": "With no constraints or control over the organization of data, you are unlikely to get those levels of performance. Opening some random file takes roughly 10 ms. 10^5 X 10^-2 secs ~ 15 mins. (Performance is known to be hard to predict, but do not expect to get anything less than several minutes without doing something different.) \n\nConsider also using full-text indexes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T07:02:02.477",
"Id": "44736",
"Score": "0",
"body": "@abuzittingillifirca: well I've no idea of full-text indexes. How do it works?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T11:00:29.720",
"Id": "44747",
"Score": "2",
"body": "[Lucene](http://en.wikipedia.org/wiki/Lucene) is the index&search Java library which I hear most about, but I've never used it. MS SQL Server (I've used its full-text indexes) (and probably other RDBMSs) ship with full-text indexing and search. There probably are simpler solutions probably but it totally depends on what your constraints are [Is mirroring the directory in Ramdisk and doing a grep an acceptable solution, where would we know?]. And that deep an analysis is beyond the scope of Code Review SE. You may try [Programmers SE](http://programmers.stackexchange.com/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T11:05:54.290",
"Id": "44748",
"Score": "0",
"body": "@abuzittingillifirca: but as you can see in the program, I'm not using any RDBMS. I've to make search in `.txt` files"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T11:09:19.773",
"Id": "44749",
"Score": "1",
"body": "I would suggest you would, if you could ;) You should really try http://programmers.stackexchange.com for some other ideas; since your problem size, as @dnozay and I have pointed out, requires more than simple optimizations to achieve the performance you expect from common systems."
}
] |
[
{
"body": "<p>A few tips :</p>\n\n<ul>\n<li>Instead of reading the entire file into memory, use a <code>Reader</code>, reading only a small buffer at a time, to check for possible matches. This will improve memory usage, and avoid reading the entire file if the <code>textToMatch</code> is found.</li>\n<li>Separate the code that loops over the files, from the code that checks a file. Use multiple threads that check files. This is an ideal candidate for the <a href=\"http://java.dzone.com/articles/producer-consumer-pattern\" rel=\"nofollow\">producer-consumer pattern</a> (using a blocking queue) with one producer, and multiple consumers.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T08:22:19.973",
"Id": "28498",
"ParentId": "28490",
"Score": "1"
}
},
{
"body": "<p>As <a href=\"https://codereview.stackexchange.com/questions/28490/searching-word-or-phrase-among-files#comment44734_28490\">poined out in the comments</a>, your current approach might be too slow for your goal of \"about 4-5 seconds\". Depending on what's your actual use case, using an index might indeed be a good idea. This is similar to how internet search engines do it.</p>\n\n<p>To create the index:</p>\n\n<ul>\n<li>create a map <code>Map<String, List<File>></code> for holding the association of search terms to files</li>\n<li>go through all your files, and for each word in each file, add that file to the list corresponding to that word in your index map</li>\n<li>you might want to skip common words, such as \"a\", \"and\", \"the\", etc., or you could even apply a <a href=\"http://en.wikipedia.org/wiki/Stemming\" rel=\"nofollow noreferrer\">stemmer</a> to drastically reduce the variability in words</li>\n</ul>\n\n<p>Once you've created the index (which could take quite some time), you just have to look up the search word in that index to get the list of files that contain the word (or a linguistic variant of it, if you used a stemmer).</p>\n\n<p>As said before, the applicability of this approach depends heavily on your actual use case. If the files contain genetic sequences and you are searching a certain pattern, this probably won't help much. Even if you are searching for some complex phrase this might not work, as you'd have to add each possible (sub) phrase to the index. But if you are looking for individual words in ordinary text files (or HTML or the like) this might work.</p>\n\n<p><em>Update:</em> Since you seem to indeed search for complex phrases, you could try the following: </p>\n\n<ul>\n<li>create the index, as desribed above, optionally using a stemmer</li>\n<li>search for each word in your phrase (or the stemmed version thereof) in your index</li>\n<li>for each file that, according to your index, contains <em>all</em> the words, do a full-text search for the original phrase</li>\n</ul>\n\n<p>Finally, if this still does not cut it, you could also create indexes for <a href=\"http://en.wikipedia.org/wiki/N-gram\" rel=\"nofollow noreferrer\">word bigrams or even trigrams</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T08:56:01.233",
"Id": "28499",
"ParentId": "28490",
"Score": "4"
}
},
{
"body": "<p>If you are hitting a bottleneck in terms of sheer hardware, you may move to a distributed model using <a href=\"http://en.wikipedia.org/wiki/MapReduce\" rel=\"nofollow\"><code>MapReduce</code></a>. It works just like a distributed <code>awk</code> / <code>grep</code> conceptually. Enter big words like <code>Big Data</code>, which really is trading compute time on one machine (expensive one most of the time) with less compute time on more machines (commodity hardware most of the time) by following <code>divide-and-conquer</code> principles. </p>\n\n<p>Here is a <a href=\"http://hadoop.apache.org/docs/stable/mapred_tutorial.html\" rel=\"nofollow\">link to a <code>Hadoop</code> tutorial</a>.</p>\n\n<p>I wouldn't take this route unless you have identified that your solution is going to hit the limits. But consider this:</p>\n\n<ul>\n<li>what happens if your files grow over time?</li>\n<li>what happens if your have more files over time?</li>\n</ul>\n\n<p>Distributed systems scale horizontally (number of machines) whereas a single machine does not scale well vertically (single machine specs ~ $$$).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T16:32:17.443",
"Id": "28514",
"ParentId": "28490",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28499",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:31:52.753",
"Id": "28490",
"Score": "1",
"Tags": [
"java",
"optimization",
"search"
],
"Title": "searching word or phrase among files"
}
|
28490
|
<p>I am was writing a practice program in javascript and it turned out to work quite alright, however I am not entirely happy with the code. I can't shake the feeling that there is a lot of code which doesn't have to be there, I feel that it can be improved.</p>
<p>The idea of the program is basically, you have a selector, each time you make a choice and hit submit a new set of choices are offered. The choices of the user are stored in an object.</p>
<p>I am interested to know if there is a way to make this code more efficient.</p>
<p>Here is the entire source code (+ the html part)</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Dynamic Selector</title>
</head>
<body>
<select id="select">
</select>
<button onclick="updateObject()">Submit</button>
</body>
</html>
<script>
var select = document.getElementById("select");
var choice = { time: "", category: "", complexity: "" };
var time = ["15", "30", "60", "60+"];
var category = ["knowedge", "experimenting", "self-iprovement", "cooking", "health"];
var complexity = [1, 2, 3, 4];
var coef = 0;
//creates the children for the time choices
function setChoices() {
if (coef === 0) {
for (var i = 0; i < time.length; i++) {
var node = document.createElement('option');
node.value = time[i].toString();
node.innerHTML = time[i];
select.appendChild(node);
}
} else if (coef === 1) {
for (var i = 0; i < category.length; i++) {
var node = document.createElement('option');
node.value = category[i].toString();
node.innerHTML = category[i];
select.appendChild(node);
}
} else if (coef === 2) {
for (var i = 0; i < complexity.length; i++) {
var node = document.createElement('option');
node.value = complexity[i].toString();
node.innerHTML = complexity[i];
select.appendChild(node);
}
}
}
function updateObject() {
if (coef === 0) {
choice.time = select.value;
console.log(choice.time);
coef++;
removeChildren();
setChoices();
} else if (coef === 1) {
choice.category = select.value;
coef++;
removeChildren();
setChoices();
} else if (coef === 2) {
choice.complexity === select.value;
printObject();
setChoices();
}
}
//removes the children of the "select" element
function removeChildren() {
while (select.firstChild) {
select.removeChild(select.firstChild);
}
}
function printObject() {
console.log("foobarr");
}
removeChildren();
setChoices();
</script>
</code></pre>
|
[] |
[
{
"body": "<p>Applying the good ol' <strong>DRY</strong> principle and by adding <code>coef</code> as a parameter, we'd get something like :</p>\n\n<pre><code>function setChoices(coef) {\n var relevantArray = (coef === 0) ? time :\n (coef === 1) ? category :\n complexity;\n for (var i = 0; i < relevantArray.length; i++) {\n var node = document.createElement('option');\n node.value = relevantArray[i].toString();\n node.innerHTML = relevantArray[i];\n select.appendChild(node);\n }\n}\n\nfunction updateObject() {\n for (var coef = 0; coef<3; coef++)\n {\n ((coef === 0) ? choice.time :\n (coef === 1) ? choice.category :\n choice.complexity) = select.value;\n removeChildren();\n setChoices(coef);\n }\n}\n</code></pre>\n\n<p>(Also, I have changed a few things which I assumed to be wrong, for instance, <code>updateObject</code> did not call <code>setChoices</code> with <code>coef=0</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T07:35:35.800",
"Id": "44738",
"Score": "0",
"body": "Just to be sure I understand this: You are creating a new array(and using it later on) containing the data of one of the 3 arrays, depending on the value of 'coef' right ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T07:54:53.547",
"Id": "44739",
"Score": "0",
"body": "That's the idea indeed but it shouldn't create a new array, it should just decide at the beginning the one we are going to use afterwards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T07:31:58.060",
"Id": "28495",
"ParentId": "28492",
"Score": "2"
}
},
{
"body": "<p>The most obvious change I would recommend is to refactor the for loop in <code>setChoices</code>. You're using the same code three times.</p>\n\n<p>Keep your code <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>.</p>\n\n<p>I'd write it somehow like this:</p>\n\n<pre><code>// It's better not to rely on globals but to pass them to your functions\n// (easier to test)\nfunction updateSelectWithItems(select, arrItems) {\n // It's always a good habit to validate your arguments\n if (!arrItems || arrItems.length === 0) {\n throw new Error(\"ArgumentNullException: 'arrItems' is null or has no items.\")\n }\n\n if (!select) {\n throw new Error(\"ArgumentNullException: 'select' is null.\")\n }\n\n for (var i = 0; i < arrItems.length; i++) {\n var node = document.createElement('option');\n node.value = arrItems[i].toString();\n node.innerHTML = arrItems[i];\n select.appendChild(node);\n }\n}\n\n//creates the children for the time choices\nfunction setChoices() {\n switch (coef) {\n case 0:\n updateSelectWithItems(mySelect, time);\n break;\n case 1:\n updateSelectWithItems(mySelect, category);\n break;\n case 2:\n updateSelectWithItems(mySelect, complexity);\n break;\n default:\n // shouldn't happen\n throw new Error(\"'coef' has a wrong value.\");\n break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T07:34:38.583",
"Id": "28496",
"ParentId": "28492",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28495",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T06:59:42.107",
"Id": "28492",
"Score": "2",
"Tags": [
"javascript",
"html5"
],
"Title": "Having less code for the current program"
}
|
28492
|
<p>I (ruby beginner) have a performance issue with the following ruby code. The idea is to aggregate a CSV into a smaller, better-to-handle file and calculating the average of some values. Basically the same code in groovy runs about 30 times faster. And I can't believe that Ruby is that slow! ;-)</p>
<p>Some background:
The file consists of lines like this (it is an output file of a JMeter performance test):</p>
<pre><code>timeStamp|elapsed|label|responseCode|responseMessage|threadName|dataType|success|failureMessage|bytes|Latency
2013-05-17_16:30:11.261|4779|Session_Cookie|200|OK|Thread-Gruppe 1-1|text|true||21647|4739
</code></pre>
<p>All values of e.g. a certain minute are selected by looking at the first 16 characters of the timestamp:</p>
<pre><code>2013-05-17_16:30:11.261 => 2013-05-17_16:30
</code></pre>
<p>I wanted to collect values in buckets/slices which are represented by the shortened timestamp and the label (third column). The value of the second column ("elapsed") is summed up.</p>
<pre><code>require 'csv'
require_relative 'slice'
# Parameters: <precision> <input file> [<output file>]
precision = ARGV[0].to_i
input_file = ARGV[1]
output_file = ARGV[2]
time_slices = Hash.new
CSV.foreach(input_file, {:col_sep => '|', :headers => :first_line}) do |row|
current_time_slice = row['timeStamp'][0, precision]
if time_slices[current_time_slice] == nil
time_slices[current_time_slice] = Hash.new
end
if time_slices[current_time_slice][row['label']]
time_slices[current_time_slice][row['label']].put_line(row)
else
new_slice = Slice.new(current_time_slice, row['label'])
new_slice.put_line(row)
time_slices[current_time_slice][row['label']] = new_slice
end
end
out = File.new(output_file, 'a')
out.puts 'time|label|elapsed_average'
time_slices.values.each do |time_slice|
time_slice.values.each do |slice|
out.puts slice.aggregated_row
end
end
</code></pre>
<p>The slice class looks like this:</p>
<pre><code>class Slice
attr_accessor :slice_timestamp, :slice_label, :lines, :sum, :count
def initialize(slice_timestamp, slice_label)
@slice_timestamp = slice_timestamp
@slice_label = slice_label
@count = 0
@sum = 0
end
def put_line(line)
@sum = @sum + line[1].to_i
@count = @count + 1
end
def average
@sum / @count
end
def aggregated_row
@slice_timestamp + '|' + @slice_label + '|' + average.to_s
end
end
</code></pre>
<p>I think that I chose a quite straightforward and non-optimized approach, but still - the same approach is <em>much</em> faster in Groovy. What can be the reason for that?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T20:11:01.343",
"Id": "44784",
"Score": "0",
"body": "You don't post the groovy code nor the input file (or did I miss the links?) so we cannot compare. Anyway, I don't see anything out of the usual in your code (regarding efficiency, it could be indeed rewritten in a more idiomatic way). Ruby is slow, a very slow language, although 30x vs another dynamic language seems too much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T07:37:23.430",
"Id": "44808",
"Score": "0",
"body": "I put the Groovy code in this gist: https://gist.github.com/marvin9000/6006367 (it evolved a little bit in the meantime, but I think the basic idea is still the same). If you want to run it on some testdata, you can download it here: http://www.filehosting.org/file/details/435358/input.csv.tgz"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T07:43:31.813",
"Id": "44810",
"Score": "0",
"body": "One more addition: I ran both scripts on the sample data again and the difference was \"only\" about 3x (6 sec vs. 23 sec). It was more significant on larger files (400+ MB), which I don't want to upload here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T07:47:25.160",
"Id": "44811",
"Score": "0",
"body": "For the record - ruby version: ruby 1.9.3p286 (2012-10-12 revision 37165) [x86_64-darwin11.4.2], Groovy Version: 2.1.3 JVM: 1.6.0_51 Vendor: Apple Inc. OS: Mac OS X"
}
] |
[
{
"body": "<pre><code>if time_slices[current_time_slice] == nil\n time_slices[current_time_slice] = Hash.new\nend\n</code></pre>\n\n<p>It's more idomatic to write</p>\n\n<pre><code>time_slices[current_time_slice] ||= {}\n</code></pre>\n\n<p>In general don't use <code>Hash.new</code> if you can just write <code>{}</code>. You can rid of that statement alltogether though if you declare the <code>time_slices</code> variable with</p>\n\n<pre><code>time_slices = Hash.new { |h, k| h[k] = {} }\n</code></pre>\n\n<p>instead of <code>time_slices = Hash.new</code>.</p>\n\n<pre><code>if time_slices[current_time_slice][row['label']]\n time_slices[current_time_slice][row['label']].put_line(row)\nelse\n new_slice = Slice.new(current_time_slice, row['label'])\n new_slice.put_line(row)\n time_slices[current_time_slice][row['label']] = new_slice\nend\n</code></pre>\n\n<p>Also</p>\n\n<pre><code>time_slices[current_time_slice][row['label']] ||= Slice.new ...\n</code></pre>\n\n<p>is more idiomatic here. But there is more to say here:</p>\n\n<ol>\n<li>Don't forget that Ruby is an interpreted language in principle (although the byte compiler of Ruby 1.9 relativizes that), so don't repeat complex references like <code>time_slices[current_time_slice][row['label']]</code>. But that's not only an performance but even more so an readability issue.</li>\n<li>Why does a <code>Slice</code> instance has to know the <code>current_time_slice</code> and <code>label</code>? That's completely redundant, since that information is already in the Hash. Get rid of that.</li>\n</ol>\n\n<p>Considering this I would write the loop like this:</p>\n\n<pre><code>time_slices = Hash.new { |h, k| h[k] = Hash.new { |h, k| h[k] = Slice.new } }\n\nCSV.foreach(input_file, col_sep: '|', headers: :first_line) do |row|\n current_time_slice = row['timeStamp'][0, precision]\n time_slices[current_time_slice][row['label']].put_line(row)\nend\n</code></pre>\n\n<p>Of course you then have to modify your output loop a little</p>\n\n<pre><code>time_slices.each do |slice_timestamp, time_slice|\n time_slice.each do |label, slice|\n out.puts [slice_timestamp, label, slice.average].join('|')\n end\nend\n</code></pre>\n\n<p>So you don't need the <code>Slice#aggregated_row</code> method anymore. But that's a good idea anyway: e.g. why does <code>Slice</code> has to know about your pipe separator? That's not a good separation of concerns.</p>\n\n<p>Note that I avoid the <code>+</code> operator here. That would create a new String instance with every <code>+</code> call. Alternatively you can also try <code><<</code>, but be aware that this modifies the leftmost string (but oftentimes that doesn't matter).</p>\n\n<p>In contrast there is no penalty in using <code>+</code> in groovy normally, because modern JVMs are using StringBuilder under the hood for it when they see fit. But in Ruby you still should be aware of its implications.</p>\n\n<pre><code>attr_accessor :slice_timestamp, :slice_label, :lines, :sum, :count\n</code></pre>\n\n<p>Why are you declaring these accessors? They are never used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-10T08:24:24.543",
"Id": "35116",
"ParentId": "28501",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T09:13:03.397",
"Id": "28501",
"Score": "1",
"Tags": [
"ruby",
"performance",
"csv"
],
"Title": "Ruby CSV reading performance problems"
}
|
28501
|
<p>I have a <a href="https://github.com/regebro/svg.path">module in Python for dealing with SVG paths</a>. One of the problems with this is that the <a href="http://www.w3.org/TR/SVG/">SVG spec</a> is obsessed with saving characters to a pointless extent. As such, this path is valid:</p>
<pre><code>"M3.4E-34-2.2e56L23-34z"
</code></pre>
<p>And should be parsed as follows:</p>
<pre><code>"M", "3.4E-34", "-2.2e56", "L", "23", "-34", "z"
</code></pre>
<p>As you see, anything non-ambiguous is allowed, including separating two numbers only by a minus sign, as long as that minus-sign is not preceded by an "E" or an "e", in which case it should be interpreted as an exponent of the first number. Letters are commands (except "E" and "e" of course), and both comma and any sort of whitespace is allowed as separators.</p>
<p>My module currently uses a rather ugly way of tokenizing the SVG path by multiple string replacements and then a split:</p>
<pre><code>COMMANDS = set('MmZzLlHhVvCcSsQqTtAa')
def _tokenize_path_replace(pathdef):
# First handle negative exponents:
pathdef = pathdef.replace('e-', 'NEGEXP').replace('E-', 'NEGEXP')
# Commas and minus-signs are separators, just like spaces.
pathdef = pathdef.replace(',', ' ').replace('-', ' -')
pathdef = pathdef.replace('NEGEXP', 'e-')
# Commands are allowed without spaces around. Let's insert spaces so it's
# easier to split later.
for c in COMMANDS:
pathdef = pathdef.replace(c, ' %s ' % c)
# Split the path into elements
return pathdef.split()
</code></pre>
<p>This in fact is doing a total of 23 string replacements on the path, and this is easy, but seems like it should be slow. I tried doing this other ways, but to my surprise they were all slower. I did a character by character tokenizer, which took around 30-40% more time. A user of the module also suggested a regex:</p>
<pre><code>import re
TOKEN_RE = re.compile("[MmZzLlHhVvCcSsQqTtAa]|[-+]?[0-9]*\.?[0-9]+(?:[eE]
[-+]?[0-9]+)?")
def _tokenize_path_replace(pathdef):
return TOKEN_RE.findall(pathdef)
</code></pre>
<p>To my surprise this was also slower than doing 23 string replacements, although just 20-30%.</p>
<p>One thing that could speed up this is if the two expressions in the regex could be merged to one, but I can't find a way of doing that. If some regex guru can, that would improve things.</p>
<p>Any other way of making a speedy parsing of SVG paths that I haven't though about would also be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T10:26:14.583",
"Id": "44746",
"Score": "1",
"body": "It's not just you having trouble with slow parsing of paths: [`svgwrite` has the same problem](https://bitbucket.org/mozman/svgwrite/issue/7/parsing-of-paths-is-very-time-consuming)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T11:55:17.037",
"Id": "44751",
"Score": "0",
"body": "Since you're asking us to try to improve the speed of your code, it's important to have a standard test suite for comparison. Can you post or link to your test suite?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T12:45:34.800",
"Id": "44752",
"Score": "1",
"body": "Maybe `re.split('([MmZzLlHhVvCcSsQqTtAa])', \"M3.4E-34-2.2e56L23-34z\")` and then parsing the coordinates separately (with a smaller regex) would speed things up?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T16:21:11.677",
"Id": "44845",
"Score": "0",
"body": "@GarethRees: The module includes a full test suite. The test_parsing.py is the testcases for parsing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T16:53:03.263",
"Id": "44850",
"Score": "0",
"body": "@VedranŠego: Well, geez, I was gonna prove to you that it wasn't gonna help because you can't do a smaller regex. It helped anyway. :-)"
}
] |
[
{
"body": "<p>With cred to @VedranŠego for kicking me in the right direction, my current solution is simply to split the two regex-parts into separate parsings, the first one a split (instead of a match) and the second one a findall on the floats (because doing a split is near impossible, as - both should and should not be a separator, depending on context).:</p>\n\n<pre><code>import re\n\nCOMMANDS = set('MmZzLlHhVvCcSsQqTtAa')\nCOMMAND_RE = re.compile(\"([MmZzLlHhVvCcSsQqTtAa])\")\nFLOAT_RE = re.compile(\"[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?\")\n\ndef _tokenize_path(pathdef):\n for x in COMMAND_RE.split(pathdef):\n if x in COMMANDS:\n yield x\n for token in FLOAT_RE.findall(x):\n yield token\n</code></pre>\n\n<p>I times this with:</p>\n\n<pre><code>from timeit import timeit\nnum = 1000000\n\na = timeit(\"_tokenize_path('M-3.4e38 3.4E+38L-3.4E-38,3.4e-38')\", \n \"from svg.path.parser import _tokenize_path\", number=num)\nb = timeit(\"_tokenize_path('M600,350 l 50,-25 a25,25 -30 0,1 50,-25 l 50,-25 a25,50 -30 0,1 50,-25 l 50,-25 a25,75 -30 0,1 50,-25 l 50,-25 a25,100 -30 0,1 50,-25 l 50,-25')\",\n \"from svg.path.parser import _tokenize_path\", number=num)\nc = timeit(\"_tokenize_path('M3.4E-34-2.2e56L23-34z')\",\n \"from svg.path.parser import _tokenize_path\", number=num)\n\nprint a + b + c\n</code></pre>\n\n<p>And it runs an astonishing 23 times faster than the \"replace\" based tokenizer above, and 30 times faster then the regex based tokenizer, even though it essentially does the same thing. :-) I really did not think it would be faster to run this \"dual\" regex in two separate steps, and I have tried other \"two-stage\" variations before that was even slower, but this time I arrived at the right combination.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T18:58:15.647",
"Id": "44874",
"Score": "0",
"body": "I'm glad I've helped. The splitter is a simple regex, by which I mean that there is no quantifiers `*` and `+`, so it runs straightforward. These quantifiers make regexes slow because they often have to try-and-fail before doing a match. With this approach, you've significantly shortened the strings being matched with the more complicated (meaning it has quantifiers) `FLOAT_RE`. Doing one match on a long string often takes much more time than doing n similar matches on strings of approximately 1/n length of a long string. Although, I have to admit I didn't expect this much of a speedup."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T14:08:09.260",
"Id": "44922",
"Score": "2",
"body": "FWIW, the regex is slightly wrong. If you look at the definition of `fractional-constant` you'll see that it permits `digit-sequence \".\"` (i.e. `[0-9]+\\.`), which isn't compatible with the regex `[0-9]*\\.?[0-9]+`. That portion should be replaced with e.g. `(?:[0-9]*\\.?[0-9]+|[0-9]+\\.?)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-17T18:11:04.817",
"Id": "44929",
"Score": "0",
"body": "Also, my reading of the BNF is that the following is a valid path: `M.4.4.4.4z`. The regex-based approach in this answer handles it correctly, but the multiple-replace approach of the question doesn't."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T17:07:34.677",
"Id": "28565",
"ParentId": "28502",
"Score": "3"
}
},
{
"body": "<p>Actually, the problem at hand might not be ideally addressed by replacements or regular expressions. The way how SVG path data is designed, seems to make going through the path string character by character more efficient.</p>\n\n<p>There are essentially five different cases one has to examine. This is a direct consequence of the BNF of SVG Paths (<a href=\"http://www.w3.org/TR/SVG/paths.html#PathDataBNF\" rel=\"nofollow\">http://www.w3.org/TR/SVG/paths.html#PathDataBNF</a>). When looping over the string, the next character could be</p>\n\n<ol>\n<li>a digit or one of the letters 'e' and 'E',</li>\n<li>a comma or a whitespace,</li>\n<li>a command letter, i.e. one of the letters 'MmZzLlHhVvCcSsQqTtAa',</li>\n<li>the dot '.',</li>\n<li>a sign, i.e. '+' or '-'.</li>\n</ol>\n\n<p>In these five cases the following things are done:</p>\n\n<ol>\n<li>We are inside a number and can simply append the character to the current entity.</li>\n<li>We have encountered a separator and if not already done in the last step, a new empty entity is started.</li>\n<li>We found a command. This command is added as a separate entity and a new empty one is started.</li>\n<li>In this case it could be that we were already inside a float (if the flag 'float' is True). Then the dot starts a new entity. Otherwise the dot indicates that we are now in a float. The flag 'float' is then set to True and we stay in the current entity.</li>\n<li>In this case it could be that the sign is the one of an exponent. Then it is just appended to the current entity. Otherwise a new one is started.</li>\n</ol>\n\n<p>A code example might look like this:</p>\n\n<pre><code>def parse_path(path_data):\n digit_exp = '0123456789eE'\n comma_wsp = ', \\t\\n\\r\\f\\v'\n drawto_command = 'MmZzLlHhVvCcSsQqTtAa'\n sign = '+-'\n exponent = 'eE'\n float = False\n entity = ''\n for char in path_data:\n if char in digit_exp:\n entity += char\n elif char in comma_wsp and entity:\n yield entity\n float = False\n entity = ''\n elif char in drawto_command:\n if entity:\n yield entity\n float = False\n entity = ''\n yield char\n elif char == '.':\n if float:\n yield entity\n entity = '.'\n else:\n entity += '.'\n float = True\n elif char in sign:\n if entity and entity[-1] not in exponent:\n yield entity\n float = False\n entity = char\n else:\n entity += char\n if entity:\n yield entity\n</code></pre>\n\n<p>I've run some tests with the above code and it was mostly twice as fast as the regexp version.</p>\n\n<p>In addition, due to the clear cases it is relativly easy to understand what's going on here. This is also helpful for finding and correcting errors.</p>\n\n<p>The problem in the regexp version Peter Taylor pointed to is not severe in most cases. But it might actually lead to wrong parsing. If one considers for example the coordinate <code>2.e2</code>, the regexp version leads to the two coordinates <code>'2','2'</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-29T13:49:12.183",
"Id": "159918",
"Score": "0",
"body": "I did try that, but stopped because if the complexity. Although it might be twice as fast, compare it to the 6 lines in my code above. :-)\n\nBut if the current speed would be an issue (which I don't think), then it's good to know that I can try this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-30T15:25:32.127",
"Id": "160154",
"Score": "0",
"body": "Of course by using reg exps, you can safe many lines of code because all the different comparisions one has to make are included in one line of reg exp. But this makes this one line quite complicated. And the complexity is just hidden inside the re module you have to import. With a module built from my code you could import it and do parsing just with 2 lines of code ;-) So what's more complex in total is perhaps a matter of the point of view.\nBut notice that the reg exp in your code may lead to wrong parsing and correcting this would probably make it more complicated and slow it down."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-18T05:33:31.373",
"Id": "224214",
"Score": "0",
"body": "Really wants to upvote this answer as it detailed the flow of processing svg path. The article by itself is a treasure to understand SVG. Though I prefer the regex solution better as it is neat and clean. Anyway thanks for your great effort Peter."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-26T17:32:57.293",
"Id": "88051",
"ParentId": "28502",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "28565",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T09:34:16.747",
"Id": "28502",
"Score": "6",
"Tags": [
"python",
"performance",
"parsing",
"regex",
"svg"
],
"Title": "SVG path parsing"
}
|
28502
|
<p>I need to improve this by using <code>switch</code> statement in which I want to set the text and <code>setFullScreen</code>. Is there any more elegant way to implement this?</p>
<pre><code>final String change[] =
{
"Full Screen", "Exit Full Screen"
};
final MenuItem fullScreen = MenuItemBuilder.create().text(change[0]).build();
fullScreen.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
fullScreen.setText((fullScreen.getText().equals(change[0])) ? change[1] : change[0]);
if (fullScreen.getText().equals(change[0]))
{
primaryStage.setFullScreen(false);
}
else
{
primaryStage.setFullScreen(true);
}
}
});
view.getItems().add(fullScreen);
</code></pre>
|
[] |
[
{
"body": "<p>This can be made a lot more elegant with the State Pattern.</p>\n\n<p>We'll introduce an enum for the two states :</p>\n\n<pre><code>private static enum Mode {\n FULLSCREEN(\"Exit Full Screen\"), NORMAL(\"Full Screen\");\n\n private final String toggleActionText;\n\n private Mode(String text) {\n this.toggleActionText = text;\n }\n\n public String getToggleActionText() {\n return toggleActionText;\n }\n\n public boolean isFullScreen() {\n return FULLSCREEN == this;\n }\n\n public Mode other() {\n return isFullScreen() ? NORMAL : FULLSCREEN;\n }\n}\n</code></pre>\n\n<p>Then, having added a properly initialized <code>Mode</code> field to the class, you can simplify your code to this :</p>\n\n<pre><code>final MenuItem fullScreen = MenuItemBuilder.create().text(mode.getToggleActionText()).build();\n\nfullScreen.setOnAction(new EventHandler<ActionEvent>()\n{\n @Override\n public void handle(ActionEvent e)\n {\n mode = mode.other();\n fullScreen.setText(mode.getToggleActionText());\n primaryStage.setFullScreen(mode.isFullScreen());\n }\n});\n\nview.getItems().add(fullScreen);\n</code></pre>\n\n<p>As you can see, it is a lot simpler to delegate the state dependent behavior to the <code>Mode</code> instance than to use an <code>if</code> whenever you have state dependent behavior.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T17:30:22.687",
"Id": "28516",
"ParentId": "28505",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T11:50:30.200",
"Id": "28505",
"Score": "2",
"Tags": [
"java",
"javafx"
],
"Title": "Menu items to enter and exit full-screen mode in JavaFX"
}
|
28505
|
<p>I'm new to Perl, learning on my own. I've wrote many scripts (utilities) for myself but never posted them online. I would really appreciate any feedback on this script before I post it on a <a href="https://bbs.archlinux.org/viewtopic.php?id=56646" rel="nofollow">forum</a>.</p>
<p>The script takes list of files names on command line, writes the name list in tmp file and opens it with vi(m). After user is done renaming, it reads new names from tmp file and renames files accordingly. Script can also process symlinks, where it lists and renames the target file name and also updates the symlink to point to renamed file afterwards.</p>
<pre><code>#!/usr/bin/perl -w
use strict;
use Getopt::Std;
use File::Temp qw( tempfile );
use File::Basename qw( basename dirname );
# HANDLING CMD ARGS
$Getopt::Std::STANDARD_HELP_VERSION = 1;
my $usage = \&main::HELP_MESSAGE;
my %opts;
sub main::VERSION_MESSAGE {
print "virename v0.1\n";
}
sub main::HELP_MESSAGE {
print << "EOF";
Usage:\n virename [OPTIONS] [file_names]
OPTIONS
-s act on symlink target (also update symlink)
-v be verbose
--help pirnt help and exit
--version version
EOF
}
if (@ARGV) {
getopts( 'vs', \%opts ) or $usage->();
}
else {
print "Not enough arguments!\n\n";
$usage->();
exit 1;
}
my ( @names, @new_names, %symlinks );
if ( $opts{s} ) {
for my $name (@ARGV) {
if ( my $target = readlink $name ) {
my $target_name = basename $target;
$symlinks{$target_name} = { 'symlink', $name, 'target', $target };
push @names, $target_name;
}
else {
push @names, $name;
}
}
}
else {
@names = @ARGV;
}
die "Nothing to rename!\n" unless @names;
my ( $tmp, $tmp_name ) = tempfile(); # Tmp file
print {$tmp} join "\n", @names; # Writing names to tmp file
if ( !system "vim $tmp_name 2>/dev/null" ) {
}
elsif ( !system 'vi', $tmp_name ) {
}
else { exit; }
seek $tmp, 0, 0;
chomp( @new_names = <$tmp> ); # Reading new names from tmp file
unlink $tmp_name; # Removing tmp file
exit if @names != @new_names;
#Renaming
for ( 0 .. $#names ) {
my ( $new_name, $old_name );
my $is_symlink = exists $symlinks{ $names[$_] };
if ( $opts{s} && $is_symlink ) {
$old_name = $symlinks{ $names[$_] }->{target};
$new_name = dirname($old_name) . q{/} . $new_names[$_];
}
else {
$old_name = $names[$_];
$new_name = $new_names[$_];
}
if ( -e $new_name ) { #Skip if file already exists
print "'$new_name' already exits!\n" if $opts{v};
}
elsif ( rename $old_name => $new_name ) {
if ( $opts{s} && $is_symlink ) {
my $symlink = $symlinks{ $names[$_] }->{symlink};
unlink $symlink; # Removing old symlink
symlink $new_name => $symlink # Creating new symlink
or warn "symlink: $!\n";
print "'$symlink': '$old_name' => '$new_name'" if $opts{v};
}
else {
print "'$old_name' => '$new_name'\n" if $opts{v};
}
}
else {
warn "failed to rename $old_name to $new_name: $!\n";
}
}
__END__
</code></pre>
|
[] |
[
{
"body": "<p>That is a nice and useful script, although a few things could be improved.</p>\n\n<ul>\n<li><p>You specified the <code>-w</code> command line option. You should instead <code>use warnings</code>. While the result is identical for such a small script, the <code>warnings</code> pragma allows for fine-grained control of warnings.</p></li>\n<li><p>You do not have to specify <code>main::</code> when defining subroutines. When no package is specified, then you are already in the package <code>main</code>. Reduce the syntactic clutter, and simply write <code>sub VERSION_MESSAGE { ... }</code>.</p></li>\n<li><p>In <code>HELP_MESSAGE</code>, I'd use the heredoc-marker differently: I'd prefer it to be <code><<'EOF'</code>. Rationale: Double quotes allow interpolation of variables. For a reader of the code, this increases the cognitive load: where do you interpolate something? Nowhere. If I specify the marker with single quotes, I can just skip to the end marker; knowing that nothing interesting happens in between.</p>\n\n<p>I'd also rather not put a space between the <code><<</code> and the <code>'END'</code>. The heredoc-marker is syntactically one single token, and you can't specify the marker with other quoting operators like <code><< q(END)</code>.</p>\n\n<p>As we now use single quotes, no escapes are available, so your <code>\\n</code> won't work any more. No problem, just use a literal newline:</p>\n\n<pre><code><<'EOF';\nUsage:\n virename [OPTIONS] [file_names]\n...\nEOF\n</code></pre>\n\n<p>for the same effect.</p></li>\n<li><p>Why do you put the <code>HELP_MESSAGE</code> sub into the scalar <code>$usage</code>? You can invoke the sub directly like <code>HELP_MESSAGE()</code> instead of the much more complicated <code>$usage->()</code>.</p></li>\n<li><p><code>sub VERSION_MESSAGE { print \"virename v0.1\\n\"; }</code>. Nope. The documentation for Getopt::Std may not make this perfectly clear, but your <code>VERSION_MESSAGE</code> sub receives some paramaters. The first of these is the filehandle you are expected to print to. Error messages or information that is not the primary output of your script should generally not go to <code>STDOUT</code>, but to <code>STDERR</code>. So we will rewrite that to</p>\n\n<pre><code># callback for Getopt::Std\nsub VERSION_MESSAGE {\n my ($handle) = @_;\n print {$handle} \"virename v0.1\\n\";\n}\n</code></pre>\n\n<p>Notice also the comment that tells a reader why you put this seemingly unused sub here and why you chose a name in offending uppercase.</p>\n\n<p>The same considerations hold for <code>HELP_MESSAGE</code>, which should be rewritten as well.</p></li>\n<li><p><code>print \"Not enough arguments!\\n\\n\"; ...; exit 1</code>. Nope.</p>\n\n<p>First, what you are expressing is very close to <code>die</code>, so we'll rather use that. The above rant about how error messages shouldn't go to <code>STDOUT</code> applies here as well, but using <code>die</code> fixes that. But we would like to print out the usage without having to call a sub that prints it out. The solution is to put this message into a variable, e.g.</p>\n\n<pre><code>my $help_message = <<'EOF';\n...\nEOF\n\n# callback for Getopt::Std\nsub HELP_MESSAGE {\n my ($handle) = @_;\n print {$handle} $help_message;\n}\n</code></pre>\n\n<p>Now we can say</p>\n\n<pre><code>@ARGV or die \"Not enough arguments!\\n\\n\", $help_message;\ngetopts 'vs', \\%opts or die $help_message;\n</code></pre>\n\n<p>When an unknown flag is among the arguments and <code>getopts</code> returns a false value, I not only print the usage (as you do), but also terminate execution. I think this is preferable than continuing with possibly wrong arguments.</p></li>\n<li><p>A comment here and there would not hurt. E.g.</p>\n\n<pre><code>if ( $opts{s} ) {\n # If a file is a symlink, we need to find the actual target\n # and put that into @names instead.\n ...\n}\n</code></pre>\n\n<p>A short paragraph telling a reader what you are about to do can really help.</p></li>\n<li><p>What the hell? </p>\n\n<pre><code>if ( !system \"vim $tmp_name 2>/dev/null\" ) {\n}\nelsif ( !system 'vi', $tmp_name ) {\n}\nelse { exit; }\n</code></pre>\n\n<p>I do understand what you are trying to express, but it isn't exactly obvious. There is a nicer way to do that. Also, don't fail with a normal exit code when there clearly was an error, and don't exit abnormally without an error message!</p>\n\n<pre><code>system(\"vim $tmp_name 2>/dev/null\") == 0\n or system(\"vi\", $tmp_name) == 0\n or die \"Can't launch vim or vi\\n\";\n</code></pre>\n\n<p>Note: Don't write code that isn't self-explanatory without a comment. Also, If you're using empty bodies for an <code>if</code> in Perl, this should raise an eyebrow.</p></li>\n<li><p><code>chomp( @new_names = <$tmp> ); # Reading new names from tmp file</code></p>\n\n<p>Thankyou for the comment, but that code is fairly self-explaining. Ergo, this comment is unneccessary.</p>\n\n<p>As this is the first occasion where the <code>@new_names</code> variable is used, it should also be declared here, and not further upwards. This would work as well:</p>\n\n<pre><code>chomp( my @new_names = <$tmp> );\n</code></pre>\n\n<p>… altough others may not like embedding declarations inside an argument list. Then:</p>\n\n<pre><code>my @new_names = <$tmp>;\nchomp @new_names;\n</code></pre></li>\n<li><p><code>exit if @names != @new_names;</code>. I covered this already: Don't exit abnormally without reflecting this in the error code, and don't abort execution without an error message telling the user what went wrong:</p>\n\n<pre><code>@names == @new_names or die \"Number of filenames changed. Did you delete a line?\\n\";\n</code></pre></li>\n<li><p>In the loop, you could consider changing the definition of <code>$is_symlink</code> to</p>\n\n<pre><code>my $is_symlink = $opts{s} && exists $symlinks{ $names[$_] };\n</code></pre>\n\n<p>This reduced a <em>tiny</em> bit of code duplicatation.</p></li>\n<li><p>The following <code>if/elsif/else</code> confuses two unrelated topics: Loop control and error handling.</p>\n\n<pre><code>if ( -e $new_name ) { #Skip if file already exists\n print \"'$new_name' already exits!\\n\" if $opts{v};\n} elsif ( rename $old_name => $new_name ) {\n ...\n} else {\n warn ...;\n}\n</code></pre>\n\n<p>If you want to move on to the next iteration of the loop, just use <code>next</code>:</p>\n\n<pre><code>if ( -e $new_name ) {\n print ... if $opst{$v};\n next;\n}\n</code></pre>\n\n<p>I am not sure if what you are printing is considered regular output, or an error message. I assume it is normal output, so my <code>STDERR</code> ranting does not apply here.</p>\n\n<p>Your <code>rename</code> and the correspondig error handling (in form of a <code>warn</code>) are seperated by a dozen lines. I would move them closer together:</p>\n\n<pre><code>rename $old_name => $new_name or do {\n warn ...;\n next;\n};\n...;\n</code></pre></li>\n<li><p>The <code>__END__</code> marker is generally useless, unless you keep some non-code resources in the same file, or when you pipe the code to the <code>perl</code> interpreter. All this marker does is to stop the parsing of the source file.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T18:15:52.103",
"Id": "28578",
"ParentId": "28506",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28578",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T13:17:11.660",
"Id": "28506",
"Score": "3",
"Tags": [
"perl"
],
"Title": "Perl script to rename multiple files with vi(m)"
}
|
28506
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.